Commit cd7a7e18 by 苗权威

8.10

parent 0bfe5351
......@@ -12,6 +12,7 @@
<module name="ruoqi" />
<module name="spirit" />
<module name="third_party_load" />
<module name="tts_offline" />
<module name="tts_service" />
<module name="xiaoai" />
<module name="xiaodu" />
......@@ -33,6 +34,7 @@
<module name="ruoqi" options="-parameters" />
<module name="spirit" options="-parameters -extdirs /usr/local/intellij/workplace/smartbox/spirit/src/main/resources/lib" />
<module name="third_party_load" options="-parameters" />
<module name="tts_offline" options="-parameters" />
<module name="tts_service" options="-parameters" />
<module name="xiaoai" options="-parameters" />
<module name="xiaodu" options="-parameters" />
......
......@@ -7,6 +7,7 @@
<file url="file://$PROJECT_DIR$/ruoqi" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/spirit" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/third_party_load" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/tts_offline" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/tts_service" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/xiaoai" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/xiaodu" charset="UTF-8" />
......
......@@ -26,6 +26,7 @@
<option value="$PROJECT_DIR$/third_party_load/pom.xml" />
<option value="$PROJECT_DIR$/xiaoduhome/pom.xml" />
<option value="$PROJECT_DIR$/tts_service/pom.xml" />
<option value="$PROJECT_DIR$/tts_offline/pom.xml" />
</list>
</option>
</component>
......
......@@ -80,13 +80,13 @@
<!--<version>2.2.0.RELEASE</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>com.baidu.bot</groupId>-->
<!--<artifactId>baidu-sdk</artifactId>-->
<!--<version>1.0.0</version>-->
<!--<scope>system</scope>-->
<!--<systemPath>${project.basedir}/src/main/resources/static/bot-sdk-1.2.0.jar</systemPath>-->
<!--</dependency>-->
<dependency>
<groupId>com.baidu.bot</groupId>
<artifactId>baidu-sdk</artifactId>
<version>1.0.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/static/bot-sdk-1.2.0.jar</systemPath>
</dependency>
</dependencies>
<build>
......
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/src/test/**
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
### VS Code ###
.vscode/
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.Properties;
public class MavenWrapperDownloader {
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL =
"https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: : " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
# TODO classpath?
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
wget "$jarUrl" -O "$wrapperJarPath"
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
curl -o "$wrapperJarPath" "$jarUrl"
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
echo Found %WRAPPER_JAR%
) else (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"
echo Finished downloading %WRAPPER_JAR%
)
@REM End of extension
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>ai.qiwu.com</groupId>
<artifactId>tts_offline</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>tts_offline</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>2.1.6.RELEASE</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
</dependencies>
<build>
<finalName>tts-offline</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package ai.qiwu.com.tts_offline;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TtsOfflineApplication {
public static void main(String[] args) {
SpringApplication.run(TtsOfflineApplication.class, args);
}
}
package ai.qiwu.com.tts_offline.common;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
/**
* @author 苗权威
* @dateTime 19-8-2 上午9:51
*/
@Slf4j
public class CallPython {
private static final String AUDIO_FILE = Config.getProperty("change_sound_path");
// private static final String INTERPRETER = getPythonInterpreter();
private static final String COMBINE_FILE = "";
public static String changeSound(String wav_filename, Double volume, Double speed, Double pitch, String filename) {
String command = ChangeSound.changeSound(wav_filename, volume, speed, pitch, filename);
String result = processUtilInJava(command);
if ("1".equals(result)) {
if (!TTSUtils.doesFileExist(filename)) {
log.error("检测到mp3文件不存在:{}", filename);
result = "0";
}
}
return result;
}
public static String changeSoundByPython(String wav_filename, String volume, String speed, String pitch, String filename) throws IOException {
String[] args = {"以后要用时再替换", AUDIO_FILE, wav_filename, volume, speed, pitch, filename};
// log.info("wav file:{}, vlo:{},speed:{}, pitch:{}", wav_filename, volume, speed, pitch);
return processUtil(args);
}
public static String combine(List<String> file_ls, String tmp_audio_name) throws IOException {
StringBuilder builder = new StringBuilder();
for (String file : file_ls) builder.append(file).append(",");
String fileList = builder.toString().substring(0, builder.length()-1);
String[] args = {"以后要用时再替换", COMBINE_FILE, fileList, tmp_audio_name};
return processUtil(args);
}
private static String getPythonInterpreter() {
String interpreter = processUtil(new String[]{"pipenv run which python"});
//log.info("获取的python解释器位置:{}", interpreter);
return interpreter;
}
private static String processUtilInJava(String arg) {
final StringBuilder successResult = new StringBuilder();
final StringBuilder failResult = new StringBuilder();
Process process = null;
try {
process = Runtime.getRuntime().exec(arg);
final InputStream inputStream = process.getInputStream();
final InputStream errorStream = process.getErrorStream();
new Thread(() -> {
String line;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));){
while ((line = reader.readLine()) != null) {
successResult.append(line);
}
} catch (Exception e) {
log.error("读取Process输入流出错:{}",e.toString());
}
}).start();
new Thread(() -> {
String line;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream));){
while ((line = reader.readLine()) != null) {
failResult.append(line);
}
} catch (Exception e) {
log.error("读取Process error流出错:{}",e.toString());
}
}).start();
process.waitFor();
process.destroy();
} catch (Exception e) {
try {
if (process != null) {
process.getInputStream().close();
process.getErrorStream().close();
process.getOutputStream().close();
}
} catch (Exception e1) {
log.error("关闭Process的流出错:{}",e1.toString());
}
}
if (successResult.length() == 0) return "1";
else {
log.error("打印Process的错误流信息:{}", failResult.toString());
return null;
}
}
private static String processUtil(String[] args) {
final StringBuilder successResult = new StringBuilder();
final StringBuilder failResult = new StringBuilder();
Process process = null;
try {
process = Runtime.getRuntime().exec(args);
final InputStream inputStream = process.getInputStream();
final InputStream errorStream = process.getErrorStream();
new Thread(() -> {
String line;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));){
while ((line = reader.readLine()) != null) {
successResult.append(line);
}
} catch (Exception e) {
log.error("读取Process输入流出错:{}",e.toString());
}
}).start();
new Thread(() -> {
String line;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream));){
while ((line = reader.readLine()) != null) {
failResult.append(line);
}
} catch (Exception e) {
log.error("读取Process error流出错:{}",e.toString());
}
}).start();
process.waitFor();
process.destroy();
} catch (Exception e) {
try {
if (process != null) {
process.getInputStream().close();
process.getErrorStream().close();
process.getOutputStream().close();
}
} catch (Exception e1) {
log.error("关闭Process的流出错:{}",e1.toString());
}
}
if (successResult.length() != 0) return successResult.toString();
else {
log.error("打印Process的错误流信息:{}", failResult.toString());
return null;
}
}
}
package ai.qiwu.com.tts_offline.common;
import ai.qiwu.com.tts_offline.pojo.sound.Call;
import ai.qiwu.com.tts_offline.pojo.sound.Compand;
import ai.qiwu.com.tts_offline.pojo.sound.TempoAndPitch;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ChangeSound {
private static final List<String> TYPES = Arrays.asList("amplitude", "power", "dB");
private static final List<String> OPT_FLAG = Arrays.asList("l", "m", "s");
private static final List<String> DEFAULT_DB_LIST = Arrays.asList("-70", "-60", "-20");;
private static final List<String> DB_LIST = Arrays.asList("-50","-115","-40","-10","-30","-7","-20","-5","-10","-3","0","-3");
private static final String OFOPTS = "-C 32";
private static void compand(Compand compand, List<String> selfCommand) {
List<String> dbList = compand.getDbList();
if (CollectionUtils.isEmpty(dbList)) {
dbList = DEFAULT_DB_LIST;
}
String dbArgs = StringUtils.join(dbList.toArray(), ",");
String softKnee = (compand.getSoftKnee() == null ? 6 : compand.getSoftKnee())+":";
String attack = compand.getAttack() == null ? "0.2" : compand.getAttack();
String decay = compand.getDecay() == null ? "1" : compand.getDecay();
selfCommand.add("compand");
selfCommand.add(String.format("%s,%s", attack, decay));
selfCommand.add(softKnee+dbArgs);
if (compand.getGain() != null) selfCommand.add(compand.getGain());
if (compand.getInitialVolumeDb() != null) selfCommand.add(compand.getInitialVolumeDb());
if (compand.getDelay() != null) selfCommand.add(compand.getDelay());
}
private static void limiter(Double gain, List<String> selfCommand) {
selfCommand.add("gain");
selfCommand.add("-l");
selfCommand.add(gain == null ? "3.0" : gain.toString());
}
private static void vol(Double gain, String type, String limitGain, List<String> selfCommand) {
selfCommand.add("vol");
selfCommand.add(gain.toString());
if (type == null) type = "dB";
if (TYPES.contains(type)) selfCommand.add(type);
else throw new IllegalArgumentException("Type has to be dB, amplitude or power");
if (limitGain != null) selfCommand.add(limitGain);
}
private static void tempo(TempoAndPitch tempo, List<String> selfCommand) {
selfCommand.add("tempo");
if (tempo.getUseTree() != null && tempo.getUseTree()) selfCommand.add("-q");
if (OPT_FLAG.contains(tempo.getOptFlag())) selfCommand.add("-"+tempo.getOptFlag());
selfCommand.add(tempo.getFactor().toString());
if (tempo.getSegment() != null) selfCommand.add(tempo.getSegment());
if (tempo.getSearch() != null) selfCommand.add(tempo.getSearch());
if (tempo.getOverlap() != null) selfCommand.add(tempo.getOverlap());
}
private static void pitch(TempoAndPitch pitch, List<String> selfCommand) {
selfCommand.add("pitch");
if (pitch.getUseTree() != null && pitch.getUseTree()) selfCommand.add("-q");
selfCommand.add(pitch.getShift().toString());
if (pitch.getSegment() != null) selfCommand.add(pitch.getSegment());
if (pitch.getSearch() != null) selfCommand.add(pitch.getSearch());
if (pitch.getOptFlag() != null) selfCommand.add(pitch.getOverlap());
}
private static String call(Call call, List<String> selfCommand) {
List<String> cmdLs = new ArrayList<>();
cmdLs.add("sox");
if (call.getGopts() != null) TTSUtils.shlexSplit(call.getGopts(), cmdLs);
if (call.getIfopts() != null) TTSUtils.shlexSplit(call.getIfopts(), cmdLs);
cmdLs.add(call.getSrc());
if (call.getOfopts() != null) TTSUtils.shlexSplit(call.getOfopts(), cmdLs);
cmdLs.add(call.getDst());
if (!selfCommand.isEmpty()) cmdLs.addAll(selfCommand);
return StringUtils.join(cmdLs, " ");
}
public static String changeSound(String wavFile, Double volume, Double speed, Double pitch, String outFile) {
ArrayList<String> selfCommand = new ArrayList<>();
volume = volume == null? 0 : volume;
speed = speed == null? 1 : speed;
pitch = pitch == null? 0 : pitch;
if (speed > 6) speed = 6.0;
else if (speed < 0.25) speed = 0.25;
if (speed != 1.0) {
TempoAndPitch tempo = new TempoAndPitch();
tempo.setFactor(speed);
tempo(tempo, selfCommand);
}
if (pitch != 0) {
TempoAndPitch pitchIns = new TempoAndPitch();
pitchIns.setShift(pitch*100);
pitch(pitchIns, selfCommand);
}
if (volume > 0) {
limiter(volume, selfCommand);
Compand compand = new Compand("0", "0.8", "0.01", DB_LIST, "2");
compand(compand, selfCommand);
}else if (volume < 0) {
vol(volume, null, null, selfCommand);
}
Call call = new Call(wavFile, outFile, OFOPTS);
return call(call, selfCommand);
}
public static void main(String[] args) {
System.out.println(Double.parseDouble("0.0") != 0);
}
}
package ai.qiwu.com.tts_offline.common;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
/**
* @author 苗权威
* @dateTime 19-7-30 下午2:40
*/
@Slf4j
public class Config {
private static Properties properties;
static {
String filename = "OfflineConfig.properties";
properties = new Properties();
try {
properties.load(new InputStreamReader(Config.class.getClassLoader().getResourceAsStream(filename), StandardCharsets.UTF_8));
} catch (Exception e) {
log.error("获取配置文件对象出错:{}", e.toString());
System.exit(1);
}
}
public static String getProperty(String key) {
String value = properties.getProperty(key.trim());
if (StringUtils.isBlank(value)) return null;
return value.trim();
}
public static String getProperty(String key, String defaultValue) {
String value = properties.getProperty(key.trim());
if (StringUtils.isBlank(value)) return defaultValue;
return value.trim();
}
}
package ai.qiwu.com.tts_service.common;
package ai.qiwu.com.tts_offline.common;
import lombok.Getter;
import lombok.Setter;
......@@ -20,8 +20,5 @@ public class OfflineConfig {
private String short_audio_dir;
private String letter_audio_dir;
private String test_text;
private String mysql_host;
private String mysql_user;
private String mysql_password;
private String models_threads;
}
package ai.qiwu.com.tts_service.common;
package ai.qiwu.com.tts_offline.common;
import ai.qiwu.com.tts_service.pojo.MP3Response;
import ai.qiwu.com.tts_service.pojo.offline.OfflineOnlineCacheResponse;
import ai.qiwu.com.tts_offline.pojo.offline.OfflineOnlineCacheResponse;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
......
package ai.qiwu.com.tts_offline.common;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.DigestUtils;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.Normalizer;
import java.util.Base64;
import java.util.Enumeration;
import java.util.List;
/**
* @author 苗权威
* @dateTime 19-7-30 下午5:39
*/
@Slf4j
public class TTSUtils {
private static final String STRIP = " /'\"";
public static boolean deleteFile(File file) {
if (!file.exists()) return false;
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) deleteFile(f);
}
return file.delete();
}
public static boolean makedir(String path) {
File file = new File(path);
boolean createDirResult = false;
if (!file.exists() || file.isFile()) {
createDirResult = file.mkdirs();
}
// log.info("要创建的文件夹路径:{}", path);
return createDirResult;
}
public static boolean createFile(String path) throws IOException {
File file = new File(path);
boolean createResult = false;
if (!file.exists() || file.isDirectory()) {
createResult = file.createNewFile();
}
return createResult;
}
public static void shlexSplit(String command, List<String> list) {
char[] arr = command.toCharArray();
int pre = 0, last = 0;
for (char c: arr) {
if (c == ' ') {
if (last >0 && arr[last-1] != ' ') {
list.add(command.substring(pre, last));
}
pre = last+1;
}
last++;
}
if (last != pre) list.add(command.substring(pre, last));
System.out.println(list);
}
public static File createFileReturnIts(String path) throws IOException {
File file = new File(path);
if (!file.exists() || file.isDirectory()) {
if (!file.createNewFile()) return null;
}
return file;
}
public static boolean createFile(String dir, String fileName) {
try {
makedir(dir);
} catch (Exception e) {
log.error("创建目录:{}失败", dir);
return false;
}
String file = buildMP3Filename(fileName);
String filePath = StringUtils.join(new String[]{dir, file}, File.separator);
boolean createFileResult;
try {
createFileResult = createFile(filePath);
} catch (Exception e) {
log.error("创建文件:{}出错:{}", fileName,e.toString());
return false;
}
if (!createFileResult) {
log.error("创建文件:{}失败", fileName);
}
return createFileResult;
}
public static String buildMP3Filename(String filename) {
String file = DigestUtils.md5DigestAsHex(filename.getBytes(StandardCharsets.UTF_8));
file = StringUtils.join(new String[]{file, "mp3"}, ".");
return file;
}
public static String buildWavFilename(String filename) {
String file = DigestUtils.md5DigestAsHex(filename.getBytes(StandardCharsets.UTF_8));
file = StringUtils.join(new String[]{file, "wav"}, ".");
return file;
}
public static String pythonlistToStr(List<String> file_ls) {
StringBuilder builder = new StringBuilder("['");
for (String str : file_ls) {
builder.append(str).append("', '");
}
String bStr = builder.toString();
String res = bStr.substring(0, bStr.length()-3)+"]";
return buildMP3Filename(res);
}
public static boolean doesFileExist(String filePath) {
File file = new File(filePath);
return file.exists();
}
public static boolean doesChangeSoundSuccess(List<String> filePathList) {
boolean result = true;
if (StringUtils.endsWith(filePathList.get(0), ".b64")) {
for (String path : filePathList) {
if (!doesFileExist(path.substring(0, path.length()-4))) {
result = false;
break;
}
}
} else {
for (String path : filePathList) {
if (!doesFileExist(path)) {
result = false;
break;
}
}
}
return result;
}
public static void cpContent(String src, String dest) {
try (BufferedInputStream input = new BufferedInputStream(new FileInputStream(new File(src)));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(dest))))){
byte[] buffer = new byte[input.available()];
StringBuilder builder = new StringBuilder();
builder.append("data:audio/mp3;base64,");
input.read(buffer);
builder.append(new String(Base64.getEncoder().encode(buffer),Charset.forName("utf-8")));
writer.write(builder.toString());
writer.flush();
} catch (Exception e) {
log.error("转移文件内容出错:{}", e.toString());
}
}
public static String readAllFile(String path) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(new File(path)))){
StringBuilder builder = new StringBuilder();
String str;
while ((str = reader.readLine()) != null) {
builder.append(str);
}
return builder.toString();
}
}
public static String pythonStrip(String s) {
char[] chars = s.toCharArray();
int pre = 0, post = s.length()-1;
while (pre <= post && STRIP.contains(chars[pre]+"")) {
pre++;
}
while (post > pre && STRIP.contains(chars[post]+"")) {
post--;
}
return s.substring(pre, post+1);
}
public static String secure_fileName(String filename) {
filename = Normalizer.normalize(filename, Normalizer.Form.NFKD);
for (String sep : new String[]{"\\\\", "/", "\\.\\."}) {
filename = filename.replaceAll(sep, " ");
}
filename = StringUtils.join(filename.split(" "), "_");
return filename;
}
public static void combineMp3File(List<String> filePathList, String targetFilepath)
throws IOException {
try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(new File(targetFilepath)));){
AudioEnumeration<InputStream> audioEnumeration = new AudioEnumeration<>();
for (String filepath : filePathList) {
// if (filepath.equals(Config.getProperty("third_party_tts_text", "third_party_tts"))) {
// continue;
// }
audioEnumeration.add(new FileInputStream(new File(filepath)));
}
SequenceInputStream sequenceInputStream= new SequenceInputStream(audioEnumeration);
byte[] buf = new byte[1024];
int ln;
while ((ln = sequenceInputStream.read(buf)) != -1) {
outputStream.write(buf, 0, ln);
}
outputStream.flush();
sequenceInputStream.close();
}
}
public static void combineMp3UseJava(List<String> filePathList, String targetFilepath) throws IOException, UnsupportedAudioFileException {
AudioFileFormat aff = AudioSystem.getAudioFileFormat(new File(filePathList.get(0)));
AudioEnumeration<AudioInputStream> enumeration = new AudioEnumeration<>();
long ln = 0;
for (String filepath : filePathList) {
AudioInputStream stream = AudioSystem.getAudioInputStream(new File(filepath));
ln += stream.getFrameLength();
enumeration.add(stream);
}
SequenceInputStream sequence = new SequenceInputStream(enumeration);
AudioSystem.write(new AudioInputStream(sequence, aff.getFormat(), ln), aff.getType(), new File(targetFilepath));
sequence.close();
}
static class AudioNode<T> {
private T value;
private AudioNode<T> next;
AudioNode(T value) {
this.value = value;
}
}
static class AudioEnumeration<T> implements Enumeration<T> {
private AudioNode<T> head;
private AudioNode<T> tail;
AudioEnumeration() {
head = tail = new AudioNode<>(null);
}
void add(T stream) {
tail.next = new AudioNode<>(stream);
tail = tail.next;
}
@Override
public boolean hasMoreElements() {
return head != tail;
}
@Override
public T nextElement() {
T result = head.next.value;
head = head.next;
return result;
}
}
public static void main(String[] args) {
String s = "abcdefg";
System.out.println(new String(Base64.getEncoder().encode(s.getBytes()),Charset.forName("utf-8")));
String s1 = new String(Base64.getEncoder().encode("a".getBytes()));
String s2 = new String(Base64.getEncoder().encode("bcdefg".getBytes()));
System.out.println(s1+s2);
}
}
package ai.qiwu.com.tts_service.controller;
package ai.qiwu.com.tts_offline.controller;
import ai.qiwu.com.tts_service.pojo.offline.OfflineOnlineCacheRequest;
import ai.qiwu.com.tts_service.pojo.offline.SpeakersApi;
import ai.qiwu.com.tts_service.service.offline.OfflineService;
import org.aspectj.lang.annotation.Before;
import ai.qiwu.com.tts_offline.pojo.offline.OfflineOnlineCacheRequest;
import ai.qiwu.com.tts_offline.pojo.offline.SpeakersApi;
import ai.qiwu.com.tts_offline.service.OfflineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
......@@ -13,6 +12,7 @@ import javax.servlet.http.HttpServletResponse;
* @author 苗权威
* @dateTime 19-8-3 下午3:45
*/
@CrossOrigin
@RestController
public class OfflineController {
......@@ -23,11 +23,6 @@ public class OfflineController {
this.offlineService = offlineService;
}
@Before(value = "speakers_api() || online_cache()")
public void before() {
}
@GetMapping("/synthesize")
public void speakers_api(@RequestParam(required = false) String person, @RequestParam(required = false) String tone,
@RequestParam(required = false) String server, @RequestParam(required = false) String text,
......@@ -46,7 +41,7 @@ public class OfflineController {
}
@PutMapping("/synthesize")
public void speakers_api(HttpServletResponse response, @RequestBody SpeakersApi api) {
public void speakers(@RequestBody SpeakersApi api, HttpServletResponse response) {
offlineService.speakers_api(api, response, "PUT");
}
......
package ai.qiwu.com.tts_service.pojo.offline;
package ai.qiwu.com.tts_offline.pojo.offline;
import lombok.Getter;
import lombok.Setter;
......
package ai.qiwu.com.tts_service.pojo.offline;
package ai.qiwu.com.tts_offline.pojo.offline;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Getter;
......
package ai.qiwu.com.tts_service.pojo.offline;
package ai.qiwu.com.tts_offline.pojo.offline;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
......
package ai.qiwu.com.tts_offline.pojo.sound;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-8-9 上午9:50
*/
@Getter
@Setter
@ToString
public class Call {
private String src;
private String dst;
private String gopts;
private String ifopts;
private String ofopts;
public Call() {
}
public Call(String src, String dst, String ofopts) {
this.src = src;
this.dst = dst;
this.ofopts = ofopts;
}
}
package ai.qiwu.com.tts_offline.pojo.sound;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
@Getter
@Setter
@ToString
public class Compand {
private String attack;
private String decay;
private String softKnee;
private List<String> dbList;
private String gain;
private String initialVolumeDb;
private String delay;
public Compand() {
}
public Compand(String attack, String decay, String softKnee, List<String> dbList, String gain) {
this.attack = attack;
this.decay = decay;
this.softKnee = softKnee;
this.dbList = dbList;
this.gain = gain;
}
}
package ai.qiwu.com.tts_offline.pojo.sound;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class TempoAndPitch {
private Double factor;
private Boolean useTree;
private String optFlag;
private String segment;
private String search;
private String overlap;
private Double shift;
}
package ai.qiwu.com.tts_service.service.offline;
package ai.qiwu.com.tts_offline.service;
import ai.qiwu.com.tts_service.common.CallPython;
import ai.qiwu.com.tts_service.common.OfflineConfig;
import ai.qiwu.com.tts_service.common.OfflineServiceUtil;
import ai.qiwu.com.tts_service.common.TTSUtils;
import ai.qiwu.com.tts_service.pojo.offline.OfflineOnlineCacheRequest;
import ai.qiwu.com.tts_service.pojo.offline.OfflineOnlineCacheResponse;
import ai.qiwu.com.tts_service.pojo.offline.SpeakersApi;
import ai.qiwu.com.tts_offline.common.CallPython;
import ai.qiwu.com.tts_offline.common.OfflineConfig;
import ai.qiwu.com.tts_offline.common.OfflineServiceUtil;
import ai.qiwu.com.tts_offline.common.TTSUtils;
import ai.qiwu.com.tts_offline.pojo.offline.OfflineOnlineCacheRequest;
import ai.qiwu.com.tts_offline.pojo.offline.OfflineOnlineCacheResponse;
import ai.qiwu.com.tts_offline.pojo.offline.SpeakersApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -14,7 +14,6 @@ import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
/**
* @author 苗权威
......@@ -31,6 +30,13 @@ public class OfflineService {
this.offlineConfig = offlineConfig;
}
/**
* 根据请求信息找到对应的wav文件,路径是servername/botname/person/mood/xxx.wav.
* 文件存在,若format字段等与wav则返回该wav文件的内容,否则返回servername/botname/person/mood/xxx.mp3文件内容
* @param request
* @param response
* @param requestMethod
*/
public void speakers_api(SpeakersApi request, HttpServletResponse response, String requestMethod) {
String person = request.getPerson();
String mood = null;
......@@ -38,12 +44,15 @@ public class OfflineService {
mood = request.getTone();
}
String server_name = request.getServer();
// text 不能为空
String text = request.getText();
if (StringUtils.isBlank(text)) {
log.info("text is empty");
//log.info("text is empty");
response.setStatus(404);
return;
}
// 若text等与"这是一段测试文本,请听下音效,选择你认为合适的一套声音",
// 则将server_name置空,这将导致botname为空
if (offlineConfig.getTest_text().equals(text)) {
server_name = null;
}
......@@ -57,8 +66,8 @@ public class OfflineService {
if (str != null) builder.append(str).append(File.separator);
}
String wavfilepath = builder.append(filename).toString();
log.info("OfflineService,51 row: filepath:{}", wavfilepath);
if (!TTSUtils.doesFileExist(wavfilepath)) {
//log.info("filepath:{}", wavfilepath);
if (TTSUtils.doesFileExist(wavfilepath)) {
if ("wav".equals(request.getFormat())) {
OfflineServiceUtil.speakersApiFile(response, wavfilepath, "audio/wav");
return;
......@@ -66,39 +75,56 @@ public class OfflineService {
String mp3Filepath = wavfilepath.replace(".wav", ".mp3");
if (!TTSUtils.doesFileExist(mp3Filepath) || StringUtils.isNotBlank(request.getChange())
|| requestMethod.equals("PUT")) {
String callResult;
try {
CallPython.changeSound(wavfilepath, volume, speed, pitch, mp3Filepath);
callResult = CallPython.changeSound(wavfilepath, Double.parseDouble(volume),
Double.parseDouble(speed), Double.parseDouble(pitch), mp3Filepath);
} catch (Exception e) {
log.info("OfflineService#speakers_api:调用changeSound方法生成mp3文件出错:{}", e.toString());
log.error("OfflineService#speakers_api:调用changeSound方法生成mp3文件出错:{}", e.toString());
response.setStatus(555);
return;
}
if (callResult == null || "0".equals(callResult)) {
log.error("调用python代码change_sound失败");
response.setStatus(555);
return;
}
OfflineServiceUtil.speakersApiFile(response, mp3Filepath, "audio/mp3");
return;
}
OfflineServiceUtil.speakersApiFile(response, mp3Filepath, "audio/mp3");
}else {
response.setStatus(404);
}
}
/**
* 删除offline/servername/botname目录
* @param request
* @param response
*/
public void online_cache(OfflineOnlineCacheRequest request, HttpServletResponse response) {
//servername, botname不能为空
String serverName = request.getServer();
String botname = null;
if (StringUtils.isNotBlank(serverName)) {
botname = request.getBotname();
if (StringUtils.isBlank(serverName)) {
OfflineServiceUtil.onlineCacheResponse(response, new OfflineOnlineCacheResponse(401, "server name should not be empty"), 401);
return;
}
String botname = request.getBotname();
if (StringUtils.isBlank(botname)) {
OfflineServiceUtil.onlineCacheResponse(response, new OfflineOnlineCacheResponse(401, "no botname"), 401);
return;
}
StringBuilder builder = new StringBuilder("offline").append(File.separator);
if (StringUtils.isNotBlank(serverName)) builder.append(serverName).append(File.separator);
if (StringUtils.isNotBlank(botname)) builder.append(botname);
String botDir = builder.toString();
if (TTSUtils.doesFileExist(botDir)) {
String botDir = StringUtils.join(new String[]{"offline", serverName, botname}, File.separator);
try {
TTSUtils.deleteFile(new File(botDir));
log.info("删除目录{}成功", botDir);
if (TTSUtils.doesFileExist(botDir)) {
log.error("目录{}仍存在,未被删除",botDir);
OfflineServiceUtil.onlineCacheResponse(response, new OfflineOnlineCacheResponse(555, "删除目录失败"), 555);
}else {
OfflineServiceUtil.onlineCacheResponse(response, new OfflineOnlineCacheResponse(200), 200);
}
} catch (Exception e) {
log.error("删除目录:{}失败", botDir);
OfflineServiceUtil.onlineCacheResponse(response, new OfflineOnlineCacheResponse(555, "删除目录失败"), 555);
}
OfflineServiceUtil.onlineCacheResponse(response, new OfflineOnlineCacheResponse(200), 200);
}
}
change_sound_path=/root/GameEditor/mqw/project/tts/pythonCode/audios.py
\ No newline at end of file
offline:
output_dir: /root/TTSOfflineService/offline
short_audio_dir: short_audio
letter_audio_dir: letter_audio
test_text: 这是一段测试文本,请听下音效,选择你认为合适的一套声音
models_threads: 3
server:
port: 9001
package ai.qiwu.com.tts_offline;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TtsOfflineApplicationTests {
@Test
public void contextLoads() {
}
}
......@@ -25,10 +25,6 @@
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
......
package ai.qiwu.com.tts_service.common;
import ai.qiwu.com.tts_service.service.Initialize;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.*;
import java.util.HashMap;
import java.util.List;
/**
......@@ -14,45 +14,198 @@ import java.util.List;
@Slf4j
public class CallPython {
private static final String INTERPRETER = "/usr/bin/python3";
private static String INTERPRETER ;
private static final String AUDIO_FILE = "/home/yf01/pythonWork/audio.py";
private static final String COMBINE_FILE = "";
private static final String COMBINE_FILE = "/home/yf01/pythonWork/combine.py";
public static void changeSound(String wav_filename, String volume, String speed, String pitch, String filename) throws IOException {
String[] args = {INTERPRETER, AUDIO_FILE, wav_filename, volume, speed, pitch, filename};
Process process = Runtime.getRuntime().exec(args);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
StringBuilder result = new StringBuilder();
while ((line = reader.readLine()) != null) {
result.append(line);
public static String changeSound(String wav_filename, Double volume, Double speed, Double pitch, String filename) {
String command = ChangeSound.changeSound(wav_filename, volume, speed, pitch, filename);
log.info("命令:{}", command);
String result = processUtilInJava(command);
if ("1".equals(result)) {
if (!TTSUtils.doesFileExist(filename)) {
log.error("检测到mp3文件不存在:{}", filename);
result = "0";
}
}
log.info("change Sound result:{}", result.toString());
reader.close();
return result;
}
public static String changeSoundByPython(String wav_filename, String volume, String speed, String pitch, String filename) throws IOException {
String[] args = {INTERPRETER, Initialize.getChangeSound(), wav_filename, volume, speed, pitch, filename};
// log.info("wav file:{}, vlo:{},speed:{}, pitch:{}", wav_filename, volume, speed, pitch);
return processUtil(args);
}
public static void combine(List<String> file_ls, String tmp_audio_name) throws IOException {
public static String combine(List<String> file_ls, String tmp_audio_name) throws IOException {
StringBuilder builder = new StringBuilder();
for (String file : file_ls) builder.append(file).append(",");
String fileList = builder.toString().substring(0, builder.length()-1);
String[] args = {INTERPRETER, COMBINE_FILE, fileList, tmp_audio_name};
Process process = Runtime.getRuntime().exec(args);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
StringBuilder result = new StringBuilder();
while ((line = reader.readLine()) != null) {
result.append(line);
return processUtil(args);
}
public static void getPythonInterpreter() {
String interpreter = processUtil("pipenv run which python");
log.info("获取的python解释器位置:{}", interpreter);
INTERPRETER = interpreter;
}
private static String processUtilInJava(String arg) {
final StringBuilder successResult = new StringBuilder();
final StringBuilder failResult = new StringBuilder();
Process process = null;
try {
process = Runtime.getRuntime().exec(arg);
final InputStream inputStream = process.getInputStream();
final InputStream errorStream = process.getErrorStream();
new Thread(() -> {
String line;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));){
while ((line = reader.readLine()) != null) {
successResult.append(line);
}
} catch (Exception e) {
log.error("读取Process输入流出错:{}",e.toString());
}
}).start();
new Thread(() -> {
String line;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream));){
while ((line = reader.readLine()) != null) {
failResult.append(line);
}
} catch (Exception e) {
log.error("读取Process error流出错:{}",e.toString());
}
}).start();
process.waitFor();
process.destroy();
} catch (Exception e) {
try {
if (process != null) {
process.getInputStream().close();
process.getErrorStream().close();
process.getOutputStream().close();
}
} catch (Exception e1) {
log.error("关闭Process的流出错:{}",e1.toString());
}
}
if (successResult.length() == 0) return "1";
else {
log.error("打印Process的错误流信息:{}", failResult.toString());
return null;
}
log.info("combine result:{}", result.toString());
reader.close();
}
public static void main(String[] args) throws IOException {
String wav = "/usr/GameEditor/mqw/tts/audio/A04/正常/f403f73cff700be9c3fed05b67fc9ace.wav";
String mp3 = "/usr/GameEditor/mqw/tts/audio/A04/正常/f403f73cff700be9c3fed05b67fc9ace.mp3";
changeSound(wav, "0", "1.32", "0", mp3);
private static String processUtil(String arg) {
final StringBuilder successResult = new StringBuilder();
final StringBuilder failResult = new StringBuilder();
Process process = null;
try {
process = Runtime.getRuntime().exec(arg);
final InputStream inputStream = process.getInputStream();
final InputStream errorStream = process.getErrorStream();
new Thread(() -> {
String line;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));){
while ((line = reader.readLine()) != null) {
successResult.append(line);
}
} catch (Exception e) {
log.error("读取Process输入流出错:{}",e.toString());
}
}).start();
new Thread(() -> {
String line;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream));){
while ((line = reader.readLine()) != null) {
failResult.append(line);
}
} catch (Exception e) {
log.error("读取Process error流出错:{}",e.toString());
}
}).start();
process.waitFor();
process.destroy();
} catch (Exception e) {
try {
if (process != null) {
process.getInputStream().close();
process.getErrorStream().close();
process.getOutputStream().close();
}
} catch (Exception e1) {
log.error("关闭Process的流出错:{}",e1.toString());
}
}
if (successResult.length() != 0) return successResult.toString();
else {
log.error("打印Process的错误流信息:{}", failResult.toString());
return null;
}
}
private static String processUtil(String[] args) {
final StringBuilder successResult = new StringBuilder();
final StringBuilder failResult = new StringBuilder();
Process process = null;
try {
process = Runtime.getRuntime().exec(args);
final InputStream inputStream = process.getInputStream();
final InputStream errorStream = process.getErrorStream();
new Thread(() -> {
String line;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));){
while ((line = reader.readLine()) != null) {
successResult.append(line);
}
} catch (Exception e) {
log.error("读取Process输入流出错:{}",e.toString());
}
}).start();
new Thread(() -> {
String line;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream));){
while ((line = reader.readLine()) != null) {
failResult.append(line);
}
} catch (Exception e) {
log.error("读取Process error流出错:{}",e.toString());
}
}).start();
process.waitFor();
process.destroy();
} catch (Exception e) {
try {
if (process != null) {
process.getInputStream().close();
process.getErrorStream().close();
process.getOutputStream().close();
}
} catch (Exception e1) {
log.error("关闭Process的流出错:{}",e1.toString());
}
}
if (successResult.length() != 0) return successResult.toString();
else {
log.error("打印Process的错误流信息:{}", failResult.toString());
return null;
}
}
}
package ai.qiwu.com.tts_service.common;
import ai.qiwu.com.tts_service.pojo.sound.Call;
import ai.qiwu.com.tts_service.pojo.sound.Compand;
import ai.qiwu.com.tts_service.pojo.sound.TempoAndPitch;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ChangeSound {
private static final List<String> TYPES = Arrays.asList("amplitude", "power", "dB");
private static final List<String> OPT_FLAG = Arrays.asList("l", "m", "s");
private static final List<String> DEFAULT_DB_LIST = Arrays.asList("-70", "-60", "-20");;
private static final List<String> DB_LIST = Arrays.asList("-50","-115","-40","-10","-30","-7","-20","-5","-10","-3","0","-3");
private static final String OFOPTS = "-C 32";
private static void compand(Compand compand, List<String> selfCommand) {
List<String> dbList = compand.getDbList();
if (CollectionUtils.isEmpty(dbList)) {
dbList = DEFAULT_DB_LIST;
}
String dbArgs = StringUtils.join(dbList.toArray(), ",");
String softKnee = (compand.getSoftKnee() == null ? 6 : compand.getSoftKnee())+":";
String attack = compand.getAttack() == null ? "0.2" : compand.getAttack();
String decay = compand.getDecay() == null ? "1" : compand.getDecay();
selfCommand.add("compand");
selfCommand.add(String.format("%s,%s", attack, decay));
selfCommand.add(softKnee+dbArgs);
if (compand.getGain() != null) selfCommand.add(compand.getGain());
if (compand.getInitialVolumeDb() != null) selfCommand.add(compand.getInitialVolumeDb());
if (compand.getDelay() != null) selfCommand.add(compand.getDelay());
}
private static void limiter(Double gain, List<String> selfCommand) {
selfCommand.add("gain");
selfCommand.add("-l");
selfCommand.add(gain == null ? "3.0" : gain.toString());
}
private static void vol(Double gain, String type, String limitGain, List<String> selfCommand) {
selfCommand.add("vol");
selfCommand.add(gain.toString());
if (type == null) type = "dB";
if (TYPES.contains(type)) selfCommand.add(type);
else throw new IllegalArgumentException("Type has to be dB, amplitude or power");
if (limitGain != null) selfCommand.add(limitGain);
}
private static void tempo(TempoAndPitch tempo, List<String> selfCommand) {
selfCommand.add("tempo");
if (tempo.getUseTree() != null && tempo.getUseTree()) selfCommand.add("-q");
if (OPT_FLAG.contains(tempo.getOptFlag())) selfCommand.add("-"+tempo.getOptFlag());
selfCommand.add(tempo.getFactor().toString());
if (tempo.getSegment() != null) selfCommand.add(tempo.getSegment());
if (tempo.getSearch() != null) selfCommand.add(tempo.getSearch());
if (tempo.getOverlap() != null) selfCommand.add(tempo.getOverlap());
}
private static void pitch(TempoAndPitch pitch, List<String> selfCommand) {
selfCommand.add("pitch");
if (pitch.getUseTree() != null && pitch.getUseTree()) selfCommand.add("-q");
selfCommand.add(pitch.getShift().toString());
if (pitch.getSegment() != null) selfCommand.add(pitch.getSegment());
if (pitch.getSearch() != null) selfCommand.add(pitch.getSearch());
if (pitch.getOptFlag() != null) selfCommand.add(pitch.getOverlap());
}
private static String call(Call call, List<String> selfCommand) {
List<String> cmdLs = new ArrayList<>();
cmdLs.add("sox");
if (call.getGopts() != null) TTSUtils.shlexSplit(call.getGopts(), cmdLs);
if (call.getIfopts() != null) TTSUtils.shlexSplit(call.getIfopts(), cmdLs);
cmdLs.add(call.getSrc());
if (call.getOfopts() != null) TTSUtils.shlexSplit(call.getOfopts(), cmdLs);
cmdLs.add(call.getDst());
if (!selfCommand.isEmpty()) cmdLs.addAll(selfCommand);
return StringUtils.join(cmdLs, " ");
}
public static String changeSound(String wavFile, Double volume, Double speed, Double pitch, String outFile) {
ArrayList<String> selfCommand = new ArrayList<>();
volume = volume == null? 0 : volume;
speed = speed == null? 1 : speed;
pitch = pitch == null? 0 : pitch;
if (speed > 6) speed = 6.0;
else if (speed < 0.25) speed = 0.25;
if (speed != 1.0) {
TempoAndPitch tempo = new TempoAndPitch();
tempo.setFactor(speed);
tempo(tempo, selfCommand);
}
if (pitch != 0) {
TempoAndPitch pitchIns = new TempoAndPitch();
pitchIns.setShift(pitch*100);
pitch(pitchIns, selfCommand);
}
if (volume > 0) {
limiter(volume, selfCommand);
Compand compand = new Compand("0", "0.8", "0.01", DB_LIST, "2");
compand(compand, selfCommand);
}else if (volume < 0) {
vol(volume, null, null, selfCommand);
}
Call call = new Call(wavFile, outFile, OFOPTS);
return call(call, selfCommand);
}
public static void main(String[] args) {
System.out.println(Double.parseDouble("0.0") != 0);
}
}
......@@ -8,6 +8,7 @@ import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
/**
......@@ -22,9 +23,10 @@ public class Config {
String filename = "tts.properties";
properties = new Properties();
try {
properties.load(new InputStreamReader(Config.class.getClassLoader().getResourceAsStream(filename), "UTF-8"));
} catch (IOException e) {
properties.load(new InputStreamReader(Config.class.getClassLoader().getResourceAsStream(filename), StandardCharsets.UTF_8));
} catch (Exception e) {
log.error("获取配置文件对象出错:{}", e.toString());
System.exit(1);
}
}
......
......@@ -97,7 +97,8 @@ public class OkHttp3Utils {
builder.headers(headBuilder.build()).post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr));
ResponseCodeWithData codeWithData = null;
try (Response response = timeoutClient.newCall(builder.build()).execute()){
log.info("doPostTimeout请求返回:{}", response.code());
//log.info("doPostTimeout请求返回:{}", response.code());
// log.info("response3333333 :{}",response.header("usetime"));
if (response.code() == 200) {
if (file != null) {
try (BufferedSink sink = Okio.buffer(Okio.sink(file))){
......@@ -191,7 +192,7 @@ public class OkHttp3Utils {
}
}
public static Integer deDeleteReturnCode(String url, Map<String, String> headers, String jsonStr) throws IOException {
public static Integer doDeleteReturnCode(String url, Map<String, String> headers, String jsonStr) throws IOException {
Request.Builder builder = new Request.Builder();
Request request = builder.url(url).build();
......
package ai.qiwu.com.tts_service.common;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author 苗权威
* @dateTime 19-8-8 上午10:58
*/
@Configuration
public class SpecialCharURLConfig {
@Bean
public ServletWebServerFactory webServerFactory() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.addConnectorCustomizers(connector -> connector.setProperty("relaxedQueryChars", "[]{}"));
return factory;
}
}
......@@ -8,4 +8,15 @@ import org.springframework.beans.factory.annotation.Autowired;
*/
public interface TTSConstants {
String DEFAULT_MOOD = "正常";
String ONLINE_SERVER = "http://dev01.centaurstech.com";
String OFFLINE_SERVER ="http://aliyun-hz1.chewrobot.com:9001";
String SERVER_NAME = "hz1";
// String AUDIO_DIR = "/root/GameEditor/mqw/tts/audio";
String AUDIO_DIR = "/usr/GameEditor/mqw/tts/audio";
String SERVER_URL= "aliyun-hz1.chewrobot.com:9663";
String THIRD_PARTY_TTS_TEXT = "third_party_tts";
String DELETE_SUCCESS = "删除文件成功";
String DELETE_FAIL = "删除文件失败";
String DELETE_OFFLINE_FAIL = "对线下测试服务器的删除指令调用失败";
}
package ai.qiwu.com.tts_service.common;
import ai.qiwu.com.tts_service.service.Initialize;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.DigestUtils;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.Format;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.*;
/**
* @author 苗权威
......@@ -37,7 +38,7 @@ public class TTSUtils {
if (!file.exists() || file.isFile()) {
createDirResult = file.mkdirs();
}
log.info("要创建的文件夹路径:{}", path);
// log.info("要创建的文件夹路径:{}", path);
return createDirResult;
}
......@@ -107,17 +108,51 @@ public class TTSUtils {
return file.exists();
}
public static void shlexSplit(String command, List<String> list) {
char[] arr = command.toCharArray();
int pre = 0, last = 0;
for (char c: arr) {
if (c == ' ') {
if (last >0 && arr[last-1] != ' ') {
list.add(command.substring(pre, last));
}
pre = last+1;
}
last++;
}
if (last != pre) list.add(command.substring(pre, last));
System.out.println(list);
}
public static boolean doesChangeSoundSuccess(List<String> filePathList) {
boolean result = true;
if (StringUtils.endsWith(filePathList.get(0), ".b64")) {
for (String path : filePathList) {
if (!doesFileExist(path.substring(0, path.length()-4))) {
result = false;
break;
}
}
} else {
for (String path : filePathList) {
if (!doesFileExist(path)) {
result = false;
break;
}
}
}
return result;
}
public static void cpContent(String src, String dest) {
try (BufferedInputStream input = new BufferedInputStream(new FileInputStream(new File(src)));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(dest))))){
byte[] buffer = new byte[1024];
int ln;
byte[] buffer = new byte[input.available()];
StringBuilder builder = new StringBuilder();
//builder.append("data:audio/mp3;base64,");
while ((ln = input.read(buffer)) != -1) {
byte[] encode = Base64.getEncoder().encode(Arrays.copyOf(buffer, ln));
builder.append(new String(encode,Charset.forName("utf-8")));
}
builder.append("data:audio/mp3;base64,");
input.read(buffer);
builder.append(new String(Base64.getEncoder().encode(buffer),Charset.forName("utf-8")));
writer.write(builder.toString());
writer.flush();
} catch (Exception e) {
......@@ -126,13 +161,11 @@ public class TTSUtils {
}
public static String readAllFile(String path) throws IOException {
try (BufferedInputStream input = new BufferedInputStream(new FileInputStream(new File(path)))){
byte[] buffer = new byte[1024];
int ln;
try (BufferedReader reader = new BufferedReader(new FileReader(new File(path)))){
StringBuilder builder = new StringBuilder();
builder.append("data:audio/mp3;base64,");
while ((ln = input.read(buffer)) != -1) {
builder.append(new String(buffer, 0, ln));
String str;
while ((str = reader.readLine()) != null) {
builder.append(str);
}
return builder.toString();
}
......@@ -159,11 +192,86 @@ public class TTSUtils {
return filename;
}
public static void combineMp3File(List<String> filePathList, String targetFilepath)
throws IOException {
try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(new File(targetFilepath)));){
AudioEnumeration<InputStream> audioEnumeration = new AudioEnumeration<>();
for (String filepath : filePathList) {
if (filepath.equals(Initialize.getThirdParty())) {
continue;
}
audioEnumeration.add(new FileInputStream(new File(filepath)));
}
SequenceInputStream sequenceInputStream= new SequenceInputStream(audioEnumeration);
byte[] buf = new byte[1024];
int ln;
while ((ln = sequenceInputStream.read(buf)) != -1) {
outputStream.write(buf, 0, ln);
}
outputStream.flush();
sequenceInputStream.close();
}
}
public static void combineMp3UseJava(List<String> filePathList, String targetFilepath) throws IOException, UnsupportedAudioFileException {
AudioFileFormat aff = AudioSystem.getAudioFileFormat(new File(filePathList.get(0)));
AudioEnumeration<AudioInputStream> enumeration = new AudioEnumeration<>();
long ln = 0;
for (String filepath : filePathList) {
AudioInputStream stream = AudioSystem.getAudioInputStream(new File(filepath));
ln += stream.getFrameLength();
enumeration.add(stream);
}
SequenceInputStream sequence = new SequenceInputStream(enumeration);
AudioSystem.write(new AudioInputStream(sequence, aff.getFormat(), ln), aff.getType(), new File(targetFilepath));
sequence.close();
}
static class AudioNode<T> {
private T value;
private AudioNode<T> next;
AudioNode(T value) {
this.value = value;
}
}
static class AudioEnumeration<T> implements Enumeration<T> {
private AudioNode<T> head;
private AudioNode<T> tail;
AudioEnumeration() {
head = tail = new AudioNode<>(null);
}
void add(T stream) {
tail.next = new AudioNode<>(stream);
tail = tail.next;
}
@Override
public boolean hasMoreElements() {
return head != tail;
}
@Override
public T nextElement() {
T result = head.next.value;
head = head.next;
return result;
}
}
public static void main(String[] args) {
String s = " '//\"\"' /a/'sf'/\" ' ";
//System.out.println(pythonStrip(s));
String s2 = "fsf\\sf///sff../fs..f/gh\\/fg..";
//System.out.println(s2.replaceAll("\\\\", " "));
System.out.println(secure_fileName(s2));
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<>());
}
}
......@@ -5,6 +5,7 @@ import ai.qiwu.com.tts_service.pojo.ResponseStatusWithList;
import ai.qiwu.com.tts_service.pojo.TTSResponse;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
......@@ -30,7 +31,8 @@ public class TTServiceUtil {
}
}
public static void buildMp3Response(HttpServletResponse response, MP3Response mp3Response, String fileName, int status) {
public static void buildMp3Response(HttpServletResponse response, MP3Response mp3Response,
String fileName, int status, boolean fileType) {
response.setStatus(status);
if (mp3Response != null) {
String ttsResJsonStr = JSON.toJSONString(mp3Response);
......@@ -47,6 +49,14 @@ public class TTServiceUtil {
OutputStream out = new BufferedOutputStream(response.getOutputStream())){
response.reset();
response.setContentType("audio/mp3");
if (fileType) {
String loadName = fileName.substring(fileName.lastIndexOf("/")+1).trim();
if (StringUtils.isBlank(loadName)) {
loadName = String.valueOf(System.currentTimeMillis());
}
String value = String.format("attachment;filename=\"%s\"", loadName);
response.setHeader("Content-Disposition", value);
}
byte[] buffer = new byte[1024];
int ln;
while ((ln = inputStream.read(buffer)) != -1) {
......
package ai.qiwu.com.tts_service.controller;
import ai.qiwu.com.tts_service.common.Config;
import ai.qiwu.com.tts_service.pojo.*;
import ai.qiwu.com.tts_service.service.Initialize;
import ai.qiwu.com.tts_service.service.TTService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -14,9 +14,9 @@ import javax.servlet.http.HttpServletResponse;
* @author 苗权威
* @dateTime 19-7-30 下午5:49
*/
@CrossOrigin
@RestController
@Slf4j
@RequestMapping("/mqw")
public class TTSController {
private final TTService ttService;
......@@ -33,7 +33,7 @@ public class TTSController {
@GetMapping("/api/speakers")
public SpeakersApiRes speakers_api() {
return new SpeakersApiRes(Config.getProperty("online_sever"), Config.getProperty("offline_server"));
return new SpeakersApiRes(Initialize.getPersonInfoOnline(), Initialize.getPersonInfoOffline());
}
@GetMapping("/api/tts")
......@@ -52,7 +52,7 @@ public class TTSController {
}
@PutMapping("/api/tts")
public void tts(HttpServletResponse response, @RequestBody TTSRequest ttsRequest) {
public void tts_put(@RequestBody TTSRequest ttsRequest,HttpServletResponse response) {
ttService.tts(ttsRequest, "PUT", response);
}
......
package ai.qiwu.com.tts_service.pojo;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
......@@ -14,10 +15,12 @@ import java.util.List;
@Getter
@Setter
@ToString
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class PersonInfo {
private String name;
private String sex;
private List<String> mood = new ArrayList<>();
private Boolean third_party;
public PersonInfo(String name, String sex) {
this.name = name;
......
......@@ -4,6 +4,8 @@ import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.Map;
/**
* @author 苗权威
* @dateTime 19-7-30 下午8:29
......@@ -12,10 +14,10 @@ import lombok.ToString;
@Setter
@ToString
public class SpeakersApiRes {
private String online;
private String offline;
private Map<String, PersonInfo> online;
private Map<String, PersonInfo> offline;
public SpeakersApiRes(String online, String offline) {
public SpeakersApiRes(Map<String, PersonInfo> online, Map<String, PersonInfo> offline) {
this.online = online;
this.offline = offline;
}
......
......@@ -25,6 +25,11 @@ public class TTSResponse {
this.message = message;
}
public TTSResponse(String audio, Integer status) {
this.status = status;
this.audio = audio;
}
public TTSResponse(Integer status) {
this.status = status;
}
......
package ai.qiwu.com.tts_service.pojo.sound;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-8-9 上午9:50
*/
@Getter
@Setter
@ToString
public class Call {
private String src;
private String dst;
private String gopts;
private String ifopts;
private String ofopts;
public Call() {
}
public Call(String src, String dst, String ofopts) {
this.src = src;
this.dst = dst;
this.ofopts = ofopts;
}
}
package ai.qiwu.com.tts_service.pojo.sound;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
@Getter
@Setter
@ToString
public class Compand {
private String attack;
private String decay;
private String softKnee;
private List<String> dbList;
private String gain;
private String initialVolumeDb;
private String delay;
public Compand() {
}
public Compand(String attack, String decay, String softKnee, List<String> dbList, String gain) {
this.attack = attack;
this.decay = decay;
this.softKnee = softKnee;
this.dbList = dbList;
this.gain = gain;
}
}
package ai.qiwu.com.tts_service.pojo.sound;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class TempoAndPitch {
private Double factor;
private Boolean useTree;
private String optFlag;
private String segment;
private String search;
private String overlap;
private Double shift;
}
package ai.qiwu.com.tts_service.service;
import ai.qiwu.com.tts_service.common.CallPython;
import ai.qiwu.com.tts_service.common.Config;
import ai.qiwu.com.tts_service.common.TTSConstants;
import ai.qiwu.com.tts_service.pojo.PersonInfo;
......@@ -32,15 +33,32 @@ public class Initialize implements InitializingBean {
private static final Map<String, PersonInfo> PERSON_INFO_OFFLINE; //speakers_offline
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 List<String> THIRD_PARTY_TTS;
private static final String SERVER_NAME;
private static final String SERVER_URL;
private static final String AUDIO_DIR;
private static final String ONLINE_SERVER;
private static final String OFFLINE_SERVER;
private static final String THIRD_PARTY;
private static final String CHANGE_SOUND;
private final SpeakerInfoRepository speakerInfoRepository;
static {
URL_LS = new ArrayList<>();
THIRD_PARTY_TTS = new ArrayList<>();
PERSON_INFO_ONLINE = new HashMap<>();
PERSON_INFO_OFFLINE = new HashMap<>();
PERSON_MOODURL = new HashMap<>();
OFFLINE_2_ONLINE = new HashMap<>();
SERVER_NAME = Config.getProperty("server_name");
SERVER_URL = Config.getProperty("server_url");
AUDIO_DIR = Config.getProperty("audio_dir");
ONLINE_SERVER = Config.getProperty("online_sever");
OFFLINE_SERVER = Config.getProperty("offline_server");
THIRD_PARTY = Config.getProperty("third_party_tts_text");
CHANGE_SOUND = Config.getProperty("change_sound_path");
}
@Autowired
......@@ -56,8 +74,15 @@ public class Initialize implements InitializingBean {
Integer withOnLine = speakerInfo.getWithOnline();
String person = speakerInfo.getPerson();
String person_offline = person+"_offline";
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;
}
if (withOnLine != null && withOnLine != 0) {
String url = String.format("%s:9%03d/synthesize", Config.getProperty("online_sever"), speakerInfo.getId());
String url = String.format("%s:9%03d/synthesize", Initialize.getOnlineServer(), speakerInfo.getId());
URL_LS.add(url);
if (StringUtils.isBlank(init_person)) {
init_person = person;
......@@ -75,11 +100,11 @@ public class Initialize implements InitializingBean {
if (jump != null) {
Map<String, String> mood2jumpUrl = OFFLINE_2_ONLINE.computeIfAbsent(person_offline, k -> new HashMap<>());
mood2jumpUrl.put(mood, String.format("%s:9%03d/synthesize", Config.getProperty("online_sever"), jump));
mood2jumpUrl.put(mood, String.format("%s:9%03d/synthesize", ONLINE_SERVER, jump));
}
Map<String, String> mood_url = PERSON_MOODURL.computeIfAbsent(person_offline, k -> new HashMap<>());
mood_url.putIfAbsent(mood, String.format("%s/synthesize", Config.getProperty("offline_server")));
mood_url.putIfAbsent(mood, String.format("%s/synthesize", OFFLINE_SERVER));
}
@Override
......@@ -88,6 +113,7 @@ public class Initialize implements InitializingBean {
for (SpeakersInfo speakerInfo: speakerInfos) {
initialize(speakerInfo);
}
//CallPython.getPythonInterpreter();
if (!PERSON_INFO_ONLINE.containsKey(init_person)) {
init_person = PERSON_INFO_ONLINE.keySet().iterator().next();
}
......@@ -96,11 +122,23 @@ public class Initialize implements InitializingBean {
init_tone = moodList.get(0);
}
init_url = PERSON_MOODURL.get(init_person).get(init_tone);
log.info("url_ls:{}", URL_LS);
log.info("PERSON_INFO_ONLINE:{}", PERSON_INFO_ONLINE);
log.info("PERSON_INFO_OFFLINE:{}", PERSON_INFO_OFFLINE);
log.info("OFFLINE2ONLINE:{}", OFFLINE_2_ONLINE);
log.info("PERSON_MODELURL:{}", PERSON_MOODURL);
// log.info("url_ls:{}", URL_LS);
// log.info("PERSON_INFO_ONLINE:{}", PERSON_INFO_ONLINE);
// log.info("PERSON_INFO_OFFLINE:{}", PERSON_INFO_OFFLINE);
// log.info("OFFLINE2ONLINE:{}", OFFLINE_2_ONLINE);
// log.info("PERSON_MODELURL:{}", PERSON_MOODURL);
}
public static Map<String, PersonInfo> getPersonInfoOnline() {
return PERSON_INFO_ONLINE;
}
public static Map<String, PersonInfo> getPersonInfoOffline() {
return PERSON_INFO_OFFLINE;
}
static boolean doesThirdPartyListHas(String person) {
return THIRD_PARTY_TTS.contains(person);
}
String getInit_person() {
......@@ -130,4 +168,36 @@ public class Initialize implements InitializingBean {
String getInit_url() {
return init_url;
}
public static List<String> getThirdPartyTts() {
return THIRD_PARTY_TTS;
}
static String getServerName() {
return SERVER_NAME;
}
static String getServerUrl() {
return SERVER_URL;
}
static String getAudioDir() {
return AUDIO_DIR;
}
private static String getOnlineServer() {
return ONLINE_SERVER;
}
static String getOfflineServer() {
return OFFLINE_SERVER;
}
public static String getThirdParty() {
return THIRD_PARTY;
}
public static String getChangeSound() {
return CHANGE_SOUND;
}
}
spring:
datasource:
# url: jdbc:mysql://localhost:3306/TTS
username: tts
password: qiwu@123234aA~
username: root
password: 3g9^pWQs#ft7
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://aliyun-hz1.chewrobot.com:3306/TTS
url: jdbc:mysql://localhost:3306/TTS
# username: tts
# password: qiwu@123234aA~
# driver-class-name: com.mysql.cj.jdbc.Driver
# url: jdbc:mysql://aliyun-hz1.chewrobot.com:3306/TTS
jpa:
database: mysql
#控制台显示SQL
......@@ -18,15 +21,5 @@ spring:
# level: info
# path: /usr/mqw/logs/tts
server:
port: 8088
offline:
output_dir: 'offline'
short_audio_dir: 'short_audio'
letter_audio_dir: 'letter_audio'
test_text: '这是一段测试文本,请听下音效,选择你认为合适的一套声音'
# hz1
mysql_host: '47.98.37.248'
mysql_user: 'tts'
mysql_password: 'qiwu@123234aA~'
models_threads: 3
\ No newline at end of file
port: 9663
#port: 8188
\ No newline at end of file
server_name=hz1
server_url=http://aliyun-hz1.chewrobot.com:9663
audio_dir=/root/GameEditor/mqw/project/tts/audio
#audio_dir=/usr/GameEditor/mqw/tts/audio
online_sever=http://dev01.centaurstech.com
offline_server=http://aliyun-hz1.chewrobot.com:9001
server_name=hz1
#audio_dir=/root/GameEditor/mqw/tts/audio
audio_dir=/usr/GameEditor/mqw/tts/audio
server_url=aliyun-hz1.chewrobot.com:9663
\ No newline at end of file
#第三方tts标记
third_party_tts_text =third_party_tts
python_interpreter=/usr/bin/python3
change_sound_path=/root/GameEditor/mqw/project/tts/pythonCode/audios.py
\ No newline at end of file
......@@ -61,6 +61,11 @@
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.0.0</version>
</dependency>
</dependencies>
<build>
......
package ai.qiwu.mi.xiaoai.commons;
import okhttp3.*;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* @author 苗权威
* @dateTime 19-7-18 上午10:54
*/
public class OkHttp3Utils {
private static OkHttpClient client = new OkHttpClient();
public static String doGet(String url) throws IOException {
return doGet(url, new HashMap<>());
}
public static String doGet(String url, Map<String, String> params) throws IOException {
return doGet(url, params, new HashMap<>());
}
public static String doGet(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()){
return response.body().string();
}
}
public static String doPost(String url, Map<String, String> params) throws IOException {
return doPost(url, new HashMap<>(), params,null);
}
public static String doPost(String url, Map<String, String> params, Map<String, String> headers) throws IOException {
return doPost(url, headers, params, null);
}
public static String doPost(String url, File file) throws IOException {
return doPost(url , new HashMap<>(), new HashMap<>(), file);
}
public static String doPostJsonStr(String url, Map<String, String> headers, String requestJsonStr) throws IOException {
Request.Builder builder = new Request.Builder();
Request request = builder.url(url).build();
Headers.Builder headBuilder = request.headers().newBuilder();
Iterator<Map.Entry<String, String>> headIterator = headers.entrySet().iterator();
headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
builder.headers(headBuilder.build()).post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr));
try (Response response = client.newCall(builder.build()).execute()){
return response.body().string();
}
}
public static String doPost(String url, Map<String, String> headers, Map<String, String> params, File file) throws IOException {
Request.Builder builder = new Request.Builder();
Request request = builder.url(url).build();
Headers.Builder headBuilder = request.headers().newBuilder();
Iterator<Map.Entry<String, String>> headIterator = headers.entrySet().iterator();
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()));
if (file != null) {
requestBuilder.addFormDataPart("uploadFiles", file.getName(),
RequestBody.create(MediaType.parse("application/octet-stream"), file));
}
builder.headers(headBuilder.build()).post(requestBuilder.build());
try (Response response = client.newCall(builder.build()).execute()){
return response.body().string();
}
}
public static String doPost(String url, Map<String, String> headers, Map<String, String> params,
String fileName, byte[] fileByte) throws IOException {
Request.Builder builder = new Request.Builder();
Request request = builder.url(url).build();
Headers.Builder headBuilder = request.headers().newBuilder();
Iterator<Map.Entry<String, String>> headIterator = headers.entrySet().iterator();
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()));
if (fileByte.length > 0) {
requestBuilder.addFormDataPart("uploadFiles", fileName,
RequestBody.create(MediaType.parse("application/octet-stream"), fileByte));
}
builder.headers(headBuilder.build()).post(requestBuilder.build());
try (Response response = client.newCall(builder.build()).execute()){
return response.body().string();
}
}
public static String doPut(String url, Map<String, String> headers, String jsonStr) throws IOException {
Request.Builder builder = new Request.Builder();
Request request = builder.url(url).build();
Headers.Builder headBuilder = request.headers().newBuilder();
Iterator<Map.Entry<String, String>> headIterator = headers.entrySet().iterator();
headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
builder.headers(headBuilder.build()).put(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonStr));
try (Response response = client.newCall(builder.build()).execute()){
return response.body().string();
}
}
public static String doDelete(String url, Map<String, String> headers, String jsonStr) throws IOException {
Request.Builder builder = new Request.Builder();
Request request = builder.url(url).build();
Headers.Builder headBuilder = request.headers().newBuilder();
Iterator<Map.Entry<String, String>> headIterator = headers.entrySet().iterator();
headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
builder.headers(headBuilder.build()).delete(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonStr));
try (Response response = client.newCall(builder.build()).execute()){
return response.body().string();
}
}
}
package ai.qiwu.mi.xiaoai.commons;
import ai.qiwu.mi.xiaoai.model.QiWuRequest;
import ai.qiwu.mi.xiaoai.model.QiWuResponse;
import com.alibaba.fastjson.JSON;
import java.io.IOException;
import java.util.HashMap;
/**
* @author 苗权威
* @dateTime 19-6-29 下午3:49
*/
public class RequestTerminal {
public static QiWuResponse requestTerminate(String userId, String userWord) throws IOException {
QiWuRequest requestPojo = new QiWuRequest();
requestPojo.setUser_id(userId);
requestPojo.setAccess(XiaoAiConstants.DEVICE_NAME);
requestPojo.setText(userWord);
String requestJsonStr = JSON.toJSONString(requestPojo);
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json;charset=utf-8");
String resStr = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE, headers, requestJsonStr);
return JSON.parseObject(resStr, QiWuResponse.class);
}
}
......@@ -5,7 +5,7 @@ package ai.qiwu.mi.xiaoai.commons;
* @dateTime 19-7-5 下午8:56
*/
public interface XiaoAiConstants {
String QI_WU_TERMINATE = "http://aliyun-hz1.chewrobot.com:8070/api/chat";
String QI_WU_TERMINATE = "http://aws-nx2.chewrobot.com:8070/api/chat2";
String DEVICE_NAME = "XIAOAI";
String CONTENT_TYPE = "application/json;charset=utf-8";
String PLAYBACK_NEARLY_FINISHED = "mediaplayer.playbacknearlyfinished";
......
package ai.qiwu.mi.xiaoai.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-7-10 下午2:29
*/
@Getter
@Setter
@ToString
public class QiWuRequest {
private String user_id;
private String text;
private String access;
}
package ai.qiwu.mi.xiaoai.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class QiWuResponse {
private String audio;
private String text;
}
package ai.qiwu.mi.xiaoai.service;
import ai.qiwu.mi.xiaoai.commons.RequestTerminal;
import ai.qiwu.mi.xiaoai.commons.Utils;
import ai.qiwu.mi.xiaoai.commons.XiaoAiConstants;
import ai.qiwu.mi.xiaoai.commons.XiaoAiConstants.TTS;
import ai.qiwu.mi.xiaoai.commons.XiaoAiConstants.ERROR_MSG;
import ai.qiwu.mi.xiaoai.model.QiWuResponse;
import ai.qiwu.mi.xiaoai.model.request.XiaoAiRequest;
import ai.qiwu.mi.xiaoai.model.response.XiaoAiResponse;
import ai.qiwu.mi.xiaoai.model.response.innerResponse.Response;
......@@ -11,24 +12,10 @@ 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.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
......@@ -50,45 +37,45 @@ public class XiaoAiService {
}
}
private XiaoAiResponse postToQiWuInterface(String userId, String userWord) {
String audioUrl = null;
String textContent = null;
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
try {
httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(XiaoAiConstants.QI_WU_TERMINATE);
HashMap<String, String> params = new HashMap<>();
params.put("user_id", userId);
params.put("text", userWord);
params.put("access",XiaoAiConstants.DEVICE_NAME);
String paramsJsonFormat = JSON.toJSONString(params);
StringEntity body = new StringEntity(paramsJsonFormat, StandardCharsets.UTF_8);
post.setHeader("Content-Type", XiaoAiConstants.CONTENT_TYPE);
post.setEntity(body);
httpResponse = httpClient.execute(post);
HttpEntity responseBody = httpResponse.getEntity();
if (responseBody != null) {
String responseContent = EntityUtils.toString(responseBody);
//log.info("齐悟接口返回: "+ responseContent);
JSONObject responseJsonFormat = JSONObject.parseObject(responseContent);
audioUrl = (String) responseJsonFormat.get("audio");
textContent = (String) responseJsonFormat.get("text");
}
} catch (IOException e) {
log.info(ERROR_MSG.TERMINATE_IO_EXCEPTION);
return buildTextResponse(ERROR_MSG.SORRY_REPEAT);
} finally {
try {
if (httpClient != null) httpClient.close();
if (httpResponse != null) httpResponse.close();
} catch (IOException e) {
log.info(ERROR_MSG.HTTP_CONNECTION_CLOSE_EXCEPTION);
}
}
return buildAudioResponse(audioUrl);
}
// private XiaoAiResponse postToQiWuInterface(String userId, String userWord) {
// String audioUrl = null;
// String textContent = null;
// CloseableHttpClient httpClient = null;
// CloseableHttpResponse httpResponse = null;
// try {
// httpClient = HttpClientBuilder.create().build();
// HttpPost post = new HttpPost(XiaoAiConstants.QI_WU_TERMINATE);
// HashMap<String, String> params = new HashMap<>();
// params.put("user_id", userId);
// params.put("text", userWord);
// params.put("access",XiaoAiConstants.DEVICE_NAME);
// String paramsJsonFormat = JSON.toJSONString(params);
// StringEntity body = new StringEntity(paramsJsonFormat, StandardCharsets.UTF_8);
// post.setHeader("Content-Type", XiaoAiConstants.CONTENT_TYPE);
// post.setEntity(body);
//
// httpResponse = httpClient.execute(post);
// HttpEntity responseBody = httpResponse.getEntity();
// if (responseBody != null) {
// String responseContent = EntityUtils.toString(responseBody);
// //log.info("齐悟接口返回: "+ responseContent);
// JSONObject responseJsonFormat = JSONObject.parseObject(responseContent);
// audioUrl = (String) responseJsonFormat.get("audio");
// textContent = (String) responseJsonFormat.get("text");
// }
// } catch (IOException e) {
// log.info(ERROR_MSG.TERMINATE_IO_EXCEPTION);
// return buildTextResponse(ERROR_MSG.SORRY_REPEAT);
// } finally {
// try {
// if (httpClient != null) httpClient.close();
// if (httpResponse != null) httpResponse.close();
// } catch (IOException e) {
// log.info(ERROR_MSG.HTTP_CONNECTION_CLOSE_EXCEPTION);
// }
// }
// return buildAudioResponse(audioUrl);
// }
private XiaoAiResponse buildResponse() {
XiaoAiResponse response = new XiaoAiResponse();
......@@ -146,11 +133,22 @@ public class XiaoAiService {
if (userWord == null) {
return buildTextResponse(ERROR_MSG.SORRY_REPEAT);
}
return postToQiWuInterface(userId, userWord);
QiWuResponse response = null;
try {
response = RequestTerminal.requestTerminate(userId, userWord);
} catch (Exception e) {
log.error("向终端发出的请求信息失败:{}", e.toString());
return buildTextResponse(ERROR_MSG.SORRY_REPEAT);
}
return buildAudioResponse(response.getAudio());
}
private XiaoAiResponse dealWithEndRequest(String userId) {
postToQiWuInterface(userId, TTS.END_WORD);
try {
RequestTerminal.requestTerminate(userId, TTS.END_WORD);
} catch (Exception e) {
log.error("向终端发出的退出请求失败:{}", e.toString());
}
return buildTextResponse(TTS.END_BYE);
}
......
package ai.qiwu.baidu.xiaodu.controller;
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.productManager.ProductManager;
import com.baidu.dueros.bot.BaseBot;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.Arrays;
/**
* @author 苗权威
* @dateTime 19-6-29 下午5:32cat
......
package ai.qiwu.baidu.xiaodu.pojo.dpl;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-8-6 下午9:26
*/
@Getter
@Setter
@ToString
public class Event {
private String type;
}
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.pojo.dpl;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.ArrayList;
import java.util.List;
/**
* @author 苗权威
* @dateTime 19-8-7 上午9:37
*/
@Getter
@Setter
@ToString
public class MyMainTemplate {
private List<String> parameters = new ArrayList<>();
private List<Item> items;
public MyMainTemplate() {
this.parameters.add("payload");
this.items = new ArrayList<>();
}
}
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();
// }
}
}
......@@ -29,16 +29,12 @@ import com.baidu.dueros.data.response.directive.audioplayer.Play;
import com.baidu.dueros.data.response.directive.audioplayer.PlayerInfo;
import com.baidu.dueros.data.response.directive.pay.Buy;
import com.baidu.dueros.data.response.directive.pay.Charge;
import com.baidu.dueros.model.Request;
import com.baidu.dueros.model.Response;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.System;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
......@@ -59,19 +55,19 @@ public class ResponseEncapsulation extends AudioPlayer {
public ResponseEncapsulation(HttpServletRequest request) throws IOException {
super(request);
String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANMWIYduiQZt0B7s\n" +
"IZ6PW15gpcO7Yn+9ZbaMSHwzJqNeDAZzh6HXF7r0ZpQcw3XEWKPAPWyuJ5eqZf46\n" +
"W/NyJQkcddWrA/5OvcZw1uAmzTt8sWz1zokt2e6v6SucvvHoPxLGjfTKWh6Qr+2x\n" +
"K/5wmdOOpikL/ruH2ZviYjto2cBPAgMBAAECgYBuQCLnD8618uk/HWo53PqGAsjR\n" +
"wK+jtJLJk9/QLw9BSL/TJshyuVuFpF1ngtZ8Tj9V1/S9LQE08CUxcd3Q+49njgEq\n" +
"R60FKDjwCe8G9El5jIYIU0RTnd84I8B0RKWBO8ShZ29qWEVXOExPZc1fMlq4UgBr\n" +
"Xkfsh/E1cTfphYyS8QJBAOuX1c11XOSeDVo5KyxM26K2Kiekjm1cLIXJR54hetRN\n" +
"diCHqd5WyolKJzxFuUMEsq+sAfgd7KsrorO5hwY42lUCQQDlXt9TiIWGMt3oVEIf\n" +
"ulJQmURhkQ+Z9EC2wHnFrE3UhkCNyX3TOwTzV8bzC+Vr2hAobbhXTCr8tLGm0Yxk\n" +
"f1wTAkEAqbQtplosF+Jh6+PSXY7fh02BAB1hGxWSXKyokhe7ysIhnT0b97S9IDfy\n" +
"G1B+KvBvZmuY34luub4s7RlvUeQSIQJANaq7Cip5Q2sHbOK6Df5kYCNcUo/EXLs/\n" +
"oQLr+wpTs5Qt6n7oh9HZWK6DCD8SUOfWu/7gENzrefE1V9jTxnfeLQJBANKf4QfA\n" +
"CvwfHTyEgphcWrWDzB7bEqUDWiEjfO8sf+lwj9I0yU6fO/+aUtwU9xwkij1PscUF\n" +
String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANMWIYduiQZt0B7s" +
"IZ6PW15gpcO7Yn+9ZbaMSHwzJqNeDAZzh6HXF7r0ZpQcw3XEWKPAPWyuJ5eqZf46" +
"W/NyJQkcddWrA/5OvcZw1uAmzTt8sWz1zokt2e6v6SucvvHoPxLGjfTKWh6Qr+2x" +
"K/5wmdOOpikL/ruH2ZviYjto2cBPAgMBAAECgYBuQCLnD8618uk/HWo53PqGAsjR" +
"wK+jtJLJk9/QLw9BSL/TJshyuVuFpF1ngtZ8Tj9V1/S9LQE08CUxcd3Q+49njgEq" +
"R60FKDjwCe8G9El5jIYIU0RTnd84I8B0RKWBO8ShZ29qWEVXOExPZc1fMlq4UgBr" +
"Xkfsh/E1cTfphYyS8QJBAOuX1c11XOSeDVo5KyxM26K2Kiekjm1cLIXJR54hetRN" +
"diCHqd5WyolKJzxFuUMEsq+sAfgd7KsrorO5hwY42lUCQQDlXt9TiIWGMt3oVEIf" +
"ulJQmURhkQ+Z9EC2wHnFrE3UhkCNyX3TOwTzV8bzC+Vr2hAobbhXTCr8tLGm0Yxk" +
"f1wTAkEAqbQtplosF+Jh6+PSXY7fh02BAB1hGxWSXKyokhe7ysIhnT0b97S9IDfy" +
"G1B+KvBvZmuY34luub4s7RlvUeQSIQJANaq7Cip5Q2sHbOK6Df5kYCNcUo/EXLs/" +
"oQLr+wpTs5Qt6n7oh9HZWK6DCD8SUOfWu/7gENzrefE1V9jTxnfeLQJBANKf4QfA" +
"CvwfHTyEgphcWrWDzB7bEqUDWiEjfO8sf+lwj9I0yU6fO/+aUtwU9xwkij1PscUF" +
"9AWUhbas+LG9mds=";
//privateKey为私钥内容,0代表你的Bot在DBP平台debug环境,1或者其他整数代表online环境,
// botMonitor对象已经在bot-sdk里初始化,可以直接调用
......@@ -225,14 +221,13 @@ public class ResponseEncapsulation extends AudioPlayer {
}
logger.info("请求终端接口:"+data);
String audioUrl = data.getAudio();
logger.info(getSupportedInterfaces().getAudioPlayer() == null?"audio is null":"audio not null");
logger.info(getSupportedInterfaces().getScreen() == null?"screen is null":"screen not null");
// if (getSupportedInterfaces().getScreen() == null) {
// addDirective(buildNoScreenPlayDirec(audioUrl, AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL));
// }else {
// addDirective(buildPlayDirective(audioUrl, data.getText(), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL));
// }
addDirective(buildPlayDirective(audioUrl, data.getText(), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL));
String screenToken = getRequest().getContext().getScreen().getToken();
logger.info("screen token:{}", screenToken);
if (screenToken == null) {
addDirective(buildNoScreenPlayDirec(audioUrl, AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL));
}else {
addDirective(buildPlayDirective(audioUrl, data.getText(), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL));
}
// String uri = "https://aliyun-hz1.chewrobot.com/xiaodu/image/5b2d0a11/lvzhou/1564033095964d39f.jpg";
// ImageStructure imageStructure = new ImageStructure(uri, 512, 512);
......@@ -374,18 +369,6 @@ public class ResponseEncapsulation extends AudioPlayer {
}
/**
* 不想对每个事件都进行处理,通过重写onDefaultEvent方法来统一处理。
* 任何事件都不允许开麦
* @return
*/
// @Override
// protected Response onDefaultEvent() {
// this.waitAnswer();
// this.setExpectSpeech(false);
// return new Response();
// }
/**
* 音频播放结束,开麦
*
* expectSpeech
......
{
"type":"DPL",
"version":"1.0",
"resources":[
],
"styles":{
},
"dataSource": {
},
"layouts":{
},
"mainTemplate": {
"parameters": [
"payload"
],
"items": [
{
"type": "Container",
"width":"100vw",
"height":"100vh",
"items":[
{
"type": "Image",
"height": "100dp",
"width": "80dp",
"src": "https://aliyun-hz1.chewrobot.com/xiaodu/image/pictures/cat.jpg",
"scale-type": "fixCenter",
"border-bottom-right-radius": "10dp",
"opacity": 0.5
},
{
"type": "Text",
"text": "This is a sample text",
"line-height": "10dp",
"letter-spacing": "8dp",
"color": "red",
"padding-left": "10dp",
"margin-left": "5dp"
},
{
"type":"Audio",
"looping":false,
"autoPlay":true,
"audioType":"mp3",
"onEnd":[
{
"type":"SendEvent"
}
]
}
]
}
]
}
}
\ No newline at end of file
......@@ -57,11 +57,6 @@
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
......
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 lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
/**
* @author 苗权威
* @dateTime 19-7-26 下午9:27
......@@ -13,15 +17,17 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
@Slf4j
public class XiaoDuHomeController {
@RequestMapping("/xiaoduhome")
@RequestMapping("/xiaoduhome/chat")
public String chat() {
try {
ResponseEncapsulation response = new ResponseEncapsulation(Utils.getHttpServletRequest());
response.enableVerify();
//response.disableVerify();
return response.run();
DplBotService service = new DplBotService(Utils.getHttpServletRequest());
log.info("请求信息:{}", service.getStrRequest());
service.disableVerify();
String str = service.run();
log.info("响应信息:{}", str);
return str;
} catch (Exception e) {
log.info("出现错误 "+e.toString());
log.error("出现错误 "+e.toString());
}
return null;
}
......
package ai.qiwu.com.xiaoduhome.pojo.dpl;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-8-6 下午9:26
*/
@Getter
@Setter
@ToString
public class Event {
private String type;
private String componentId;
}
package ai.qiwu.com.xiaoduhome.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;
@JsonProperty("margin-top")
private String marginTop;
private Boolean looping;
private Boolean autoPlay;
private String audioType;
private List<Event> onEnd;
private List<Event> onPrepared;
private List<Event> onLoaded;
private List<Event> onPause;
private List<Event> onPlay;
private List<Event> onRelease;
private String command;
private List<Item> items;
private String position;
private String top;
private String left;
private String headerImage;
@JsonProperty("flex-direction")
private String flexDirection;
@JsonProperty("font-size")
private String fontSize;
private List<String> hints;
private String componentId;
}
package ai.qiwu.com.xiaoduhome.pojo.dpl;
import com.baidu.dueros.data.response.directive.dpl.Document;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-8-7 上午9:50
*/
@Getter
@Setter
@ToString
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class MyDocument extends Document {
private MyMainTemplate mainTemplate;
}
package ai.qiwu.com.xiaoduhome.pojo.dpl;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.ArrayList;
import java.util.List;
/**
* @author 苗权威
* @dateTime 19-8-7 上午9:37
*/
@Getter
@Setter
@ToString
public class MyMainTemplate {
private List<String> parameters = new ArrayList<>();
private List<Item> items;
public MyMainTemplate() {
this.parameters.add("payload");
this.items = new ArrayList<>();
}
}
package ai.qiwu.com.xiaoduhome.service;
import ai.qiwu.com.xiaoduhome.common.Constants;
import ai.qiwu.com.xiaoduhome.common.Utils;
import ai.qiwu.com.xiaoduhome.pojo.QiWuResponse;
import ai.qiwu.com.xiaoduhome.pojo.dpl.Item;
import ai.qiwu.com.xiaoduhome.pojo.dpl.MyDocument;
import com.alibaba.fastjson.JSON;
import com.baidu.dueros.bot.AudioPlayer;
import com.baidu.dueros.bot.BaseBot;
import com.baidu.dueros.data.request.IntentRequest;
import com.baidu.dueros.data.request.LaunchRequest;
import com.baidu.dueros.data.request.Query;
import com.baidu.dueros.data.request.audioplayer.event.PlaybackFinishedEvent;
import com.baidu.dueros.data.request.audioplayer.event.PlaybackStoppedEvent;
import com.baidu.dueros.data.response.OutputSpeech;
import com.baidu.dueros.data.response.Reprompt;
import com.baidu.dueros.data.response.card.Card;
import com.baidu.dueros.data.response.card.TextCard;
import com.baidu.dueros.data.response.directive.dpl.Document;
import com.baidu.dueros.data.response.directive.dpl.ExecuteCommands;
import com.baidu.dueros.data.response.directive.dpl.RenderDocument;
import com.baidu.dueros.data.response.directive.dpl.commands.SendEventCommand;
import com.baidu.dueros.data.response.directive.dpl.commands.UpdateComponentCommand;
import com.baidu.dueros.data.response.directive.dpl.event.UserEvent;
import com.baidu.dueros.model.Response;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
/**
* @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
public Response onLaunch(LaunchRequest launchRequest) {
Document document = null;
try {
String str = getJsonFromName("static/json/onLunch.json");
//log.info("JSON STR:{}", jsonStr);
document = Document.getDocumentFromString(str);
} catch (IOException e) {
e.printStackTrace();
}
//MyDocument document = JSON.parseObject(testJsonStr(), MyDocument.class);
RenderDocument render = new RenderDocument();
render.setDocument(document);
this.addDirective(render);
OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "欢迎来到文艺大厅,这里有海量的作品在这等您");
return new Response(outputSpeech);
}
@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);
QiWuResponse data = null;
try {
data = RequestTerminal.requestTerminate(userWord, userId);
} catch (IOException e) {
log.error("请求终端接口出错:", e.toString());
}
if (data == null) {
return buildErrorResponse(Constants.ErrorMsg.SORRY_UNCATCH);
}
log.info("小悟返回:{}", data.getText());
List<Item> items = document.getMainTemplate().getItems().get(0).getItems();
items.get(2).getItems().get(1).getItems().get(0).getItems().get(2).setText(data.getText());
items.get(1).setSrc(data.getAudio());
ExecuteCommands executeCommands = new ExecuteCommands();
UpdateComponentCommand update = new UpdateComponentCommand();
update.setDocument(document);
update.setComponentId("whole");
executeCommands.addCommand(update);
this.addDirective(executeCommands);
return new Response();
}
private String testJsonStr() {
if (jsonStr == null) {
try {
jsonStr = getJsonFromName("static/json/demo01.json");
} catch (Exception e) {
log.error("没有获取到json字符串:{}", e.toString());
}
}
return jsonStr;
}
@Override
protected Response onPlaybackFinishedEvent(PlaybackFinishedEvent playbackFinishedEvent) {
log.info("音频播放完毕,开麦");
this.setExpectSpeech(true);
return new Response();
}
@Override
protected Response onPlaybackStoppedEvent(PlaybackStoppedEvent playbackStoppedEvent) {
log.info("音频播放停止");
return new Response();
}
@Override
protected Response onUserEvent(UserEvent userEvent) {
log.info("未拦截的事件类型:"+getEventType(this.getStrRequest()));
log.info("onUserEvent事件触发,token:{}, componentId:{}",userEvent.getToken(),userEvent.getPayload().getComponentId());
setExpectSpeech(true);
return new Response();
}
@Override
protected Response onDefaultEvent() {
log.info("未拦截的事件类型:"+getEventType(this.getStrRequest()));
this.waitAnswer();
return new Response();
}
private String getEventType(String requestStr) {
int typeIndex = requestStr.lastIndexOf("type");
int comma = requestStr.indexOf(',', typeIndex);
return requestStr.substring(typeIndex, comma);
}
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 {
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(filename);
InputStreamReader reader = new InputStreamReader(inputStream);
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();
}
}
......@@ -17,8 +17,6 @@ import java.util.HashMap;
*/
class RequestTerminal {
private static final Logger logger = LoggerFactory.getLogger(RequestTerminal.class);
static QiWuResponse requestTerminate(String userId, String userWord) throws IOException {
QiWuRequest requestPojo = new QiWuRequest();
requestPojo.setUser_id(userId);
......
{
"type": "DPL",
"version": "1.0",
"mainTemplate": {
"parameters": [
"payload"
],
"items": [
{
"type": "Container",
"width": "100%",
"height": "100%",
"componentId": "whole",
"items": [
{
"type": "Image",
"position": "absolute",
"top": "0dp",
"left": "0dp",
"height": "100%",
"width": "100%",
"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",
"width": "100%",
"height": "100%",
"items": [
{
"type": "Header",
"headerImage": "https://aliyun-hz1.chewrobot.com/xiaodu/image/5b2d0a11/lvzhou/15640330891628686.jpg"
},
{
"type": "Container",
"flex-direction": "row",
"width": "100%",
"height": "100%",
"items": [
{
"type": "Container",
"width": "65%",
"height": "100%",
"items": [
{
"type": "Text",
"text": "互动天地",
"color": "blue",
"font-size": "35dp",
"letter-spacing": "30dp",
"margin-top": "30dp",
"margin-left": "10%"
},
{
"type": "Text",
"text": "有声互动小说",
"font-size": "25dp",
"letter-spacing": "30dp",
"margin-top": "20dp",
"margin-left": "10%"
},
{
"type": "Text",
"text": "欢迎来到互动天地",
"font-size": "30dp",
"letter-spacing": "30dp",
"margin-top": "20dp",
"margin-left": "10%"
}
]
},
{
"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": [
"有什么好玩的码?","推荐作品","我要玩绿洲"
]
}
]
}
]
}
]
}
}
\ No newline at end of file
{
"type": "DPL",
"version": "1.0",
"mainTemplate": {
"parameters": [
"payload"
],
"items": [
{
"type": "Container",
"width": "100%",
"height": "100%",
"componentId": "whole",
"items": [
{
"type": "Image",
"position": "absolute",
"top": "0dp",
"left": "0dp",
"height": "100%",
"width": "100%",
"src": "https://duerstatic.bj.bcebos.com/dbp-image%2FDPLMaterial%2Fimage2019-6-24_19-8-392.jpg"
},
{
"type": "Container",
"width": "100%",
"height": "100%",
"items": [
{
"type": "Header",
"headerImage": "https://aliyun-hz1.chewrobot.com/xiaodu/image/5b2d0a11/lvzhou/15640330891628686.jpg"
},
{
"type": "Container",
"flex-direction": "row",
"width": "100%",
"height": "100%",
"items": [
{
"type": "Container",
"width": "65%",
"height": "100%",
"items": [
{
"type": "Text",
"text": "互动天地",
"color": "blue",
"font-size": "35dp",
"letter-spacing": "30dp",
"margin-top": "30dp",
"margin-left": "10%"
},
{
"type": "Text",
"text": "有声互动小说",
"font-size": "25dp",
"letter-spacing": "30dp",
"margin-top": "20dp",
"margin-left": "10%"
},
{
"type": "Text",
"text": "欢迎来到互动天地",
"font-size": "30dp",
"letter-spacing": "30dp",
"margin-top": "20dp",
"margin-left": "10%"
}
]
},
{
"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": [
"有什么好玩的码?","推荐作品","我要玩绿洲"
]
}
]
}
]
}
]
}
}
\ No newline at end of file
{
"type":"DPL",
"version":"1.0",
"resources":[
],
"styles":{
},
"dataSource": {
},
"layouts":{
},
"mainTemplate": {
"parameters": [
"payload"
],
"items": [
{
"type": "Image",
"position": "absolute",
"top": "0dp",
"left": "0dp",
"src": "https://aliyun-hz1.chewrobot.com/xiaodu/image/5b2d0a11/lvzhou/15640330891628686.jpg",
"height": "100%",
"width": "100%"
},
{
"type": "Container",
"width": "100%",
"height": "100%",
"items": [
{
}
]
},
{
"type": "Text",
"text": "欢迎来到文艺大厅",
"line-height": "5dp",
"letter-spacing": "2dp",
"padding-left": "5dp",
"margin-left": "5dp"
},
{
"type": "Image",
"height": "25dp",
"width": "25dp",
"src": "https://aliyun-hz1.chewrobot.com/xiaoduhome/image/cat.jpg",
"scale-type": "fixCenter",
"border-bottom-right-radius": "2dp",
"opacity": 0.5
}
]
}
}
\ 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