diff --git a/.idea/compiler.xml b/.idea/compiler.xml
index 72c6e9c..8c04fd8 100644
--- a/.idea/compiler.xml
+++ b/.idea/compiler.xml
@@ -12,6 +12,7 @@
+
@@ -33,6 +34,7 @@
+
diff --git a/.idea/encodings.xml b/.idea/encodings.xml
index 4e3340b..7be22c9 100644
--- a/.idea/encodings.xml
+++ b/.idea/encodings.xml
@@ -7,6 +7,7 @@
+
diff --git a/.idea/misc.xml b/.idea/misc.xml
index 76dbd0f..9cd3f5e 100644
--- a/.idea/misc.xml
+++ b/.idea/misc.xml
@@ -26,6 +26,7 @@
+
diff --git a/.idea/workspace.xml b/.idea/workspace.xml
index 0741fd9..16a53c5 100644
--- a/.idea/workspace.xml
+++ b/.idea/workspace.xml
@@ -2,12 +2,42 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -24,6 +54,7 @@
+
@@ -52,8 +83,8 @@
-
-
+
+
@@ -62,83 +93,67 @@
-
+
-
-
-
-
-
+
+
-
-
+
+
-
-
-
-
-
-
-
+
+
-
+
-
-
+
+
-
-
-
+
-
-
+
+
-
+
-
-
-
-
-
+
+
-
-
+
+
-
-
-
-
-
+
+
-
+
-
-
+
+
@@ -174,6 +189,16 @@
StringUtils.join
_type
500
+ MyAudioEffectsChain
+ GeneralMP3Data
+ filePath
+
+ getEventType
+ log
+ log.info
+ moodUrl
+ offlineService
+ pitch
OPENID_CACHE
@@ -188,57 +213,57 @@
@@ -256,20 +281,20 @@
-
+
-
+
-
+
-
+
@@ -280,9 +305,9 @@
-
-
-
+
+
+
@@ -293,8 +318,6 @@
-
-
@@ -305,25 +328,25 @@
-
+
-
+
-
+
-
+
@@ -331,41 +354,75 @@
-
+
-
+
-
+
-
+
-
+
-
+
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
+
+
@@ -375,8 +432,6 @@
-
-
@@ -396,10 +451,65 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -412,7 +522,7 @@
-
+
@@ -423,6 +533,8 @@
+
+
@@ -431,18 +543,18 @@
-
-
-
-
-
+
+
+
+
+
+
+
-
-
@@ -457,7 +569,7 @@
-
+
@@ -471,12 +583,12 @@
-
-
+
+
-
+
@@ -484,12 +596,25 @@
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
@@ -497,12 +622,12 @@
-
-
-
+
+
+
-
+
@@ -727,22 +852,6 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
@@ -792,6 +901,13 @@
+
+
+
+
+
+
+
@@ -828,9 +944,11 @@
-
+
+
+
@@ -838,7 +956,6 @@
-
@@ -851,15 +968,15 @@
-
+
-
-
+
-
-
+
+
+
@@ -916,7 +1033,14 @@
-
+
+
+
+
+
+
+
+
@@ -926,7 +1050,7 @@
-
+
@@ -938,10 +1062,10 @@
-
+
-
+
@@ -949,14 +1073,14 @@
-
+
-
-
-
+
+
+
-
+
@@ -965,21 +1089,21 @@
-
+
-
+
-
+
-
+
-
+
@@ -987,30 +1111,30 @@
-
+
-
-
+
+
-
+
-
+
-
+
-
+
-
+
@@ -1021,447 +1145,367 @@
-
+
-
-
+
+
-
+
-
-
+
+
-
-
-
-
-
-
-
+
+
+
+
+
-
+
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
-
-
-
-
-
-
+
+
-
+
-
-
+
+
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
+
+
+
-
+
-
-
+
+
-
-
-
+
-
+
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
-
-
+
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
-
-
-
-
+
+
-
+
-
-
-
-
-
+
+
-
+
-
-
-
-
-
+
+
-
+
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
-
+
-
-
-
-
-
+
+
-
+
-
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
-
-
+
-
+
-
-
-
-
-
+
+
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
-
-
-
-
+
+
-
+
-
-
-
-
-
+
+
-
+
-
-
-
-
-
+
+
-
+
-
-
+
+
-
-
-
+
-
-
+
+
+
+
+
-
+
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
-
-
-
-
-
-
+
+
-
+
-
-
-
-
-
-
-
+
+
diff --git a/third_party_load/pom.xml b/third_party_load/pom.xml
index 379c07d..8e7932f 100644
--- a/third_party_load/pom.xml
+++ b/third_party_load/pom.xml
@@ -80,13 +80,13 @@
-
-
-
-
-
-
-
+
+ com.baidu.bot
+ baidu-sdk
+ 1.0.0
+ system
+ ${project.basedir}/src/main/resources/static/bot-sdk-1.2.0.jar
+
diff --git a/tts_offline/.gitignore b/tts_offline/.gitignore
new file mode 100644
index 0000000..a2a3040
--- /dev/null
+++ b/tts_offline/.gitignore
@@ -0,0 +1,31 @@
+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/
diff --git a/tts_offline/.mvn/wrapper/MavenWrapperDownloader.java b/tts_offline/.mvn/wrapper/MavenWrapperDownloader.java
new file mode 100644
index 0000000..7f91a56
--- /dev/null
+++ b/tts_offline/.mvn/wrapper/MavenWrapperDownloader.java
@@ -0,0 +1,114 @@
+/*
+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();
+ }
+
+}
diff --git a/tts_offline/.mvn/wrapper/maven-wrapper.jar b/tts_offline/.mvn/wrapper/maven-wrapper.jar
new file mode 100644
index 0000000..01e6799
Binary files /dev/null and b/tts_offline/.mvn/wrapper/maven-wrapper.jar differ
diff --git a/tts_offline/.mvn/wrapper/maven-wrapper.properties b/tts_offline/.mvn/wrapper/maven-wrapper.properties
new file mode 100644
index 0000000..cd0d451
--- /dev/null
+++ b/tts_offline/.mvn/wrapper/maven-wrapper.properties
@@ -0,0 +1 @@
+distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip
diff --git a/tts_offline/mvnw b/tts_offline/mvnw
new file mode 100755
index 0000000..8b9da3b
--- /dev/null
+++ b/tts_offline/mvnw
@@ -0,0 +1,286 @@
+#!/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 "$@"
diff --git a/tts_offline/mvnw.cmd b/tts_offline/mvnw.cmd
new file mode 100644
index 0000000..fef5a8f
--- /dev/null
+++ b/tts_offline/mvnw.cmd
@@ -0,0 +1,161 @@
+@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%
diff --git a/tts_offline/pom.xml b/tts_offline/pom.xml
new file mode 100644
index 0000000..c638c87
--- /dev/null
+++ b/tts_offline/pom.xml
@@ -0,0 +1,65 @@
+
+
+ 4.0.0
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 2.1.7.RELEASE
+
+
+ ai.qiwu.com
+ tts_offline
+ 0.0.1-SNAPSHOT
+ tts_offline
+ Demo project for Spring Boot
+
+
+ 1.8
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+
+ org.projectlombok
+ lombok
+ true
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+ org.apache.commons
+ commons-lang3
+ 3.9
+
+
+ org.springframework.boot
+ spring-boot-configuration-processor
+ 2.1.6.RELEASE
+ true
+
+
+ com.alibaba
+ fastjson
+ 1.2.58
+
+
+
+
+ tts-offline
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+
+
diff --git a/tts_offline/src/main/java/ai/qiwu/com/tts_offline/TtsOfflineApplication.java b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/TtsOfflineApplication.java
new file mode 100644
index 0000000..ac323e5
--- /dev/null
+++ b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/TtsOfflineApplication.java
@@ -0,0 +1,13 @@
+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);
+ }
+
+}
diff --git a/tts_offline/src/main/java/ai/qiwu/com/tts_offline/common/CallPython.java b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/common/CallPython.java
new file mode 100644
index 0000000..f064e53
--- /dev/null
+++ b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/common/CallPython.java
@@ -0,0 +1,160 @@
+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 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;
+ }
+ }
+}
diff --git a/tts_offline/src/main/java/ai/qiwu/com/tts_offline/common/ChangeSound.java b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/common/ChangeSound.java
new file mode 100644
index 0000000..2e52594
--- /dev/null
+++ b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/common/ChangeSound.java
@@ -0,0 +1,116 @@
+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 TYPES = Arrays.asList("amplitude", "power", "dB");
+ private static final List OPT_FLAG = Arrays.asList("l", "m", "s");
+ private static final List DEFAULT_DB_LIST = Arrays.asList("-70", "-60", "-20");;
+ private static final List 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 selfCommand) {
+ List 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 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 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 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 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 selfCommand) {
+ List 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 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);
+ }
+}
diff --git a/tts_offline/src/main/java/ai/qiwu/com/tts_offline/common/Config.java b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/common/Config.java
new file mode 100644
index 0000000..bbe410b
--- /dev/null
+++ b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/common/Config.java
@@ -0,0 +1,40 @@
+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();
+ }
+}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/OfflineConfig.java b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/common/OfflineConfig.java
similarity index 89%
rename from tts_service/src/main/java/ai/qiwu/com/tts_service/common/OfflineConfig.java
rename to tts_offline/src/main/java/ai/qiwu/com/tts_offline/common/OfflineConfig.java
index 5c6a9f4..c52b607 100644
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/OfflineConfig.java
+++ b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/common/OfflineConfig.java
@@ -1,4 +1,4 @@
-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;
}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/OfflineServiceUtil.java b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/common/OfflineServiceUtil.java
similarity index 94%
rename from tts_service/src/main/java/ai/qiwu/com/tts_service/common/OfflineServiceUtil.java
rename to tts_offline/src/main/java/ai/qiwu/com/tts_offline/common/OfflineServiceUtil.java
index 1e1eb63..079dfa4 100644
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/OfflineServiceUtil.java
+++ b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/common/OfflineServiceUtil.java
@@ -1,7 +1,6 @@
-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;
diff --git a/tts_offline/src/main/java/ai/qiwu/com/tts_offline/common/TTSUtils.java b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/common/TTSUtils.java
new file mode 100644
index 0000000..338449f
--- /dev/null
+++ b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/common/TTSUtils.java
@@ -0,0 +1,272 @@
+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 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 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 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 filePathList, String targetFilepath)
+ throws IOException {
+ try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(new File(targetFilepath)));){
+ AudioEnumeration 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 filePathList, String targetFilepath) throws IOException, UnsupportedAudioFileException {
+ AudioFileFormat aff = AudioSystem.getAudioFileFormat(new File(filePathList.get(0)));
+ AudioEnumeration 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 {
+ private T value;
+ private AudioNode next;
+
+ AudioNode(T value) {
+ this.value = value;
+ }
+ }
+
+ static class AudioEnumeration implements Enumeration {
+ private AudioNode head;
+ private AudioNode 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);
+ }
+}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/controller/OfflineController.java b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/controller/OfflineController.java
similarity index 84%
rename from tts_service/src/main/java/ai/qiwu/com/tts_service/controller/OfflineController.java
rename to tts_offline/src/main/java/ai/qiwu/com/tts_offline/controller/OfflineController.java
index 03ca579..a178b77 100644
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/controller/OfflineController.java
+++ b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/controller/OfflineController.java
@@ -1,9 +1,8 @@
-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");
}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/offline/OfflineOnlineCacheRequest.java b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/pojo/offline/OfflineOnlineCacheRequest.java
similarity index 93%
rename from tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/offline/OfflineOnlineCacheRequest.java
rename to tts_offline/src/main/java/ai/qiwu/com/tts_offline/pojo/offline/OfflineOnlineCacheRequest.java
index 414c335..a819995 100644
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/offline/OfflineOnlineCacheRequest.java
+++ b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/pojo/offline/OfflineOnlineCacheRequest.java
@@ -1,4 +1,4 @@
-package ai.qiwu.com.tts_service.pojo.offline;
+package ai.qiwu.com.tts_offline.pojo.offline;
import lombok.Getter;
import lombok.Setter;
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/offline/OfflineOnlineCacheResponse.java b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/pojo/offline/OfflineOnlineCacheResponse.java
similarity index 95%
rename from tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/offline/OfflineOnlineCacheResponse.java
rename to tts_offline/src/main/java/ai/qiwu/com/tts_offline/pojo/offline/OfflineOnlineCacheResponse.java
index e0dd843..acb5514 100644
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/offline/OfflineOnlineCacheResponse.java
+++ b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/pojo/offline/OfflineOnlineCacheResponse.java
@@ -1,4 +1,4 @@
-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;
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/offline/SpeakersApi.java b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/pojo/offline/SpeakersApi.java
similarity index 97%
rename from tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/offline/SpeakersApi.java
rename to tts_offline/src/main/java/ai/qiwu/com/tts_offline/pojo/offline/SpeakersApi.java
index 4dccba6..be50ab5 100644
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/offline/SpeakersApi.java
+++ b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/pojo/offline/SpeakersApi.java
@@ -1,4 +1,4 @@
-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;
diff --git a/tts_offline/src/main/java/ai/qiwu/com/tts_offline/pojo/sound/Call.java b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/pojo/sound/Call.java
new file mode 100644
index 0000000..7d5159e
--- /dev/null
+++ b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/pojo/sound/Call.java
@@ -0,0 +1,29 @@
+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;
+ }
+}
diff --git a/tts_offline/src/main/java/ai/qiwu/com/tts_offline/pojo/sound/Compand.java b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/pojo/sound/Compand.java
new file mode 100644
index 0000000..54cd915
--- /dev/null
+++ b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/pojo/sound/Compand.java
@@ -0,0 +1,31 @@
+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 dbList;
+ private String gain;
+ private String initialVolumeDb;
+ private String delay;
+
+ public Compand() {
+ }
+
+ public Compand(String attack, String decay, String softKnee, List dbList, String gain) {
+ this.attack = attack;
+ this.decay = decay;
+ this.softKnee = softKnee;
+ this.dbList = dbList;
+ this.gain = gain;
+ }
+}
diff --git a/tts_offline/src/main/java/ai/qiwu/com/tts_offline/pojo/sound/TempoAndPitch.java b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/pojo/sound/TempoAndPitch.java
new file mode 100644
index 0000000..b69fcbc
--- /dev/null
+++ b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/pojo/sound/TempoAndPitch.java
@@ -0,0 +1,18 @@
+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;
+}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/offline/OfflineService.java b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/service/OfflineService.java
similarity index 67%
rename from tts_service/src/main/java/ai/qiwu/com/tts_service/service/offline/OfflineService.java
rename to tts_offline/src/main/java/ai/qiwu/com/tts_offline/service/OfflineService.java
index b0a9d93..b2cef45 100644
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/offline/OfflineService.java
+++ b/tts_offline/src/main/java/ai/qiwu/com/tts_offline/service/OfflineService.java
@@ -1,12 +1,12 @@
-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);
}
}
diff --git a/tts_offline/src/main/resources/OfflineConfig.properties b/tts_offline/src/main/resources/OfflineConfig.properties
new file mode 100644
index 0000000..35c6de4
--- /dev/null
+++ b/tts_offline/src/main/resources/OfflineConfig.properties
@@ -0,0 +1 @@
+change_sound_path=/root/GameEditor/mqw/project/tts/pythonCode/audios.py
\ No newline at end of file
diff --git a/tts_offline/src/main/resources/application.yml b/tts_offline/src/main/resources/application.yml
new file mode 100644
index 0000000..967abf1
--- /dev/null
+++ b/tts_offline/src/main/resources/application.yml
@@ -0,0 +1,9 @@
+offline:
+ output_dir: /root/TTSOfflineService/offline
+ short_audio_dir: short_audio
+ letter_audio_dir: letter_audio
+ test_text: 这是一段测试文本,请听下音效,选择你认为合适的一套声音
+ models_threads: 3
+
+server:
+ port: 9001
diff --git a/tts_offline/src/test/java/ai/qiwu/com/tts_offline/TtsOfflineApplicationTests.java b/tts_offline/src/test/java/ai/qiwu/com/tts_offline/TtsOfflineApplicationTests.java
new file mode 100644
index 0000000..d70bc50
--- /dev/null
+++ b/tts_offline/src/test/java/ai/qiwu/com/tts_offline/TtsOfflineApplicationTests.java
@@ -0,0 +1,16 @@
+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() {
+ }
+
+}
diff --git a/tts_service/pom.xml b/tts_service/pom.xml
index 4bfebc3..521a94c 100644
--- a/tts_service/pom.xml
+++ b/tts_service/pom.xml
@@ -25,10 +25,6 @@
org.springframework.boot
- spring-boot-starter-thymeleaf
-
-
- org.springframework.boot
spring-boot-starter-web
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/CallPython.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/CallPython.java
index 941d4b9..48cf4c4 100644
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/CallPython.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/CallPython.java
@@ -1,10 +1,10 @@
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 file_ls, String tmp_audio_name) throws IOException {
+ public static String combine(List 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;
+ }
}
}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/ChangeSound.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/ChangeSound.java
new file mode 100644
index 0000000..878f7f9
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/ChangeSound.java
@@ -0,0 +1,116 @@
+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 TYPES = Arrays.asList("amplitude", "power", "dB");
+ private static final List OPT_FLAG = Arrays.asList("l", "m", "s");
+ private static final List DEFAULT_DB_LIST = Arrays.asList("-70", "-60", "-20");;
+ private static final List 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 selfCommand) {
+ List 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 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 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 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 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 selfCommand) {
+ List 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 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);
+ }
+}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/Config.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/Config.java
index 6d9d28b..054e9fe 100644
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/Config.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/Config.java
@@ -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);
}
}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/OkHttp3Utils.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/OkHttp3Utils.java
index 13661d2..fe6d68b 100644
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/OkHttp3Utils.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/OkHttp3Utils.java
@@ -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 headers, String jsonStr) throws IOException {
+ public static Integer doDeleteReturnCode(String url, Map headers, String jsonStr) throws IOException {
Request.Builder builder = new Request.Builder();
Request request = builder.url(url).build();
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/SpecialCharURLConfig.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/SpecialCharURLConfig.java
new file mode 100644
index 0000000..7a0105f
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/SpecialCharURLConfig.java
@@ -0,0 +1,21 @@
+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;
+ }
+}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSConstants.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSConstants.java
index 7497ed1..6c20d31 100644
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSConstants.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSConstants.java
@@ -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 = "对线下测试服务器的删除指令调用失败";
}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java
index 213fd1e..3cb7ec8 100644
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java
@@ -1,18 +1,19 @@
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 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 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 filePathList, String targetFilepath)
+ throws IOException {
+ try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(new File(targetFilepath)));){
+ AudioEnumeration 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 filePathList, String targetFilepath) throws IOException, UnsupportedAudioFileException {
+ AudioFileFormat aff = AudioSystem.getAudioFileFormat(new File(filePathList.get(0)));
+ AudioEnumeration 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 {
+ private T value;
+ private AudioNode next;
+
+ AudioNode(T value) {
+ this.value = value;
+ }
+ }
+
+ static class AudioEnumeration implements Enumeration {
+ private AudioNode head;
+ private AudioNode 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<>());
}
}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTServiceUtil.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTServiceUtil.java
index cbbaac5..37fe816 100644
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTServiceUtil.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTServiceUtil.java
@@ -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) {
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/controller/TTSController.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/controller/TTSController.java
index b4b2fac..03cb9ad 100644
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/controller/TTSController.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/controller/TTSController.java
@@ -1,7 +1,7 @@
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);
}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/PersonInfo.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/PersonInfo.java
index bb6e7a4..40bd324 100644
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/PersonInfo.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/PersonInfo.java
@@ -1,5 +1,6 @@
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 mood = new ArrayList<>();
+ private Boolean third_party;
public PersonInfo(String name, String sex) {
this.name = name;
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/SpeakersApiRes.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/SpeakersApiRes.java
index 6486416..5c01836 100644
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/SpeakersApiRes.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/SpeakersApiRes.java
@@ -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 online;
+ private Map offline;
- public SpeakersApiRes(String online, String offline) {
+ public SpeakersApiRes(Map online, Map offline) {
this.online = online;
this.offline = offline;
}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TTSResponse.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TTSResponse.java
index 118152e..93c3efe 100644
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TTSResponse.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TTSResponse.java
@@ -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;
}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/sound/Call.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/sound/Call.java
new file mode 100644
index 0000000..45d7926
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/sound/Call.java
@@ -0,0 +1,29 @@
+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;
+ }
+}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/sound/Compand.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/sound/Compand.java
new file mode 100644
index 0000000..50d0099
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/sound/Compand.java
@@ -0,0 +1,31 @@
+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 dbList;
+ private String gain;
+ private String initialVolumeDb;
+ private String delay;
+
+ public Compand() {
+ }
+
+ public Compand(String attack, String decay, String softKnee, List dbList, String gain) {
+ this.attack = attack;
+ this.decay = decay;
+ this.softKnee = softKnee;
+ this.dbList = dbList;
+ this.gain = gain;
+ }
+}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/sound/TempoAndPitch.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/sound/TempoAndPitch.java
new file mode 100644
index 0000000..97a80ca
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/sound/TempoAndPitch.java
@@ -0,0 +1,18 @@
+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;
+}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Initialize.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Initialize.java
index 29e5816..046b4d7 100644
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Initialize.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Initialize.java
@@ -1,5 +1,6 @@
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 PERSON_INFO_OFFLINE; //speakers_offline
private static final Map> PERSON_MOODURL; //api
private static final Map> OFFLINE_2_ONLINE;
+ private static final List 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 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 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 getPersonInfoOnline() {
+ return PERSON_INFO_ONLINE;
+ }
+
+ public static Map 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 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;
+ }
}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java
index 426cc74..6e98c36 100644
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java
@@ -2,7 +2,6 @@ package ai.qiwu.com.tts_service.service;
import ai.qiwu.com.tts_service.common.*;
import ai.qiwu.com.tts_service.pojo.*;
-import ai.qiwu.com.tts_service.repository.SpeakerInfoRepository;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
@@ -26,6 +25,12 @@ import java.util.concurrent.*;
@Service
@Slf4j
public class TTService {
+
+ private static final Integer CORE_THREAD_NUM = Runtime.getRuntime().availableProcessors();
+ private static final ThreadPoolExecutor POOL = new ThreadPoolExecutor(CORE_THREAD_NUM*2,
+ 1000, 3, TimeUnit.SECONDS, new ArrayBlockingQueue<>(15),
+ new ThreadPoolExecutor.CallerRunsPolicy());
+
private final Initialize initialize;
private final String offlineService;
@@ -33,9 +38,14 @@ public class TTService {
@Autowired
public TTService(Initialize initialize) {
this.initialize = initialize;
- this.offlineService = String.format("%s/synthesize", Config.getProperty("offline_server"));
+ this.offlineService = String.format("%s/synthesize", Initialize.getOfflineServer());
}
+ /**
+ * 退出请求的处理/返回TTS_test.mp3文件的下载链接
+ * @param request
+ * @return
+ */
public ChatBotResponse chatbot(ChatBotRequest request) {
String userId = request.getUser_id();
String text = request.getText();
@@ -45,34 +55,47 @@ public class TTService {
}
String filename = "TTS_test.mp3";
if ("file".equals(request.get_type())) filename += "&_type=file";
- String audio = "http://aliyun-hz1.chewrobot.com:9663/api/tts/get_audio?filename="+URLEncoder.encode(filename);
+ String audio = Initialize.getServerUrl()+"/api/tts/get_audio?filename="+filename;
return new ChatBotResponse(text, audio);
}
+ /**
+ * 删除本地botname目录及向线下服务器发出删除botname请求
+ * @param onlineCache
+ * @param response
+ */
public void online_cache(OnlineCache onlineCache, HttpServletResponse response) {
String botName = onlineCache.getBotname();
- if (StringUtils.isEmpty(botName)) {
+ if (StringUtils.isBlank(botName)) {
TTServiceUtil.buildOnlineCacheResponse(response, new TTSResponse(401, "no botName"), 401);
return;
}
- String bot_dir = Config.getProperty("audio_dir")+ File.separator+botName;
+ String bot_dir = Initialize.getAudioDir()+ File.separator+botName;
File deleteBotDir = new File(bot_dir);
try {
TTSUtils.deleteFile(deleteBotDir);
} catch (Exception e) {
- log.warn("删除文件出错:{}", e.toString());
+ log.warn("删除本地文件:{}出错:{}",bot_dir, e.toString());
+ TTServiceUtil.buildOnlineCacheResponse(response, new TTSResponse(555, "删除本地文件"+bot_dir+"出错"), 555);
}
- onlineCache.setServer(Config.getProperty("server_name"));
+ onlineCache.setServer(Initialize.getServerName());
String offlineStr = JSON.toJSONString(onlineCache);
- int deleteOfflineResCode;
+ int deleteOfflineResCode = -1;
+ String result = TTSConstants.DELETE_SUCCESS;
try {
- deleteOfflineResCode = OkHttp3Utils.deDeleteReturnCode(String.format("%s/online_cache",
- Config.getProperty("offline_server")), new HashMap<>(), offlineStr);
- } catch (IOException e) {
+ String url = String.format("%s/online_cache", Initialize.getOfflineServer());
+ deleteOfflineResCode = OkHttp3Utils.doDeleteReturnCode(url, new HashMap<>(), offlineStr);
+ if (deleteOfflineResCode != 200) {
+ log.error("对:{} 地址的delete请求失败,响应码:{}",url, deleteOfflineResCode);
+ result = TTSConstants.DELETE_OFFLINE_FAIL;
+ deleteOfflineResCode = 555;
+ }
+ } catch (Exception e) {
log.error("删除offline地址的bot请求出错:{}", e.toString());
+ result = TTSConstants.DELETE_FAIL;
deleteOfflineResCode = 555;
}
- TTServiceUtil.buildOnlineCacheResponse(response, new TTSResponse(deleteOfflineResCode, "no botName"), deleteOfflineResCode);
+ TTServiceUtil.buildOnlineCacheResponse(response, new TTSResponse(deleteOfflineResCode, result), deleteOfflineResCode);
}
/**
@@ -83,61 +106,82 @@ public class TTService {
* @param response
*/
public void mp3(String dirs, String filename, String _type, HttpServletResponse response) {
+ // 修正dirs的格式
if (dirs != null) {
- String dir_text = dirs;
- if ("..".equals(dir_text) || StringUtils.startsWith(dir_text, "/")) {
- TTServiceUtil.buildMp3Response(response, new MP3Response(400, "参数设置有误,不能包含..或是以/开头"), null, 400);
+ if ("..".equals(dirs) || StringUtils.startsWith(dirs, "/")) {
+ TTServiceUtil.buildMp3Response(response, new MP3Response(400, "参数设置有误,不能包含..或是以/开头"),
+ null, 400, false);
return;
}
- if (StringUtils.startsWith(dir_text, "[") && StringUtils.endsWith(dir_text, "]")) {
- dir_text = dir_text.substring(1, dir_text.length()-1);
+ if (StringUtils.startsWith(dirs, "[") && StringUtils.endsWith(dirs, "]")) {
+ dirs = dirs.substring(1, dirs.length()-1);
List dir_ls = new ArrayList<>();
- for (String dir : dir_text.split(",")) {
+ for (String dir : dirs.split(",")) {
dir_ls.add(TTSUtils.pythonStrip(dir));
}
if (StringUtils.startsWith(dir_ls.get(0), "/")) {
- TTServiceUtil.buildMp3Response(response, new MP3Response(400, "参数设置有误,参数形式如下[/,..]"), null, 400);
+ TTServiceUtil.buildMp3Response(response, new MP3Response(400, "参数设置有误,参数形式如下[/,..]"),
+ null, 400, false);
return;
}
dirs = StringUtils.join(dir_ls, "/");
}
//去除 \\ / ..
- else dirs = TTSUtils.secure_fileName(dir_text);
+ else dirs = TTSUtils.secure_fileName(dirs);
}
- log.info("filename:{}",filename);
- if (StringUtils.endsWith(filename,".mp3")) {
- filename = StringUtils.join(new String[]{Config.getProperty("audio_dir"), dirs, filename}, File.separator);
- log.info("filename:{}",filename);
+ //log.info("filename:{}",filename);
+ if (filename != null && StringUtils.endsWith(filename,".mp3")) {
+ StringBuilder builder = new StringBuilder(Initialize.getAudioDir()).append(File.separator);
+ if (StringUtils.isNotBlank(dirs)) builder.append(dirs).append(File.separator);
+ filename = builder.append(filename).toString();
+ log.info("mp3():本次请求要获取的请求的文件:{}",filename);
if (TTSUtils.doesFileExist(filename)) {
if ("file".equals(_type)) {
- TTServiceUtil.buildMp3Response(response, null, filename, 200);
+ // 请求头中添加 Content-Disposition = attachment 可下载
+ TTServiceUtil.buildMp3Response(response, null, filename, 200, true);
return;
}
- TTServiceUtil.buildMp3Response(response, null, filename, 200);
+ TTServiceUtil.buildMp3Response(response, null, filename, 200, false);
return;
}
}
- TTServiceUtil.buildMp3Response(response, new MP3Response(400), null, 400);
+ TTServiceUtil.buildMp3Response(response, new MP3Response(400), null, 400, false);
}
+ /**
+ * 音箱及app调用
+ * tts方法的list版本,根据每个text_info的数据内容下载相应的.wav文件,再转换成.mp3文件,
+ * 再根据platform字段,对于xiaoai平台的请求,我们会将请求信息相应的所有mp3文件合而为一,并返回一个访问该mp3文件的url;
+ * 对于非xiaoai平台的请求,首先将每个mp3文件的数据拷贝到对应的.mp3.b64文件,若_type为filename,则
+ * 返回.b64文件的路径列表,否则返回所有.b64文件的内容数据.
+ * @param request 请求信息
+ * @param response
+ */
public void tts_ls(TTSLSRequest request, HttpServletResponse response) {
- log.info("TTSLSRequest:{}", request);
String _type = request.get_type();
String platform = request.getPlatform();
List infoList = request.getText_info_ls();
String botName = request.getBotname();
- ExecutorService executor = null;
List> futures = new ArrayList<>();
List file_ls = new ArrayList<>();
if (infoList != null) {
- if (infoList.size() > 1) executor = Executors.newFixedThreadPool(infoList.size());
-
for (TextInfo info : infoList) {
- String person = info.getPerson() == null ? initialize.getInit_person() : info.getPerson();
+ // person没有值或是不存在则赋予init_person
+ String person = info.getPerson();
+ if (StringUtils.isBlank(person)) {
+ person = initialize.getInit_person();
+ } else if (Initialize.doesThirdPartyListHas(person)){
+ file_ls.add(Initialize.getThirdParty());
+ continue;
+ }
if (!initialize.getPersonMoodurl().containsKey(person)) person = initialize.getInit_person();
- log.info("person:{}",person);
+ //log.info("person:{}",person);
+
+ // text 字段不为空
String text = info.getText();
if (StringUtils.isBlank(text)) continue;
+
+ // 确保tone值为person的某个已有的情绪值
String tone = info.getTone() == null ? initialize.getInit_tone() : info.getTone();
Map moodUrlMap = initialize.getPersonMoodurl().get(person);
if (!moodUrlMap.containsKey(tone)) tone = initialize.getDefault_tone();
@@ -145,50 +189,59 @@ public class TTService {
if (person.equals(initialize.getInit_person())) tone = initialize.getInit_tone();
else tone = moodUrlMap.keySet().iterator().next();
}
- log.info("mood:{}",tone);
+ //log.info("mood:{}",tone);
+
+ // 获取该person的mood的url地址,获取或初始话音频操作变量
String url = moodUrlMap.get(tone);
- log.info("mood->url:{}", url);
- double volume = Double.parseDouble(info.getVolume() == null ? "0" : info.getVolume());
- double pitch = Double.parseDouble(info.getPitch() == null ? "0" : info.getVolume());
- double speed = Double.parseDouble(info.getSpeed() == null ? "1" : info.getVolume());
+ //log.info("mood->url:{}", url);
+ double volume = Double.parseDouble(StringUtils.isBlank(info.getVolume()) ? "0" : info.getVolume());
+ double pitch = Double.parseDouble(StringUtils.isBlank(info.getPitch()) ? "0" : info.getPitch());
+ double speed = Double.parseDouble(StringUtils.isBlank(info.getSpeed()) ? "1" : info.getSpeed());
+ // 目录为:(audio_dir)/botname/person/tone
String[] parents;
if (StringUtils.isBlank(botName)) {
- parents = new String[]{Config.getProperty("audio_dir"), person, tone};
+ parents = new String[]{Initialize.getAudioDir(), person, tone};
}else {
- parents = new String[]{Config.getProperty("audio_dir"), botName, person, tone};
+ parents = new String[]{Initialize.getAudioDir(), botName, person, tone};
}
String folder = StringUtils.join(parents, File.separator);
TTSUtils.makedir(folder);
+ // 生成文件名
String filepath = String.format("%s/%s", folder, TTSUtils.buildMP3Filename(text));
log.info("tts_ls方法:filepath:{}", filepath);
+
+ // 若文件不存在则先下载wav文件,之后转换成mp3
if (!TTSUtils.doesFileExist(filepath)) {
- log.info("general mp3");
- GeneralMP3Data data = new GeneralMP3Data(Config.getProperty("server_name"), text,
+ //log.info("general mp3");
+ GeneralMP3Data data = new GeneralMP3Data(Initialize.getServerName(), text,
person, tone, botName, true, volume, speed, pitch);
- if (executor != null) {
- String path = filepath;
- Future future = executor.submit(() -> generalMP3(url, data, path, "GET"));
- futures.add(future);
- }
- else {
- ResponseCodeWithData codeWithData = generalMP3(url, data, filepath, "GET");
- if (codeWithData.getCode() != 200) {
- log.error("下载:{}音频失败, status:{}", url, codeWithData.getCode());
- TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(codeWithData.getCode()), null, codeWithData.getCode());
- return;
- }
- }
+ String path = filepath;
+ Future future = POOL.submit(() -> generalMP3(url, data, path, "GET"));
+ futures.add(future);
}
+ // _type为filename的请求都将返回文件名列表
+ // xiaoai 平台的,返回如下:
+ // "audio": [
+ // "..../xxx.mp3",
+ // "......"
+ // ]
+ // 非xiaoai平台的,返回如下:
+ //"audio": [
+ // "..../xxx.mp3.b64",
+ // "......"
+ // ]
if ("filename".equals(_type) && !"xiaoai".equals(platform)) {
filepath = filepath+".b64";
}
file_ls.add(filepath);
}
- log.info("182:file list:{}", file_ls);
+
+ // 阻塞等待mp3文件生成成功
+ //log.info("196:file list:{}", file_ls);
for (Future future : futures) {
try {
- ResponseCodeWithData data = future.get(36, TimeUnit.SECONDS);
+ ResponseCodeWithData data = future.get(6, TimeUnit.SECONDS);
if (data.getCode() != 200) {
log.error("下载:{}音频失败, status:{}", data.getCode());
TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(data.getCode()), null, data.getCode());
@@ -200,36 +253,53 @@ public class TTService {
return;
}
}
+
+ // 小爱平台的请求,我们会讲所有mp3文件合在一起,文件路径为(audio_dir)/botname/xiaoai/xxx.mp3,
+ // 成功则构建请求get_audio接口的请求url,包括参数信息,返回该url
if ("xiaoai".equals(platform)) {
String tmp_name = TTSUtils.pythonlistToStr(file_ls);
String[] parents;
+ String dirs = "[xiaoai]";
if (StringUtils.isBlank(botName)) {
- parents = new String[]{Config.getProperty("audio_dir"), "xiaoai"};
+ parents = new String[]{Initialize.getAudioDir(), "xiaoai"};
}else {
- parents = new String[]{Config.getProperty("audio_dir"), botName, "xiaoai"};
+ parents = new String[]{Initialize.getAudioDir(), botName, "xiaoai"};
+ dirs = String.format("[%s,xiaoai]", botName);
}
String folder = StringUtils.join(parents, File.separator);
- String dirs = String.format("[%s,xiaoai]", botName);
String tmp_audio_name = String.format("%s/%s", folder, tmp_name);
- log.info("小爱tmp_audio_name:{}", tmp_audio_name);
+ //log.info("小爱tmp_audio_name:{}", tmp_audio_name);
try {
if (!TTSUtils.doesFileExist(tmp_audio_name)) {
TTSUtils.makedir(folder);
- log.info("调用python的combine");
- CallPython.combine(file_ls, tmp_audio_name);
+ //log.info("调用python的combine");
+ TTSUtils.combineMp3File(file_ls, tmp_audio_name);
+ //CallPython.combine(file_ls, tmp_audio_name);
+ }
+ if (!TTSUtils.doesFileExist(tmp_audio_name)) {
+ log.error("小爱平台的请求,聚合mp3文件失败");
+ TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(555, "小爱平台的请求,聚合mp3文件失败"), null, 555);
+ } else {
+ String audio = Initialize.getServerUrl()+"/api/tts/get_audio?dirs=%s&filename=%s";
+ TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(200, String.format(audio, URLEncoder.encode(dirs),
+ URLEncoder.encode(tmp_name))), null, 200);
}
- String audio = "http://aliyun-hz1.chewrobot.com:9663/api/tts/get_audio?dirs=%s&filename=%s";
- TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(200, String.format(audio, URLEncoder.encode(dirs),
- URLEncoder.encode(tmp_name))), null, 200);
} catch (Exception e) {
log.error("调用python的combine出错:{}", e.toString());
+ TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(555, "调用python的combine出错"+e.toString()), null, 555);
}
}
+ // 非xiaoai平台的请求,首先将.mp3文件的数据存储在对应的.mp3.b64文件内
+ // 若请求字段_type为filename,则返回.b64文件的路径列表,负责返回所有.b64文件的内容数据
else {
+ // 将.mp3文件的数据存储在对应的.mp3.b64文件内
for (String filename : file_ls) {
+ if (filename.equals(Initialize.getThirdParty())) {
+ continue;
+ }
String filename_64 = StringUtils.endsWith(filename, ".b64") ? filename : filename+".b64";
if (!TTSUtils.doesFileExist(filename_64)) {
- log.info("225:文件:{}不存在",filename_64);
+// log.info("241:文件:{}不存在",filename_64);
TTSUtils.cpContent(filename_64.substring(0, filename_64.length()-4), filename_64);
}
}
@@ -239,6 +309,10 @@ public class TTService {
}
List contents = new ArrayList<>();
for (String filename : file_ls) {
+ if (filename.equals(Initialize.getThirdParty())) {
+ contents.add(filename);
+ continue;
+ }
filename = filename+".b64";
try {
contents.add(TTSUtils.readAllFile(filename));
@@ -248,12 +322,15 @@ public class TTService {
}
TTServiceUtil.buildTTS_lsResponse(response, null, contents, 200);
}
+ }else {
+ TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(400, "text_info_ls字段不能为空"), null, 400);
}
}
/**
+ * 开发网页调用
* 该方法就是根据请求信息下载音频数据,生成.mp3文件,若_type是json则返回获取该生成后的.mp3文件的请求URL,
- * 否则返回该.mp3文件的内容数据
+ * 否则返回该.mp3文件
* @param ttsRequest 请求信息
* @param requestMethod 请求方法
* @param servletResponse
@@ -261,8 +338,13 @@ public class TTService {
public void tts(TTSRequest ttsRequest, String requestMethod, HttpServletResponse servletResponse) {
// 获取person,没有或数据库中不存在,则付值 init_person
String person = ttsRequest.getPerson();
+ if (Initialize.doesThirdPartyListHas(person)) {
+ TTServiceUtil.buildServletResponse(servletResponse, new TTSResponse(400,
+ Initialize.getThirdParty()), null,400);
+ return;
+ }
if (person == null || !initialize.getPersonMoodurl().containsKey(person)) person = initialize.getInit_person();
- log.info("257:person:{}", person);
+ //log.info("257:person:{}", person);
// 获取mood 没有或数据库对应person中不存在 则赋值default_mood
String mood = ttsRequest.getTone();
@@ -277,7 +359,7 @@ public class TTService {
mood = particularPersonMoodUrl.keySet().iterator().next();
}
}
- log.info("268:tone:{}",mood);
+ //log.info("268:tone:{}",mood);
// 获取该person的mood的音频地址
String moodUrl = particularPersonMoodUrl.get(mood);
@@ -291,8 +373,8 @@ public class TTService {
}
double volume = Double.parseDouble(ttsRequest.getVolume() == null ? "0" : ttsRequest.getVolume());
- double pitch = Double.parseDouble(ttsRequest.getPitch() == null ? "0" : ttsRequest.getVolume());
- double speed = Double.parseDouble(ttsRequest.getSpeed() == null ? "1" : ttsRequest.getVolume());
+ double pitch = Double.parseDouble(ttsRequest.getPitch() == null ? "0" : ttsRequest.getPitch());
+ double speed = Double.parseDouble(ttsRequest.getSpeed() == null ? "1" : ttsRequest.getSpeed());
// botname为空则赋予tmp
String botName = ttsRequest.getBotname();
@@ -301,7 +383,7 @@ public class TTService {
}
// (audio_dir)/botname/person/mood目录
- String folder = StringUtils.join(new String[]{Config.getProperty("audio_dir"), botName, person, mood}, File.separator);
+ String folder = StringUtils.join(new String[]{Initialize.getAudioDir(), botName, person, mood}, File.separator);
TTSUtils.makedir(folder);
String fileName = TTSUtils.buildMP3Filename(ttsRequest.getText());
// (audio_dir)/botname/person/mood/xxx.mp3文件路径
@@ -313,11 +395,11 @@ public class TTService {
if ("json".equals(ttsRequest.get_type())) {
String dirs = String.format("[%s,%s,%s]", botName, person, mood);
//http://(server_url)/api/tts/get_audio?dirs=[botname+person,mood]&filename=xxx.mp3
- String audio = String.format("http://%s/api/tts/get_audio?dirs=%s&filename=%s", Config.getProperty("server_url"),
- dirs, fileName);
try {
- audio = URLEncoder.encode(audio, "utf-8"); // 编码URL中的中文
- response = new TTSResponse(200, audio);
+ dirs = URLEncoder.encode(dirs, "utf-8"); // 编码URL中的中文
+ String audio = String.format("%s/api/tts/get_audio?dirs=%s&filename=%s", Initialize.getServerUrl(),
+ dirs, fileName);
+ response = new TTSResponse(audio,200);
} catch (UnsupportedEncodingException e) {
log.error("URLEncoding编码出错:{}", e.toString());
response = new TTSResponse(555, "编码URL中的中文出错");
@@ -325,7 +407,7 @@ public class TTService {
}
// filepath文件不存在或是put请求,调用generalMP3生成该filepath所指的mp3文件
if (!TTSUtils.doesFileExist(filePath) || requestMethod.equals("PUT")){
- GeneralMP3Data data = new GeneralMP3Data(Config.getProperty("server_name"), ttsRequest.getText(),
+ GeneralMP3Data data = new GeneralMP3Data(Initialize.getServerName(), ttsRequest.getText(),
person, mood, botName, true, volume, speed, pitch);
ResponseCodeWithData codeWithData = generalMP3(moodUrl, data, filePath, requestMethod);
if (codeWithData.getCode() != 200) {
@@ -353,6 +435,7 @@ public class TTService {
* @return 返回状态码,调用方法通过此来判断方法是否成功
*/
private ResponseCodeWithData generalMP3(String url, GeneralMP3Data data, String filePath, String requestMethod) {
+ //long startTime = System.currentTimeMillis();
ResponseCodeWithData res = null;
String wavFilename = filePath.substring(0, filePath.length()-4)+".wav";
if (!TTSUtils.doesFileExist(wavFilename)) {
@@ -361,22 +444,35 @@ public class TTService {
if (url.equals(offlineService)) {
longTime = false;
}
+ //long wavStartTime = System.currentTimeMillis();
+ log.info("url:{}", url);
res = requestTemplate(url, data, wavFilename, longTime);
+ //long wavEndTime = System.currentTimeMillis();
+ //log.info("wav whole time:{}", (wavEndTime-wavStartTime)/1000.0);
if (res.getCode() != 200) {
log.error("请求线上地址,下载音频文件:{},失败:{}",wavFilename,res);
return res;
}
}
if (requestMethod.equals("PUT") || (!TTSUtils.doesFileExist(filePath) && !offlineService.equals(url))) {
+ String executeResult = null;
try {
- CallPython.changeSound(wavFilename, String.valueOf(data.getVolume()), String.valueOf(data.getSpeed()),
- String.valueOf(data.getPitch()), filePath);
+ //long changeSoundStartTime = System.currentTimeMillis();
+ log.info("url:{}", url);
+ executeResult = CallPython.changeSound(wavFilename, data.getVolume(), data.getSpeed(),
+ data.getPitch(), filePath);
+ //long changeSoundEndTime = System.currentTimeMillis();
+ log.info("url:{} , call changeSound() executeResult:{}",url, executeResult);
} catch (Exception e) {
- log.error("调用python的changeSound出错:{}", e.toString());
+ log.error("调用changeSound出错:{}", e.toString());
+ res = new ResponseCodeWithData(555);
+ }
+ if (executeResult == null || !executeResult.equals("1")) {
+ log.error("mp3文件没有创建成功");
res = new ResponseCodeWithData(555);
}
}
- // 如果url是线下地址:http://aliyun-hz1.chewrobot.com:9001/synthesize 且xx.mp3文件不存在,则直接下载
+ // 如果url是线下地址且xx.mp3文件不存在,则直接下载
else if (!TTSUtils.doesFileExist(filePath) && offlineService.equals(url)) {
data.setFormat("mp3");
res = requestTemplate(url , data, filePath, false);
@@ -384,6 +480,9 @@ public class TTService {
log.error("线下请求音频文件:{},失败:{}",filePath, res);
}
}
+ //long endTime = System.currentTimeMillis();
+ //log.info("单个任务耗时时间:{}",(endTime-startTime)/1000.0);
+ if (res == null) res = new ResponseCodeWithData(200);
return res;
}
@@ -397,7 +496,7 @@ public class TTService {
*/
private ResponseCodeWithData requestTemplate(String url, GeneralMP3Data data, String filePath, boolean longTime) {
String dataStr = JSON.toJSONString(data);
- log.info("GeneralMP3Data:{}", dataStr);
+// log.info("GeneralMP3Data:{}", dataStr);
ResponseCodeWithData res = null;
File mp3File = null;
for (int i = 0; i < 3; i++) {
@@ -412,6 +511,10 @@ public class TTService {
log.error("第{}次失败,原因{}", i+1, e.toString());
continue;
}
+ if (res == null) {
+ log.error("requestTemplate请求无法获取到结果,该请求信息是:{}", data.toString());
+ return new ResponseCodeWithData(402, "requestTemplate请求无法获取到结果,该请求信息是:"+data.toString());
+ }
int resCode = res.getCode();
if (resCode == 200) {
return res;
diff --git a/tts_service/src/main/resources/application.yml b/tts_service/src/main/resources/application.yml
index a6ba6f1..fde8fcc 100644
--- a/tts_service/src/main/resources/application.yml
+++ b/tts_service/src/main/resources/application.yml
@@ -1,10 +1,13 @@
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
diff --git a/tts_service/src/main/resources/tts.properties b/tts_service/src/main/resources/tts.properties
index e67a14a..6a20def 100644
--- a/tts_service/src/main/resources/tts.properties
+++ b/tts_service/src/main/resources/tts.properties
@@ -1,6 +1,12 @@
+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
diff --git a/xiaoai/pom.xml b/xiaoai/pom.xml
index af0ac41..ea80caf 100644
--- a/xiaoai/pom.xml
+++ b/xiaoai/pom.xml
@@ -61,6 +61,11 @@
1.18.8
provided
+
+ com.squareup.okhttp3
+ okhttp
+ 4.0.0
+
diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/commons/OkHttp3Utils.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/commons/OkHttp3Utils.java
new file mode 100644
index 0000000..a8e4ca8
--- /dev/null
+++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/commons/OkHttp3Utils.java
@@ -0,0 +1,149 @@
+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 params) throws IOException {
+ return doGet(url, params, new HashMap<>());
+ }
+
+ public static String doGet(String url, Map params, Map 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> headIterator = header.entrySet().iterator();
+ headIterator.forEachRemaining(e -> headerBuilder.add(e.getKey(), e.getValue()));
+
+ Iterator> 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 params) throws IOException {
+ return doPost(url, new HashMap<>(), params,null);
+ }
+
+ public static String doPost(String url, Map params, Map 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 headers, String requestJsonStr) throws IOException {
+ Request.Builder builder = new Request.Builder();
+ Request request = builder.url(url).build();
+
+ Headers.Builder headBuilder = request.headers().newBuilder();
+
+ Iterator> 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 headers, Map params, File file) throws IOException {
+ Request.Builder builder = new Request.Builder();
+ Request request = builder.url(url).build();
+
+ Headers.Builder headBuilder = request.headers().newBuilder();
+
+ Iterator> headIterator = headers.entrySet().iterator();
+ headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
+
+ MultipartBody.Builder requestBuilder = new MultipartBody.Builder();
+ Iterator> 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 headers, Map 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> headIterator = headers.entrySet().iterator();
+ headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
+
+ MultipartBody.Builder requestBuilder = new MultipartBody.Builder();
+ Iterator> 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 headers, String jsonStr) throws IOException {
+ Request.Builder builder = new Request.Builder();
+ Request request = builder.url(url).build();
+
+ Headers.Builder headBuilder = request.headers().newBuilder();
+
+ Iterator> 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 headers, String jsonStr) throws IOException {
+ Request.Builder builder = new Request.Builder();
+ Request request = builder.url(url).build();
+
+ Headers.Builder headBuilder = request.headers().newBuilder();
+
+ Iterator> 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();
+ }
+ }
+}
diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/commons/RequestTerminal.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/commons/RequestTerminal.java
new file mode 100644
index 0000000..c3b073d
--- /dev/null
+++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/commons/RequestTerminal.java
@@ -0,0 +1,27 @@
+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 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);
+ }
+}
diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/commons/XiaoAiConstants.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/commons/XiaoAiConstants.java
index 6004bb5..1241b67 100644
--- a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/commons/XiaoAiConstants.java
+++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/commons/XiaoAiConstants.java
@@ -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";
diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/QiWuRequest.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/QiWuRequest.java
new file mode 100644
index 0000000..303a680
--- /dev/null
+++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/QiWuRequest.java
@@ -0,0 +1,18 @@
+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;
+}
diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/QiWuResponse.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/QiWuResponse.java
new file mode 100644
index 0000000..7872fc1
--- /dev/null
+++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/QiWuResponse.java
@@ -0,0 +1,13 @@
+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;
+}
diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/service/XiaoAiService.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/service/XiaoAiService.java
index 1ab030a..3fd04fc 100644
--- a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/service/XiaoAiService.java
+++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/service/XiaoAiService.java
@@ -1,9 +1,10 @@
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 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 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);
}
diff --git a/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/controller/XiaoDuController.java b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/controller/XiaoDuController.java
index 6a6f60e..3ab5343 100644
--- a/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/controller/XiaoDuController.java
+++ b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/controller/XiaoDuController.java
@@ -1,20 +1,11 @@
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
diff --git a/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/pojo/dpl/Event.java b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/pojo/dpl/Event.java
new file mode 100644
index 0000000..55190d5
--- /dev/null
+++ b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/pojo/dpl/Event.java
@@ -0,0 +1,16 @@
+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;
+}
diff --git a/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/pojo/dpl/Item.java b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/pojo/dpl/Item.java
new file mode 100644
index 0000000..70eabb2
--- /dev/null
+++ b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/pojo/dpl/Item.java
@@ -0,0 +1,46 @@
+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 onEnd;
+ private List- items;
+}
diff --git a/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/pojo/dpl/MyDocument.java b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/pojo/dpl/MyDocument.java
new file mode 100644
index 0000000..d56059e
--- /dev/null
+++ b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/pojo/dpl/MyDocument.java
@@ -0,0 +1,24 @@
+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;
+}
diff --git a/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/pojo/dpl/MyMainTemplate.java b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/pojo/dpl/MyMainTemplate.java
new file mode 100644
index 0000000..6b64e85
--- /dev/null
+++ b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/pojo/dpl/MyMainTemplate.java
@@ -0,0 +1,25 @@
+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 parameters = new ArrayList<>();
+ private List
- items;
+
+ public MyMainTemplate() {
+ this.parameters.add("payload");
+ this.items = new ArrayList<>();
+ }
+}
diff --git a/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/service/DplBotService.java b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/service/DplBotService.java
new file mode 100644
index 0000000..9e5918f
--- /dev/null
+++ b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/service/DplBotService.java
@@ -0,0 +1,137 @@
+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();
+// }
+ }
+}
diff --git a/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/service/ResponseEncapsulation.java b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/service/ResponseEncapsulation.java
index f6314a3..623900c 100644
--- a/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/service/ResponseEncapsulation.java
+++ b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/service/ResponseEncapsulation.java
@@ -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
diff --git a/xiaodu/src/main/resources/static/json/demo01.json b/xiaodu/src/main/resources/static/json/demo01.json
new file mode 100644
index 0000000..7bc3d05
--- /dev/null
+++ b/xiaodu/src/main/resources/static/json/demo01.json
@@ -0,0 +1,59 @@
+{
+ "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
diff --git a/xiaoduhome/pom.xml b/xiaoduhome/pom.xml
index 6f44619..5acd7b7 100644
--- a/xiaoduhome/pom.xml
+++ b/xiaoduhome/pom.xml
@@ -57,11 +57,6 @@
4.0.0
- com.squareup.okhttp3
- okhttp
- 4.0.0
-
-
com.alibaba
fastjson
1.2.58
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoDuHomeController.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoDuHomeController.java
index 70dee28..0dd395f 100644
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoDuHomeController.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoDuHomeController.java
@@ -1,11 +1,15 @@
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;
}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/dpl/Event.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/dpl/Event.java
new file mode 100644
index 0000000..ee3d383
--- /dev/null
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/dpl/Event.java
@@ -0,0 +1,17 @@
+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;
+}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/dpl/Item.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/dpl/Item.java
new file mode 100644
index 0000000..c6939a6
--- /dev/null
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/dpl/Item.java
@@ -0,0 +1,66 @@
+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 onEnd;
+ private List onPrepared;
+ private List onLoaded;
+ private List onPause;
+ private List onPlay;
+ private List onRelease;
+ private String command;
+
+ private List
- 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 hints;
+ private String componentId;
+}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/dpl/MyDocument.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/dpl/MyDocument.java
new file mode 100644
index 0000000..8fe9942
--- /dev/null
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/dpl/MyDocument.java
@@ -0,0 +1,19 @@
+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;
+}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/dpl/MyMainTemplate.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/dpl/MyMainTemplate.java
new file mode 100644
index 0000000..1e61197
--- /dev/null
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/dpl/MyMainTemplate.java
@@ -0,0 +1,25 @@
+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 parameters = new ArrayList<>();
+ private List
- items;
+
+ public MyMainTemplate() {
+ this.parameters.add("payload");
+ this.items = new ArrayList<>();
+ }
+}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplBotService.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplBotService.java
new file mode 100644
index 0000000..28b2b62
--- /dev/null
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplBotService.java
@@ -0,0 +1,170 @@
+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
- 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();
+ }
+}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/RequestTerminal.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/RequestTerminal.java
index 5428dc2..42b02b8 100644
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/RequestTerminal.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/RequestTerminal.java
@@ -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);
diff --git a/xiaoduhome/src/main/resources/application.properties b/xiaoduhome/src/main/resources/application.properties
index f8992a5..c4df02b 100644
--- a/xiaoduhome/src/main/resources/application.properties
+++ b/xiaoduhome/src/main/resources/application.properties
@@ -1 +1 @@
-server.port=8188
+server.port=8088
diff --git a/xiaoduhome/src/main/resources/static/json/demo01.json b/xiaoduhome/src/main/resources/static/json/demo01.json
new file mode 100644
index 0000000..13ba560
--- /dev/null
+++ b/xiaoduhome/src/main/resources/static/json/demo01.json
@@ -0,0 +1,105 @@
+{
+ "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
diff --git a/xiaoduhome/src/main/resources/static/json/onLunch.json b/xiaoduhome/src/main/resources/static/json/onLunch.json
new file mode 100644
index 0000000..fe256e9
--- /dev/null
+++ b/xiaoduhome/src/main/resources/static/json/onLunch.json
@@ -0,0 +1,93 @@
+{
+ "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
diff --git a/xiaoduhome/src/main/resources/static/json/text.json b/xiaoduhome/src/main/resources/static/json/text.json
new file mode 100644
index 0000000..9674d85
--- /dev/null
+++ b/xiaoduhome/src/main/resources/static/json/text.json
@@ -0,0 +1,59 @@
+{
+ "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