diff --git a/.idea/compiler.xml b/.idea/compiler.xml
index 1236775..72c6e9c 100644
--- a/.idea/compiler.xml
+++ b/.idea/compiler.xml
@@ -12,6 +12,7 @@
+
@@ -32,6 +33,7 @@
+
diff --git a/.idea/encodings.xml b/.idea/encodings.xml
index b9f8147..4e3340b 100644
--- a/.idea/encodings.xml
+++ b/.idea/encodings.xml
@@ -7,6 +7,7 @@
+
diff --git a/.idea/misc.xml b/.idea/misc.xml
index 4e91bec..76dbd0f 100644
--- a/.idea/misc.xml
+++ b/.idea/misc.xml
@@ -25,6 +25,7 @@
+
diff --git a/.idea/workspace.xml b/.idea/workspace.xml
index 46911f1..50dee81 100644
--- a/.idea/workspace.xml
+++ b/.idea/workspace.xml
@@ -6,26 +6,13 @@
-
-
-
-
+
-
-
-
-
-
-
-
-
+
+
-
-
-
-
@@ -41,6 +28,7 @@
+
@@ -66,64 +54,79 @@
+
+
+
+
+
+
+
+
+
+
+
+
-
+
-
-
+
+
+
+
+
-
+
-
-
+
+
-
+
-
-
+
+
+
+
+
-
+
-
-
+
+
-
-
-
-
-
-
+
+
+
-
+
-
-
+
+
-
+
-
-
+
+
@@ -131,15 +134,24 @@
+
+
+
+
+
+
+
+
+
@@ -150,10 +162,19 @@
msgId
logger
StreamResponse
+ PERSON_INFO
+ platform
+ AudioSystem
+ requestTemplate
+ generalMP3
+ Config
+ StringUtils.join
+ _type
OPENID_CACHE
log
+ PERSON_INFO_ONLINE
@@ -162,57 +183,57 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -230,6 +251,15 @@
+
+
+
+
+
+
+
+
+
@@ -245,10 +275,10 @@
-
-
+
+
-
+
@@ -259,6 +289,7 @@
+
@@ -269,77 +300,92 @@
-
+
-
+
+
-
+
+
-
+
+
-
+
+
-
+
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
+
+
+
+
+
+
+
+
+
+
+
-
+
@@ -348,16 +394,17 @@
+
+
+
+
+
-
-
-
-
@@ -370,34 +417,37 @@
-
+
-
+
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
+
+
+
+
+
+
@@ -412,13 +462,13 @@
-
-
-
-
+
+
+
+
-
+
@@ -426,8 +476,8 @@
-
-
+
+
@@ -439,12 +489,12 @@
-
-
-
+
+
+
-
+
@@ -465,19 +515,6 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
@@ -695,6 +732,22 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -744,6 +797,13 @@
+
+
+
+
+
+
+
@@ -773,11 +833,10 @@
-
-
-
+
+
@@ -785,6 +844,7 @@
+
@@ -796,14 +856,15 @@
+
+
+
+
-
-
-
@@ -852,12 +913,25 @@
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
@@ -869,10 +943,10 @@
-
+
-
+
@@ -880,455 +954,494 @@
-
+
-
-
+
+
-
+
-
+
-
-
-
-
-
-
-
+
+
+
+
+
+
+
-
+
-
+
-
+
-
-
+
+
-
-
-
+
+
+
-
+
-
+
-
+
+
-
+
-
-
-
-
-
+
+
-
+
+
-
-
+
+
-
-
+
+
+
+
+
+
-
+
-
-
+
+
-
+
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
+
+
+
+
+
+
+
-
-
+
-
+
+
+
-
+
-
-
+
+
-
+
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
+
-
-
-
-
+
-
-
+
+
+
+
+
-
+
-
-
+
+
-
+
-
-
+
+
+
+
+
+
+
-
-
-
-
+
-
-
+
+
+
+
+
+
+
-
+
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
+
+
+
+
-
+
-
-
+
+
+
+
+
+
-
+
-
-
+
+
-
+
-
-
-
-
-
+
+
-
+
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
+
+
+
-
+
-
-
+
+
+
+
+
+
+
-
+
-
-
+
+
-
-
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
+
+
+
-
+
-
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
-
-
+
+
+
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
-
+
-
+
-
-
+
+
-
-
+
-
+
-
-
+
+
+
+
+
-
+
-
-
+
+
+
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
+
-
-
+
+
+
+
+
-
+
-
-
+
+
+
+
+
diff --git a/tts_service/.gitignore b/tts_service/.gitignore
new file mode 100644
index 0000000..a2a3040
--- /dev/null
+++ b/tts_service/.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_service/.mvn/wrapper/MavenWrapperDownloader.java b/tts_service/.mvn/wrapper/MavenWrapperDownloader.java
new file mode 100644
index 0000000..7f91a56
--- /dev/null
+++ b/tts_service/.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_service/.mvn/wrapper/maven-wrapper.jar b/tts_service/.mvn/wrapper/maven-wrapper.jar
new file mode 100644
index 0000000..01e6799
Binary files /dev/null and b/tts_service/.mvn/wrapper/maven-wrapper.jar differ
diff --git a/tts_service/.mvn/wrapper/maven-wrapper.properties b/tts_service/.mvn/wrapper/maven-wrapper.properties
new file mode 100644
index 0000000..cd0d451
--- /dev/null
+++ b/tts_service/.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_service/mvnw b/tts_service/mvnw
new file mode 100755
index 0000000..8b9da3b
--- /dev/null
+++ b/tts_service/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_service/mvnw.cmd b/tts_service/mvnw.cmd
new file mode 100644
index 0000000..fef5a8f
--- /dev/null
+++ b/tts_service/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_service/pom.xml b/tts_service/pom.xml
new file mode 100644
index 0000000..4bfebc3
--- /dev/null
+++ b/tts_service/pom.xml
@@ -0,0 +1,90 @@
+
+
+ 4.0.0
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 2.1.6.RELEASE
+
+
+ ai.qiwu.com
+ tts_service
+ 0.0.1-SNAPSHOT
+ tts_service
+ Demo project for Spring Boot
+
+
+ 1.8
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-data-jpa
+
+
+ org.springframework.boot
+ spring-boot-starter-thymeleaf
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+
+ mysql
+ mysql-connector-java
+ runtime
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+ org.springframework.boot
+ spring-boot-configuration-processor
+ 2.1.6.RELEASE
+ true
+
+
+ com.squareup.okhttp3
+ okhttp
+ 4.0.0
+
+
+ com.alibaba
+ fastjson
+ 1.2.58
+
+
+ org.projectlombok
+ lombok
+ 1.18.8
+ provided
+
+
+ org.apache.commons
+ commons-lang3
+ 3.9
+
+
+
+
+
+
+
+
+
+
+ tts
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+
+
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/TtsServiceApplication.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/TtsServiceApplication.java
new file mode 100644
index 0000000..b54a643
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/TtsServiceApplication.java
@@ -0,0 +1,17 @@
+package ai.qiwu.com.tts_service;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.autoconfigure.domain.EntityScan;
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
+
+@SpringBootApplication
+@EntityScan(basePackages = {"ai.qiwu.com.tts_service.entity"})
+@EnableJpaRepositories(basePackages = {"ai.qiwu.com.tts_service.repository"})
+public class TtsServiceApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(TtsServiceApplication.class, args);
+ }
+
+}
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
new file mode 100644
index 0000000..08a5af2
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/CallPython.java
@@ -0,0 +1,73 @@
+package ai.qiwu.com.tts_service.common;
+
+import lombok.extern.slf4j.Slf4j;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.nio.Buffer;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author 苗权威
+ * @dateTime 19-8-2 上午9:51
+ */
+@Slf4j
+public class CallPython {
+
+ private static final String INTERPRETER = "/usr/bin/python3";
+
+ private static final String AUDIO_FILE = "/home/yf01/pythonWork/audio.py";
+
+ 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);
+ }
+ log.info("change Sound result:{}", result.toString());
+ reader.close();
+ }
+
+ public static void 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);
+ }
+ log.info("combine result:{}", result.toString());
+ reader.close();
+ }
+
+ public static void changeSound() throws IOException {
+ String[] args = {INTERPRETER, "/home/yf01/pythonWork/hello.py", "1", "2"};
+ 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);
+ }
+ log.info("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);
+ }
+
+}
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
new file mode 100644
index 0000000..6d9d28b
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/Config.java
@@ -0,0 +1,42 @@
+package ai.qiwu.com.tts_service.common;
+
+import lombok.Getter;
+import lombok.Setter;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.UnsupportedEncodingException;
+import java.util.Properties;
+
+/**
+ * @author 苗权威
+ * @dateTime 19-7-30 下午2:40
+ */
+@Slf4j
+public class Config {
+ private static Properties properties;
+
+ static {
+ String filename = "tts.properties";
+ properties = new Properties();
+ try {
+ properties.load(new InputStreamReader(Config.class.getClassLoader().getResourceAsStream(filename), "UTF-8"));
+ } catch (IOException e) {
+ log.error("获取配置文件对象出错:{}", e.toString());
+ }
+ }
+
+ 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/ErrorMsgEnum.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/ErrorMsgEnum.java
new file mode 100644
index 0000000..f08c873
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/ErrorMsgEnum.java
@@ -0,0 +1,46 @@
+package ai.qiwu.com.tts_service.common;
+
+import lombok.Getter;
+import lombok.Setter;
+
+/**
+ * @author 苗权威
+ * @dateTime 19-7-31 上午10:04
+ */
+public enum ErrorMsgEnum {
+ FAIL_DEL_OFFLINE_BOT(1001, "删除offline地址的bot请求出错"),
+ FAIL_IN_CREATE_DIR(1002, "创建文件失败");
+
+ private int code;
+ private String msg;
+
+ ErrorMsgEnum(int code, String msg) {
+ this.code = code;
+ this.msg = msg;
+ }
+
+ public static String findMsgByCode(int code) {
+ for (ErrorMsgEnum item: ErrorMsgEnum.values()) {
+ if (item.getCode() == code) {
+ return item.getMsg();
+ }
+ }
+ return null;
+ }
+
+ public int getCode() {
+ return code;
+ }
+
+ public void setCode(int code) {
+ this.code = code;
+ }
+
+ public String getMsg() {
+ return msg;
+ }
+
+ public void setMsg(String msg) {
+ this.msg = msg;
+ }
+}
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
new file mode 100644
index 0000000..13661d2
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/OkHttp3Utils.java
@@ -0,0 +1,208 @@
+package ai.qiwu.com.tts_service.common;
+
+import ai.qiwu.com.tts_service.pojo.ResponseCodeWithData;
+import lombok.extern.slf4j.Slf4j;
+import okhttp3.*;
+import okio.BufferedSink;
+import okio.Okio;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * @author 苗权威
+ * @dateTime 19-7-18 上午10:54
+ */
+@Slf4j
+public class OkHttp3Utils {
+ private static final OkHttpClient client = new OkHttpClient.Builder().connectTimeout(12, TimeUnit.SECONDS).build();
+
+ private static final OkHttpClient ShortTimeoutClient = new OkHttpClient.Builder().connectTimeout(3, TimeUnit.SECONDS).build();
+
+ 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 ResponseCodeWithData doPostTimeout(String url, Map headers,
+ String requestJsonStr, File file, boolean longTime) throws IOException {
+ OkHttpClient timeoutClient;
+ if (longTime) {
+ timeoutClient = client;
+ } else {
+ timeoutClient = ShortTimeoutClient;
+ }
+
+ 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));
+ ResponseCodeWithData codeWithData = null;
+ try (Response response = timeoutClient.newCall(builder.build()).execute()){
+ log.info("doPostTimeout请求返回:{}", response.code());
+ if (response.code() == 200) {
+ if (file != null) {
+ try (BufferedSink sink = Okio.buffer(Okio.sink(file))){
+ sink.writeAll(Objects.requireNonNull(response.body()).source());
+ codeWithData = new ResponseCodeWithData(response.code());
+ }
+ } else {
+ codeWithData = new ResponseCodeWithData(response.code(), response.body().string());
+ }
+ }
+ return codeWithData;
+ }
+ }
+
+ 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();
+ }
+ }
+
+ public static Integer deDeleteReturnCode(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.code();
+ }
+ }
+}
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
new file mode 100644
index 0000000..7497ed1
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSConstants.java
@@ -0,0 +1,11 @@
+package ai.qiwu.com.tts_service.common;
+
+import org.springframework.beans.factory.annotation.Autowired;
+
+/**
+ * @author 苗权威
+ * @dateTime 19-7-31 下午2:30
+ */
+public interface TTSConstants {
+ String DEFAULT_MOOD = "正常";
+}
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
new file mode 100644
index 0000000..4b3fe79
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java
@@ -0,0 +1,163 @@
+package ai.qiwu.com.tts_service.common;
+
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.util.DigestUtils;
+
+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;
+
+/**
+ * @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 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 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 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;
+ 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")));
+ }
+ writer.write(builder.toString());
+ writer.flush();
+ } catch (Exception e) {
+ log.error("转移文件内容出错:{}", e.toString());
+ }
+ }
+
+ 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;
+ StringBuilder builder = new StringBuilder();
+ builder.append("data:audio/mp3;base64,");
+ while ((ln = input.read(buffer)) != -1) {
+ builder.append(new String(buffer, 0, ln));
+ }
+ 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 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));
+ }
+}
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
new file mode 100644
index 0000000..cbbaac5
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTServiceUtil.java
@@ -0,0 +1,109 @@
+package ai.qiwu.com.tts_service.common;
+
+import ai.qiwu.com.tts_service.pojo.MP3Response;
+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 javax.servlet.http.HttpServletResponse;
+import java.io.*;
+import java.util.List;
+
+/**
+ * @author 苗权威
+ * @dateTime 19-8-1 下午8:26
+ */
+@Slf4j
+public class TTServiceUtil {
+
+ public static void buildOnlineCacheResponse(HttpServletResponse response, TTSResponse ttsResponse, int status) {
+ String ttsResJsonStr = JSON.toJSONString(ttsResponse);
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application/json;charset=utf-8");
+ response.setStatus(status);
+ try (PrintWriter out = response.getWriter()){
+ out.append(ttsResJsonStr);
+ out.flush();
+ } catch (Exception e) {
+ log.error("获取PrintWriter出错:{}",e.toString());
+ }
+ }
+
+ public static void buildMp3Response(HttpServletResponse response, MP3Response mp3Response, String fileName, int status) {
+ response.setStatus(status);
+ if (mp3Response != null) {
+ String ttsResJsonStr = JSON.toJSONString(mp3Response);
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application/json;charset=utf-8");
+ try (PrintWriter out = response.getWriter()){
+ out.append(ttsResJsonStr);
+ out.flush();
+ } catch (Exception e) {
+ log.error("获取PrintWriter出错:{}",e.toString());
+ }
+ } else {
+ try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(fileName));
+ OutputStream out = new BufferedOutputStream(response.getOutputStream())){
+ response.reset();
+ response.setContentType("audio/mp3");
+ byte[] buffer = new byte[1024];
+ int ln;
+ while ((ln = inputStream.read(buffer)) != -1) {
+ out.write(buffer, 0, ln);
+ }
+ out.flush();
+ } catch (Exception e) {
+ log.error("写入音频流到HttpServletResponse失败:{}", e.toString());
+ }
+ }
+ }
+
+ public static void buildTTS_lsResponse(HttpServletResponse servletResponse, TTSResponse ttsResponse, List list, int status) {
+ servletResponse.setStatus(status);
+ String ttsResJsonStr;
+ if (ttsResponse != null) {
+ ttsResJsonStr = JSON.toJSONString(ttsResponse);
+ } else {
+ ResponseStatusWithList statusWithList = new ResponseStatusWithList(200, list);
+ ttsResJsonStr = JSON.toJSONString(statusWithList);
+ }
+ servletResponse.setCharacterEncoding("UTF-8");
+ servletResponse.setContentType("application/json;charset=utf-8");
+ try (PrintWriter out = servletResponse.getWriter()){
+ out.append(ttsResJsonStr);
+ out.flush();
+ } catch (Exception e) {
+ log.error("获取PrintWriter出错:{}",e.toString());
+ }
+ }
+
+ public static void buildServletResponse(HttpServletResponse servletResponse, TTSResponse ttsResponse, File file, int status) {
+ servletResponse.setStatus(status);
+ if (ttsResponse == null) {
+ try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
+ OutputStream out = new BufferedOutputStream(servletResponse.getOutputStream())){
+ servletResponse.reset();
+ servletResponse.setContentType("audio/mp3");
+ byte[] buffer = new byte[1024];
+ int ln;
+ while ((ln = inputStream.read(buffer)) != -1) {
+ out.write(buffer, 0, ln);
+ }
+ out.flush();
+ } catch (Exception e) {
+ log.error("写入音频流到HttpServletResponse失败:{}", e.toString());
+ }
+ } else {
+ String ttsResJsonStr = JSON.toJSONString(ttsResponse);
+ servletResponse.setCharacterEncoding("UTF-8");
+ servletResponse.setContentType("application/json;charset=utf-8");
+ try (PrintWriter out = servletResponse.getWriter()){
+ out.append(ttsResJsonStr);
+ out.flush();
+ } catch (Exception e) {
+ log.error("获取PrintWriter出错:{}",e.toString());
+ }
+ }
+ }
+}
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
new file mode 100644
index 0000000..9aa2136
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/controller/TTSController.java
@@ -0,0 +1,75 @@
+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.TTService;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.*;
+
+import javax.servlet.http.HttpServletResponse;
+
+
+/**
+ * @author 苗权威
+ * @dateTime 19-7-30 下午5:49
+ */
+@RestController
+@Slf4j
+@RequestMapping("/mqw")
+public class TTSController {
+
+// @Autowired
+ private final TTService ttService;
+
+ @Autowired
+ public TTSController(TTService ttService) {
+ this.ttService = ttService;
+ }
+
+ @DeleteMapping("/online_cache")
+ public void online_cache(@RequestBody OnlineCache onlineCache, HttpServletResponse response) {
+ ttService.online_cache(onlineCache, response);
+ }
+
+ @GetMapping("/api/speakers")
+ public SpeakersApiRes speakers_api() {
+ return new SpeakersApiRes(Config.getProperty("online_sever"), Config.getProperty("offline_server"));
+ }
+
+ @GetMapping("/api/tts")
+ public void tts(@RequestParam(required = false) String person, @RequestParam(required = false) String tone,
+ @RequestParam(required = false) String text, @RequestParam(required = false) String botname,
+ @RequestParam(required = false) String _type, @RequestParam(required = false) String volume,
+ @RequestParam(required = false) String pitch, @RequestParam(required = false) String speed,
+ HttpServletResponse servletResponse) {
+ TTSRequest ttsRequest = new TTSRequest(person, text, _type, pitch, tone, botname, volume, speed);
+ ttService.tts(ttsRequest, "GET", servletResponse);
+ }
+
+ @PostMapping("/api/tts")
+ public void tts(@RequestBody TTSRequest ttsRequest, HttpServletResponse response) {
+ ttService.tts(ttsRequest, "POST", response);
+ }
+
+ @PutMapping("/api/tts")
+ public void tts(HttpServletResponse response, @RequestBody TTSRequest ttsRequest) {
+ ttService.tts(ttsRequest, "PUT", response);
+ }
+
+ @PostMapping("/api/tts_ls")
+ public void tts_ls(@RequestBody TTSLSRequest request, HttpServletResponse response) {
+ ttService.tts_ls(request, response);
+ }
+
+ @GetMapping("/api/tts/get_audio")
+ public void mp3(@RequestParam(required = false) String dirs, @RequestParam(required = false) String filename,
+ @RequestParam(required = false) String _type, HttpServletResponse response) {
+ ttService.mp3(dirs, filename, _type, response);
+ }
+
+ @PostMapping("/api/chatbot")
+ public ChatBotResponse chatbot(@RequestBody ChatBotRequest request) {
+ return ttService.chatbot(request);
+ }
+}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/entity/SpeakersInfo.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/entity/SpeakersInfo.java
new file mode 100644
index 0000000..ecebb1e
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/entity/SpeakersInfo.java
@@ -0,0 +1,52 @@
+package ai.qiwu.com.tts_service.entity;
+
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
+import org.hibernate.annotations.GenericGenerator;
+import org.springframework.data.jpa.domain.AbstractPersistable;
+
+import javax.persistence.*;
+
+/**
+ * @author 苗权威
+ * @dateTime 19-7-30 下午1:24
+ */
+@Entity
+@Table(name = "speakers_info")
+@Getter
+@Setter
+@ToString
+public class SpeakersInfo {
+
+ @Id
+ @GeneratedValue
+ private Integer id;
+
+ @Column
+ private String person;
+
+ @Column
+ private String name;
+
+ @Column
+ private String sex;
+
+ @Column
+ private String mood;
+
+ @Column(name = "model_name")
+ private String modelName;
+
+ @Column
+ private Integer jump; // null
+
+ @Column
+ private String hparams; //''
+
+ @Column(name = "with_online")
+ private Integer withOnline; // 0
+
+ @Column(name = "is_delete")
+ private String isDelete; //'0'
+}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/ChatBotRequest.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/ChatBotRequest.java
new file mode 100644
index 0000000..c4197ea
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/ChatBotRequest.java
@@ -0,0 +1,26 @@
+package ai.qiwu.com.tts_service.pojo;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
+
+/**
+ * @author 苗权威
+ * @dateTime 19-8-1 下午8:14
+ */
+@Getter
+@Setter
+@ToString
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class ChatBotRequest {
+ private String user_id;
+ private String text;
+ private String _type;
+
+ public ChatBotRequest(String user_id, String text, String _type) {
+ this.user_id = user_id;
+ this.text = text;
+ this._type = _type;
+ }
+}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/ChatBotResponse.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/ChatBotResponse.java
new file mode 100644
index 0000000..ed2a76d
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/ChatBotResponse.java
@@ -0,0 +1,28 @@
+package ai.qiwu.com.tts_service.pojo;
+
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
+
+/**
+ * @author 苗权威
+ * @dateTime 19-8-1 下午8:18
+ */
+@Getter
+@Setter
+@ToString
+@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
+public class ChatBotResponse {
+ private String text;
+ private String audio;
+
+ public ChatBotResponse(String text) {
+ this.text = text;
+ }
+
+ public ChatBotResponse(String text, String audio) {
+ this.text = text;
+ this.audio = audio;
+ }
+}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/GeneralMP3Data.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/GeneralMP3Data.java
new file mode 100644
index 0000000..2ad2219
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/GeneralMP3Data.java
@@ -0,0 +1,39 @@
+package ai.qiwu.com.tts_service.pojo;
+
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
+
+/**
+ * @author 苗权威
+ * @dateTime 19-7-31 下午1:34
+ */
+@Getter
+@Setter
+@ToString
+public class GeneralMP3Data {
+ private String server;
+ private String text;
+ private String person;
+ private String tone;
+ private String botname;
+ private Boolean cache;
+ private Double volume;
+ private Double speed;
+ private Double pitch;
+
+ private String format;
+
+ public GeneralMP3Data(String server, String text, String person, String tone, String botname,
+ Boolean cache, Double volume, Double speed, Double pitch) {
+ this.server = server;
+ this.text = text;
+ this.person = person;
+ this.tone = tone;
+ this.botname = botname;
+ this.cache = cache;
+ this.volume = volume;
+ this.speed = speed;
+ this.pitch = pitch;
+ }
+}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/MP3Response.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/MP3Response.java
new file mode 100644
index 0000000..ead4c98
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/MP3Response.java
@@ -0,0 +1,28 @@
+package ai.qiwu.com.tts_service.pojo;
+
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
+
+/**
+ * @author 苗权威
+ * @dateTime 19-8-1 下午5:32
+ */
+@Getter
+@Setter
+@ToString
+@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
+public class MP3Response {
+ private Integer status;
+ private String message;
+
+ public MP3Response(Integer status, String message) {
+ this.status = status;
+ this.message = message;
+ }
+
+ public MP3Response(Integer status) {
+ this.status = status;
+ }
+}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/OnlineCache.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/OnlineCache.java
new file mode 100644
index 0000000..b7711a9
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/OnlineCache.java
@@ -0,0 +1,17 @@
+package ai.qiwu.com.tts_service.pojo;
+
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
+
+/**
+ * @author 苗权威
+ * @dateTime 19-7-30 下午6:46
+ */
+@Getter
+@Setter
+@ToString
+public class OnlineCache {
+ private String botname;
+ private String server;
+}
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
new file mode 100644
index 0000000..bb6e7a4
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/PersonInfo.java
@@ -0,0 +1,26 @@
+package ai.qiwu.com.tts_service.pojo;
+
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author 苗权威
+ * @dateTime 19-7-30 下午3:27
+ */
+@Getter
+@Setter
+@ToString
+public class PersonInfo {
+ private String name;
+ private String sex;
+ private List mood = new ArrayList<>();
+
+ public PersonInfo(String name, String sex) {
+ this.name = name;
+ this.sex = sex;
+ }
+}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/ResponseCodeWithData.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/ResponseCodeWithData.java
new file mode 100644
index 0000000..01cc327
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/ResponseCodeWithData.java
@@ -0,0 +1,26 @@
+package ai.qiwu.com.tts_service.pojo;
+
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
+
+/**
+ * @author 苗权威
+ * @dateTime 19-7-31 下午2:24
+ */
+@Getter
+@Setter
+@ToString
+public class ResponseCodeWithData {
+ private int code;
+ private String res;
+
+ public ResponseCodeWithData(int code, String res) {
+ this.code = code;
+ this.res = res;
+ }
+
+ public ResponseCodeWithData(int code) {
+ this.code = code;
+ }
+}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/ResponseStatusWithList.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/ResponseStatusWithList.java
new file mode 100644
index 0000000..aebb459
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/ResponseStatusWithList.java
@@ -0,0 +1,24 @@
+package ai.qiwu.com.tts_service.pojo;
+
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
+
+import java.util.List;
+
+/**
+ * @author 苗权威
+ * @dateTime 19-8-1 下午3:52
+ */
+@Getter
+@Setter
+@ToString
+public class ResponseStatusWithList {
+ private Integer status;
+ private List audio;
+
+ public ResponseStatusWithList(Integer status, List audio) {
+ this.status = status;
+ this.audio = audio;
+ }
+}
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
new file mode 100644
index 0000000..6486416
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/SpeakersApiRes.java
@@ -0,0 +1,22 @@
+package ai.qiwu.com.tts_service.pojo;
+
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
+
+/**
+ * @author 苗权威
+ * @dateTime 19-7-30 下午8:29
+ */
+@Getter
+@Setter
+@ToString
+public class SpeakersApiRes {
+ private String online;
+ private String offline;
+
+ public SpeakersApiRes(String online, String offline) {
+ this.online = online;
+ this.offline = offline;
+ }
+}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TTSLSRequest.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TTSLSRequest.java
new file mode 100644
index 0000000..84d7abd
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TTSLSRequest.java
@@ -0,0 +1,24 @@
+package ai.qiwu.com.tts_service.pojo;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
+
+import java.util.List;
+
+/**
+ * @author 苗权威
+ * @dateTime 19-8-1 上午10:38
+ */
+@Getter
+@Setter
+@ToString
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class TTSLSRequest {
+ private String _type;
+ private String platform;
+ private List text_info_ls;
+ private String botname;
+ private String person;
+}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TTSRequest.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TTSRequest.java
new file mode 100644
index 0000000..8e402ef
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TTSRequest.java
@@ -0,0 +1,37 @@
+package ai.qiwu.com.tts_service.pojo;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
+
+/**
+ * @author 苗权威
+ * @dateTime 19-7-30 下午8:44
+ */
+@Getter
+@Setter
+@ToString
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class TTSRequest {
+ private String person;
+ private String text;
+ private String _type;
+ private String pitch;
+ private String tone;
+ private String botname;
+ private String volume;
+ private String speed;
+
+ public TTSRequest(String person, String text, String _type, String pitch,
+ String tone, String botname, String volume, String speed) {
+ this.person = person;
+ this.text = text;
+ this._type = _type;
+ this.pitch = pitch;
+ this.tone = tone;
+ this.botname = botname;
+ this.volume = volume;
+ this.speed = speed;
+ }
+}
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
new file mode 100644
index 0000000..118152e
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TTSResponse.java
@@ -0,0 +1,31 @@
+package ai.qiwu.com.tts_service.pojo;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
+
+/**
+ * @author 苗权威
+ * @dateTime 19-7-30 下午6:53
+ */
+@Getter
+@Setter
+@ToString
+@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
+public class TTSResponse {
+ private Integer status;
+ private String message;
+ private String audio;
+
+ public TTSResponse(Integer status, String message) {
+ this.status = status;
+ this.message = message;
+ }
+
+ public TTSResponse(Integer status) {
+ this.status = status;
+ }
+}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TextInfo.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TextInfo.java
new file mode 100644
index 0000000..0d1d626
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TextInfo.java
@@ -0,0 +1,26 @@
+package ai.qiwu.com.tts_service.pojo;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
+
+/**
+ * @author 苗权威
+ * @dateTime 19-8-1 上午10:40
+ */
+@Getter
+@Setter
+@ToString
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class TextInfo {
+ private String person;
+ private String text;
+ private String tone;
+ private String volume;
+ private String pitch;
+ private String speed;
+ private Boolean cache;
+ private String server;
+ private String botname;
+}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/repository/SpeakerInfoRepository.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/repository/SpeakerInfoRepository.java
new file mode 100644
index 0000000..7061270
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/repository/SpeakerInfoRepository.java
@@ -0,0 +1,14 @@
+package ai.qiwu.com.tts_service.repository;
+
+import ai.qiwu.com.tts_service.entity.SpeakersInfo;
+import org.springframework.data.jpa.repository.JpaRepository;
+
+import java.util.List;
+
+/**
+ * @author 苗权威
+ * @dateTime 19-7-30 下午2:07
+ */
+public interface SpeakerInfoRepository extends JpaRepository {
+ List findByIsDelete(String isDelete);
+}
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
new file mode 100644
index 0000000..29e5816
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Initialize.java
@@ -0,0 +1,133 @@
+package ai.qiwu.com.tts_service.service;
+
+import ai.qiwu.com.tts_service.common.Config;
+import ai.qiwu.com.tts_service.common.TTSConstants;
+import ai.qiwu.com.tts_service.pojo.PersonInfo;
+import ai.qiwu.com.tts_service.entity.SpeakersInfo;
+import ai.qiwu.com.tts_service.repository.SpeakerInfoRepository;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.InitializingBean;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * @author 苗权威
+ * @dateTime 19-7-30 下午5:05
+ */
+@Component
+@Slf4j
+public class Initialize implements InitializingBean {
+ private String init_person = "B05";
+ private String init_tone = "正常";
+ private String init_url;
+
+ private static final List URL_LS;
+ private static final Map PERSON_INFO_ONLINE; //speakers_online
+ private static final Map PERSON_INFO_OFFLINE; //speakers_offline
+ private static final Map> PERSON_MOODURL; //api
+ private static final Map> OFFLINE_2_ONLINE;
+
+ private final SpeakerInfoRepository speakerInfoRepository;
+
+ static {
+ URL_LS = new ArrayList<>();
+ PERSON_INFO_ONLINE = new HashMap<>();
+ PERSON_INFO_OFFLINE = new HashMap<>();
+ PERSON_MOODURL = new HashMap<>();
+ OFFLINE_2_ONLINE = new HashMap<>();
+ }
+
+ @Autowired
+ public Initialize(SpeakerInfoRepository speakerInfoRepository) {
+ this.speakerInfoRepository = speakerInfoRepository;
+ }
+
+ private void initialize(SpeakersInfo speakerInfo) {
+ String name = speakerInfo.getName();
+ String sex = speakerInfo.getSex();
+ String mood = speakerInfo.getMood();
+ Integer jump = speakerInfo.getJump();
+ Integer withOnLine = speakerInfo.getWithOnline();
+ String person = speakerInfo.getPerson();
+ String person_offline = person+"_offline";
+ if (withOnLine != null && withOnLine != 0) {
+ String url = String.format("%s:9%03d/synthesize", Config.getProperty("online_sever"), speakerInfo.getId());
+ URL_LS.add(url);
+ if (StringUtils.isBlank(init_person)) {
+ init_person = person;
+ }
+
+ PersonInfo personInfo_online = PERSON_INFO_ONLINE.computeIfAbsent(person, k -> new PersonInfo(name, sex));
+ personInfo_online.getMood().add(mood);
+
+ Map mood_url = PERSON_MOODURL.computeIfAbsent(person, k -> new HashMap<>());
+ mood_url.put(mood, url);
+ }
+
+ PersonInfo personInfo_offline = PERSON_INFO_OFFLINE.computeIfAbsent(person_offline, k -> new PersonInfo(name, sex));
+ personInfo_offline.getMood().add(mood);
+
+ if (jump != null) {
+ 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));
+ }
+
+ Map mood_url = PERSON_MOODURL.computeIfAbsent(person_offline, k -> new HashMap<>());
+ mood_url.putIfAbsent(mood, String.format("%s/synthesize", Config.getProperty("offline_server")));
+ }
+
+ @Override
+ public void afterPropertiesSet() throws Exception {
+ List speakerInfos = speakerInfoRepository.findByIsDelete("0");
+ for (SpeakersInfo speakerInfo: speakerInfos) {
+ initialize(speakerInfo);
+ }
+ if (!PERSON_INFO_ONLINE.containsKey(init_person)) {
+ init_person = PERSON_INFO_ONLINE.keySet().iterator().next();
+ }
+ List moodList = PERSON_INFO_ONLINE.get(init_person).getMood();
+ if (!moodList.contains(init_tone)) {
+ init_tone = moodList.get(0);
+ }
+ init_url = PERSON_MOODURL.get(init_person).get(init_tone);
+ 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);
+ }
+
+ String getInit_person() {
+ return init_person;
+ }
+
+ Map> getPersonMoodurl() {
+ return PERSON_MOODURL;
+ }
+
+ String getDefault_tone() {
+ return TTSConstants.DEFAULT_MOOD;
+ }
+
+ String getInit_tone() {
+ return init_tone;
+ }
+
+ Map getThePersonJumpUrls(String person) {
+ return OFFLINE_2_ONLINE.get(person);
+ }
+
+ boolean doesThisMoodUrlWithOnline0(String url) {
+ return !URL_LS.contains(url);
+ }
+
+ String getInit_url() {
+ return init_url;
+ }
+}
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
new file mode 100644
index 0000000..5c3de9a
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java
@@ -0,0 +1,479 @@
+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;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.*;
+import java.net.URLEncoder;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.*;
+
+
+/**
+ * @author 苗权威
+ * @dateTime 19-7-30 下午2:29
+ */
+@Service
+@Slf4j
+public class TTService {
+ private final Initialize initialize;
+
+ private final String offlineService;
+
+ @Autowired
+ public TTService(Initialize initialize) {
+ this.initialize = initialize;
+ this.offlineService = String.format("%s/synthesize", Config.getProperty("offline_server"));
+ }
+
+ public ChatBotResponse chatbot(ChatBotRequest request) {
+ String userId = request.getUser_id();
+ String text = request.getText();
+ log.info("userId:{},text:{}", userId, text);
+ if ("退出文艺平台".equals(text) || "退出文艺大厅".equals(text)) {
+ return new ChatBotResponse("退出");
+ }
+ 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);
+ return new ChatBotResponse(text, audio);
+ }
+
+ public void online_cache(OnlineCache onlineCache, HttpServletResponse response) {
+ String botName = onlineCache.getBotname();
+ if (StringUtils.isEmpty(botName)) {
+ TTServiceUtil.buildOnlineCacheResponse(response, new TTSResponse(401, "no botName"), 401);
+ return;
+ }
+ String bot_dir = Config.getProperty("audio_dir")+ File.separator+botName;
+ File deleteBotDir = new File(bot_dir);
+ try {
+ TTSUtils.deleteFile(deleteBotDir);
+ } catch (Exception e) {
+ log.warn("删除文件出错:{}", e.toString());
+ }
+ onlineCache.setServer(Config.getProperty("server_name"));
+ String offlineStr = JSON.toJSONString(onlineCache);
+ int deleteOfflineResCode;
+ try {
+ deleteOfflineResCode = OkHttp3Utils.deDeleteReturnCode(String.format("%s/online_cache",
+ Config.getProperty("offline_server")), new HashMap<>(), offlineStr);
+ } catch (IOException e) {
+ log.error("删除offline地址的bot请求出错:{}", e.toString());
+ deleteOfflineResCode = 500;
+ }
+ TTServiceUtil.buildOnlineCacheResponse(response, new TTSResponse(deleteOfflineResCode, "no botName"), deleteOfflineResCode);
+ }
+
+ /**
+ * 参数dirs与filename指向一个mp3音频文件,返回该文件内容数据
+ * @param dirs mp3音频文件路径
+ * @param filename mp3音频文件名称
+ * @param _type
+ * @param response
+ */
+ public void mp3(String dirs, String filename, String _type, HttpServletResponse response) {
+ if (dirs != null) {
+ String dir_text = dirs;
+ if ("..".equals(dir_text) || StringUtils.startsWith(dir_text, "/")) {
+ TTServiceUtil.buildMp3Response(response, new MP3Response(400, "参数设置有误,不能包含..或是以/开头"), null, 400);
+ return;
+ }
+ if (StringUtils.startsWith(dir_text, "[") && StringUtils.endsWith(dir_text, "]")) {
+ dir_text = dir_text.substring(1, dir_text.length()-1);
+ List dir_ls = new ArrayList<>();
+ for (String dir : dir_text.split(",")) {
+ dir_ls.add(TTSUtils.pythonStrip(dir));
+ }
+ if (StringUtils.startsWith(dir_ls.get(0), "/")) {
+ TTServiceUtil.buildMp3Response(response, new MP3Response(400, "参数设置有误,参数形式如下[/,..]"), null, 400);
+ return;
+ }
+ dirs = StringUtils.join(dir_ls, "/");
+ }
+ //去除 \\ / ..
+ else dirs = TTSUtils.secure_fileName(dir_text);
+ }
+ 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);
+ if (TTSUtils.doesFileExist(filename)) {
+ if ("file".equals(_type)) {
+ TTServiceUtil.buildMp3Response(response, null, filename, 200);
+ return;
+ }
+ TTServiceUtil.buildMp3Response(response, null, filename, 200);
+ return;
+ }
+ }
+ TTServiceUtil.buildMp3Response(response, new MP3Response(400), null, 400);
+ }
+
+ 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();
+ if (!initialize.getPersonMoodurl().containsKey(person)) person = initialize.getInit_person();
+ log.info("person:{}",person);
+ String text = info.getText();
+ if (StringUtils.isBlank(text)) continue;
+ String tone = info.getTone() == null ? initialize.getInit_tone() : info.getTone();
+ Map moodUrlMap = initialize.getPersonMoodurl().get(person);
+ if (!moodUrlMap.containsKey(tone)) tone = initialize.getDefault_tone();
+ if (!moodUrlMap.containsKey(tone)) {
+ if (person.equals(initialize.getInit_person())) tone = initialize.getInit_tone();
+ else tone = moodUrlMap.keySet().iterator().next();
+ }
+ log.info("mood:{}",tone);
+ 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());
+
+ String[] parents;
+ if (StringUtils.isBlank(botName)) {
+ parents = new String[]{Config.getProperty("audio_dir"), person, tone};
+ }else {
+ parents = new String[]{Config.getProperty("audio_dir"), 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);
+ if (!TTSUtils.doesFileExist(filepath)) {
+ log.info("general mp3");
+ GeneralMP3Data data = new GeneralMP3Data(Config.getProperty("server_name"), 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;
+ }
+ }
+ }
+ if ("filename".equals(_type) && !"xiaoai".equals(platform)) {
+ filepath = filepath+".b64";
+ }
+ file_ls.add(filepath);
+ }
+ log.info("182:file list:{}", file_ls);
+ for (Future future : futures) {
+ try {
+ ResponseCodeWithData data = future.get(36, TimeUnit.SECONDS);
+ if (data.getCode() != 200) {
+ log.error("下载:{}音频失败, status:{}", data.getCode());
+ TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(data.getCode()), null, data.getCode());
+ return;
+ }
+ } catch (InterruptedException | ExecutionException | TimeoutException e) {
+ log.error("获取结果出错:{}", e.toString());
+ TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(400), null, 400);
+ return;
+ }
+ }
+ if ("xiaoai".equals(platform)) {
+ String tmp_name = TTSUtils.pythonlistToStr(file_ls);
+ String[] parents;
+ if (StringUtils.isBlank(botName)) {
+ parents = new String[]{Config.getProperty("audio_dir"), "xiaoai"};
+ }else {
+ parents = new String[]{Config.getProperty("audio_dir"), botName, "xiaoai"};
+ }
+ 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);
+ try {
+ if (!TTSUtils.doesFileExist(tmp_audio_name)) {
+ TTSUtils.makedir(folder);
+ log.info("调用python的combine");
+ CallPython.combine(file_ls, tmp_audio_name);
+ }
+ 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());
+ }
+ }
+ else {
+ for (String filename : file_ls) {
+ String filename_64 = StringUtils.endsWith(filename, ".b64") ? filename : filename+".b64";
+ if (!TTSUtils.doesFileExist(filename_64)) {
+ log.info("225:文件:{}不存在",filename_64);
+ TTSUtils.cpContent(filename_64.substring(0, filename_64.length()-4), filename_64);
+ }
+ }
+ if ("filename".equals(_type)) {
+ TTServiceUtil.buildTTS_lsResponse(response, null, file_ls, 200);
+ return;
+ }
+ List contents = new ArrayList<>();
+ for (String filename : file_ls) {
+ filename = filename+".b64";
+ try {
+ contents.add(TTSUtils.readAllFile(filename));
+ } catch (Exception e) {
+ log.error("读取文件{}内容出错:{}", filename, e.toString());
+ }
+ }
+ TTServiceUtil.buildTTS_lsResponse(response, null, contents, 200);
+ }
+ }
+ }
+
+ /**
+ * 该方法就是根据请求信息下载音频数据,生成.mp3文件,若_type是json则返回获取该生成后的.mp3文件的请求URL,
+ * 否则返回该.mp3文件的内容数据
+ * @param ttsRequest 请求信息
+ * @param requestMethod 请求方法
+ * @param servletResponse
+ */
+ public void tts(TTSRequest ttsRequest, String requestMethod, HttpServletResponse servletResponse) {
+ // 获取person,没有或数据库中不存在,则付值 init_person
+ String person = ttsRequest.getPerson();
+ if (person == null || !initialize.getPersonMoodurl().containsKey(person)) person = initialize.getInit_person();
+ log.info("257:person:{}", person);
+
+ // 获取mood 没有或数据库对应person中不存在 则赋值default_mood
+ String mood = ttsRequest.getTone();
+ Map particularPersonMoodUrl = initialize.getPersonMoodurl().get(person);
+ if (mood == null || !particularPersonMoodUrl.containsKey(mood)) mood = initialize.getDefault_tone();
+
+ //如果person不存在该mood,若person为init_person则赋值init_mood,否则随机返回一个该person的mood
+ if (!particularPersonMoodUrl.containsKey(mood)) {
+ if (person.equals(initialize.getInit_person())) {
+ mood = initialize.getInit_tone();
+ }else {
+ mood = particularPersonMoodUrl.keySet().iterator().next();
+ }
+ }
+ log.info("268:tone:{}",mood);
+
+ // 获取该person的mood的音频地址
+ String moodUrl = particularPersonMoodUrl.get(mood);
+ log.info("270:moodurl:{}", moodUrl);
+
+ // text字段不能为空
+ String text = ttsRequest.getText();
+ if (StringUtils.isBlank(text)) {
+ TTServiceUtil.buildServletResponse(servletResponse, new TTSResponse(404, "文本不能为空"), null, 404);
+ return;
+ }
+
+ 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());
+
+ // botname为空则赋予tmp
+ String botName = ttsRequest.getBotname();
+ if (StringUtils.isBlank(botName)) {
+ botName = "tmp";
+ }
+
+ // (audio_dir)/botname/person/mood目录
+ String folder = StringUtils.join(new String[]{Config.getProperty("audio_dir"), botName, person, mood}, File.separator);
+ TTSUtils.makedir(folder);
+ String fileName = TTSUtils.buildMP3Filename(ttsRequest.getText());
+ // (audio_dir)/botname/person/mood/xxx.mp3文件路径
+ String filePath = StringUtils.join(new String[]{folder, fileName}, File.separator);
+ log.info("filepath:{}", filePath);
+
+ TTSResponse response = null;
+ // _type为json,则构建请求get_audio接口的信息
+ 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);
+ } catch (UnsupportedEncodingException e) {
+ log.error("URLEncoding编码出错:{}", e.toString());
+ response = new TTSResponse(500, "编码URL中的中文出错");
+ }
+ }
+ // filepath文件不存在或是put请求,调用generalMP3生成该filepath所指的mp3文件
+ if (!TTSUtils.doesFileExist(filePath) || requestMethod.equals("PUT")){
+ GeneralMP3Data data = new GeneralMP3Data(Config.getProperty("server_name"), ttsRequest.getText(),
+ person, mood, botName, true, volume, speed, pitch);
+ ResponseCodeWithData codeWithData = generalMP3(moodUrl, data, filePath, requestMethod);
+ if (codeWithData.getCode() != 200) {
+ log.error("下载:{}音频失败", moodUrl);
+ TTServiceUtil.buildServletResponse(servletResponse, new TTSResponse(codeWithData.getCode()), null, codeWithData.getCode());
+ return;
+ }
+ }
+ if (response == null) {
+ TTServiceUtil.buildServletResponse(servletResponse, null, new File(filePath), 200);
+ } else {
+ TTServiceUtil.buildServletResponse(servletResponse, response, null, 200);
+ }
+ }
+
+ /**
+ * 若文件已存在则不进行覆盖,除非是put更新请求.
+ * 首先从音频下载地址下载数据到本地,文件地址为filepath(该文件原指的是mp3文件,先改为wav文件),
+ * 该下载好的wav文件经过python的change_sound方法生成mp3文件,该文件即filepath.
+ *
+ * @param url 音频下载地址
+ * @param data 请求信息
+ * @param filePath mp3文件的地址
+ * @param requestMethod 请求方法
+ * @return 返回状态码,调用方法通过此来判断方法是否成功
+ */
+ private ResponseCodeWithData generalMP3(String url, GeneralMP3Data data, String filePath, String requestMethod) {
+ ResponseCodeWithData res = null;
+ String wavFilename = filePath.substring(0, filePath.length()-4)+".wav";
+ if (!TTSUtils.doesFileExist(wavFilename)) {
+ data.setFormat("wav");
+ boolean longTime = true;
+ if (url.equals(offlineService)) {
+ longTime = false;
+ }
+ res = requestTemplate(url, data, wavFilename, longTime);
+ if (res.getCode() != 200) {
+ log.error("请求线上地址,下载音频文件:{},失败:{}",wavFilename,res);
+ return res;
+ }
+ }
+ if (requestMethod.equals("PUT") || (!TTSUtils.doesFileExist(filePath) && !offlineService.equals(url))) {
+ try {
+ CallPython.changeSound(wavFilename, String.valueOf(data.getVolume()), String.valueOf(data.getSpeed()),
+ String.valueOf(data.getPitch()), filePath);
+ } catch (Exception e) {
+ log.error("调用python的changeSound出错:{}", e.toString());
+ res = new ResponseCodeWithData(500);
+ }
+ }
+ // 如果url是线下地址:http://aliyun-hz1.chewrobot.com:9001/synthesize 且xx.mp3文件不存在,则直接下载
+ else if (!TTSUtils.doesFileExist(filePath) && offlineService.equals(url)) {
+ data.setFormat("mp3");
+ res = requestTemplate(url , data, filePath, false);
+ if (res.getCode() != 200) {
+ log.error("线下请求音频文件:{},失败:{}",filePath, res);
+ }
+ }
+ return res;
+ }
+
+ /**
+ * 下载音频文件或只是普通的post请求,失败尝试次数3
+ * @param url 音频请求地址
+ * @param data 请求信息
+ * @param filePath 文件地址
+ * @param longTime 线下测试超时为3s,线上为12s
+ * @return 返回状态码,调用方法通过此来判断方法是否成功
+ */
+ private ResponseCodeWithData requestTemplate(String url, GeneralMP3Data data, String filePath, boolean longTime) {
+ String dataStr = JSON.toJSONString(data);
+ log.info("GeneralMP3Data:{}", dataStr);
+ ResponseCodeWithData res = null;
+ File mp3File = null;
+ for (int i = 0; i < 3; i++) {
+ try {
+ if (filePath != null) {
+ mp3File = TTSUtils.createFileReturnIts(filePath);
+ res = OkHttp3Utils.doPostTimeout(url, new HashMap<>(), dataStr, mp3File, longTime);
+ } else {
+ res = OkHttp3Utils.doPostTimeout(url, new HashMap<>(), dataStr, null, longTime);
+ }
+ } catch (Exception e) {
+ log.error("第{}次失败,原因{}", i+1, e.toString());
+ continue;
+ }
+ int resCode = res.getCode();
+ if (resCode == 200) {
+ return res;
+ }
+ else if (resCode == 404 && url.equals(offlineService)) {
+ String person = data.getPerson();
+ String mood = data.getTone();
+ try {
+ url = "";
+ Map moodJumpUrl = initialize.getThePersonJumpUrls(person);
+ if (moodJumpUrl != null) {
+ if ((url = moodJumpUrl.get(mood)) == null) url = "";
+ }
+ if (initialize.doesThisMoodUrlWithOnline0(url)) {
+ url = initialize.getInit_url();
+ }
+ res = requestLongTimeout(url, dataStr, mp3File);
+ } catch (Exception e) {
+ log.error("person:{},mood:{}, url not found", person, mood);
+ res = null;
+ break;
+ }
+ }
+ }
+ if (res == null) {
+ log.error("请求无法获取到结果,该请求信息是:{}", data.toString());
+ return new ResponseCodeWithData(402, null);
+ }
+ if (res.getCode() != 200) {
+ log.info("请求不成功,该请求信息是:{}", data.toString());
+ }
+ return res;
+ }
+
+ /**
+ * 线下请求超时的话尝试将时间延长为12s再次进行请求,失败尝试次数3
+ * @param url 音频请求地址
+ * @param dataJsonStr 请求信息
+ * @param file 是否是下载音频文件的请求
+ * @return 返回状态码,调用方法通过此来判断方法是否成功
+ */
+ private ResponseCodeWithData requestLongTimeout(String url, String dataJsonStr, File file) {
+ ResponseCodeWithData res = null;
+ for (int i = 0; i < 3; i++) {
+ try {
+ if (file != null) {
+ res = OkHttp3Utils.doPostTimeout(url, new HashMap<>(), dataJsonStr, file, true);
+ }else {
+ res = OkHttp3Utils.doPostTimeout(url, new HashMap<>(), dataJsonStr, null, true);
+ }
+ } catch (Exception e) {
+ log.error("第{}次失败,原因{}", i+1, e.toString());
+ continue;
+ }
+ int resCode = res == null ? 500 : res.getCode();
+ if (resCode == 200) {
+ break;
+ }
+ }
+ if (res == null) {
+ log.error("请求无法获取到结果:{},该请求信息是:{}", url,dataJsonStr);
+ }
+ return res;
+ }
+}
diff --git a/tts_service/src/main/resources/application.yml b/tts_service/src/main/resources/application.yml
new file mode 100644
index 0000000..c7a0f88
--- /dev/null
+++ b/tts_service/src/main/resources/application.yml
@@ -0,0 +1,21 @@
+spring:
+ datasource:
+# 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
+ show-sql: true
+ hibernate:
+ ddl-auto: none
+ output:
+ ansi:
+ enabled: detect
+#logging:
+# level: info
+# path: /usr/mqw/logs/tts
+server:
+ port: 8088
diff --git a/tts_service/src/main/resources/tts.properties b/tts_service/src/main/resources/tts.properties
new file mode 100644
index 0000000..e67a14a
--- /dev/null
+++ b/tts_service/src/main/resources/tts.properties
@@ -0,0 +1,6 @@
+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
diff --git a/tts_service/src/test/java/ai/qiwu/com/tts_service/TtsServiceApplicationTests.java b/tts_service/src/test/java/ai/qiwu/com/tts_service/TtsServiceApplicationTests.java
new file mode 100644
index 0000000..2841647
--- /dev/null
+++ b/tts_service/src/test/java/ai/qiwu/com/tts_service/TtsServiceApplicationTests.java
@@ -0,0 +1,29 @@
+package ai.qiwu.com.tts_service;
+
+import ai.qiwu.com.tts_service.common.TTSUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.util.DigestUtils;
+
+import java.nio.charset.StandardCharsets;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest
+public class TtsServiceApplicationTests {
+
+ @Test
+ public void contextLoads() {
+ }
+
+ @Test
+ public void createFileTest() {
+ String fileName = DigestUtils.md5DigestAsHex("text".getBytes(StandardCharsets.UTF_8));
+ fileName = StringUtils.join(new String[]{fileName, "mp3"}, ".");
+ boolean result = TTSUtils.createFile("/usr/springbootdemo/优美/A307/女声高兴", fileName);
+ System.out.println(result);
+ }
+
+}
diff --git a/xiaodu/pom.xml b/xiaodu/pom.xml
index 1e296b4..477fde3 100644
--- a/xiaodu/pom.xml
+++ b/xiaodu/pom.xml
@@ -11,7 +11,7 @@
ai.qiwu.baidu
xiaodu
0.0.1-SNAPSHOT
-
+ war
xiaodu
Demo project for Spring Boot
@@ -23,14 +23,21 @@
org.springframework.boot
spring-boot-starter-web
-
-
-
-
-
-
+
+
+ org.springframework.boot
+ spring-boot-starter-tomcat
+
+
+
+
+
+
+
+
+
javax.servlet
@@ -45,6 +52,12 @@
test
+
+
+
+
+
+
com.baidu.dueros
bot-sdk
@@ -57,11 +70,6 @@
1.2.0
- org.apache.httpcomponents
- httpclient
- 4.5.8
-
-
com.alibaba
fastjson
1.2.58
@@ -72,11 +80,6 @@
1.18.8
provided
-
- com.squareup.okhttp3
- okhttp
- 4.0.0
-
org.springframework.boot
@@ -99,21 +102,21 @@
commons-fileupload
1.4
-
-
- com.github.ipld
- java-cid
- v1.1.1
-
+
+
+
+
+
+
-
-
- jitpack.io
- https://jitpack.io
-
-
+
+
+
+
+
+
xiaodu
diff --git a/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/XiaoduApplication.java b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/XiaoduApplication.java
index ab14281..920fbc8 100644
--- a/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/XiaoduApplication.java
+++ b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/XiaoduApplication.java
@@ -8,14 +8,14 @@ import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
-public class XiaoduApplication{
+public class XiaoduApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(XiaoduApplication.class, args);
}
-// @Override
-// protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
-// return builder.sources(XiaoduApplication.class);
-// }
+ @Override
+ protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
+ return builder.sources(XiaoduApplication.class);
+ }
}
diff --git a/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/common/Utils.java b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/common/Utils.java
index 4b299c6..316453d 100644
--- a/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/common/Utils.java
+++ b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/common/Utils.java
@@ -1,7 +1,6 @@
package ai.qiwu.baidu.xiaodu.common;
import ai.qiwu.baidu.xiaodu.pojo.product.response.ProductIdRequest;
-import io.ipfs.cid.Cid;
import org.apache.commons.codec.binary.Base64;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
@@ -9,8 +8,6 @@ import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
/**
* @author 苗权威
diff --git a/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/pojo/AudioUrlAndText.java b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/pojo/AudioUrlAndText.java
index 4953fd6..c69d072 100644
--- a/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/pojo/AudioUrlAndText.java
+++ b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/pojo/AudioUrlAndText.java
@@ -1,26 +1,17 @@
package ai.qiwu.baidu.xiaodu.pojo;
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
+
/**
* @author 苗权威
* @dateTime 19-6-29 下午4:32
*/
+@Getter
+@Setter
+@ToString
public class AudioUrlAndText {
- private String audioUrl;
+ private String audio;
private String text;
-
- public String getAudioUrl() {
- return audioUrl;
- }
-
- public void setAudioUrl(String audioUrl) {
- this.audioUrl = audioUrl;
- }
-
- public String getText() {
- return text;
- }
-
- public void setText(String text) {
- this.text = text;
- }
}
diff --git a/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/pojo/QiWuRequest.java b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/pojo/QiWuRequest.java
new file mode 100644
index 0000000..de58afe
--- /dev/null
+++ b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/pojo/QiWuRequest.java
@@ -0,0 +1,16 @@
+package ai.qiwu.baidu.xiaodu.pojo;
+
+import lombok.Getter;
+import lombok.Setter;
+
+/**
+ * @author 苗权威
+ * @dateTime 19-7-10 下午2:29
+ */
+@Getter
+@Setter
+public class QiWuRequest {
+ private String user_id;
+ private String text;
+ private String access;
+}
diff --git a/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/service/RequestTerminal.java b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/service/RequestTerminal.java
index 58d831e..91e9219 100644
--- a/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/service/RequestTerminal.java
+++ b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/service/RequestTerminal.java
@@ -1,9 +1,13 @@
package ai.qiwu.baidu.xiaodu.service;
import ai.qiwu.baidu.xiaodu.common.Constants;
+import ai.qiwu.baidu.xiaodu.common.OkHttp3Utils;
import ai.qiwu.baidu.xiaodu.pojo.AudioUrlAndText;
+import ai.qiwu.baidu.xiaodu.pojo.QiWuRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
+import lombok.extern.slf4j.Slf4j;
+import okhttp3.*;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
@@ -21,52 +25,63 @@ import java.util.HashMap;
* @author 苗权威
* @dateTime 19-6-29 下午3:49
*/
+@Slf4j
class RequestTerminal {
- private static final Logger logger = LoggerFactory.getLogger(RequestTerminal.class);
-
- static AudioUrlAndText requestTerminate(String word, String userId) {
- AudioUrlAndText store = new AudioUrlAndText();
- String audioUrl = "";
- String textContent = "请说推荐作品";
- CloseableHttpClient httpClient = null;
- CloseableHttpResponse httpResponse = null;
- try {
- httpClient = HttpClientBuilder.create().build();
- HttpPost post = new HttpPost(Constants.QI_WU_INTERFACE);
-
- HashMap params = new HashMap<>();
- params.put("user_id", String.valueOf(userId));
- params.put("text", word);
- params.put("access",Constants.SERVICE_NAME);
-
- String paramsJsonFormat = JSON.toJSONString(params);
- StringEntity body = new StringEntity(paramsJsonFormat, "UTF-8");
- post.setHeader("Content-Type", "application/json;charset=utf-8");
- post.setEntity(body);
-
- httpResponse = httpClient.execute(post);
- HttpEntity responseBody = httpResponse.getEntity();
- if (responseBody != null) {
- String responseContent = EntityUtils.toString(responseBody);
- logger.info("齐悟接口返回: "+ responseContent);
- JSONObject responseJsonFormat = JSONObject.parseObject(responseContent);
- audioUrl = (String) responseJsonFormat.get("audio");
- textContent = (String) responseJsonFormat.get("text");
- }
- } catch (IOException e) {
- logger.error("请求齐悟接口出错:"+e.toString());
- return null;
- } finally {
- try {
- if (httpClient != null) httpClient.close();
- if (httpResponse != null) httpResponse.close();
- } catch (IOException e) {
- logger.error("关闭与齐悟接口时出错:"+e.toString());
- }
- }
- store.setAudioUrl(audioUrl);
- store.setText(textContent);
- return store;
+ static AudioUrlAndText requestTerminate(String userWord, String userId) throws IOException {
+ QiWuRequest requestPojo = new QiWuRequest();
+ requestPojo.setUser_id(userId);
+ requestPojo.setAccess(Constants.SERVICE_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(Constants.QI_WU_INTERFACE, headers, requestJsonStr);
+ return JSON.parseObject(resStr, AudioUrlAndText.class);
}
+
+// static AudioUrlAndText requestTerminate(String word, String userId) {
+// AudioUrlAndText store = new AudioUrlAndText();
+// String audioUrl = "";
+// String textContent = "请说推荐作品";
+// CloseableHttpClient httpClient = null;
+// CloseableHttpResponse httpResponse = null;
+// try {
+// httpClient = HttpClientBuilder.create().build();
+// HttpPost post = new HttpPost(Constants.QI_WU_INTERFACE);
+//
+// HashMap params = new HashMap<>();
+// params.put("user_id", String.valueOf(userId));
+// params.put("text", word);
+// params.put("access",Constants.SERVICE_NAME);
+//
+// String paramsJsonFormat = JSON.toJSONString(params);
+// StringEntity body = new StringEntity(paramsJsonFormat, "UTF-8");
+// post.setHeader("Content-Type", "application/json;charset=utf-8");
+// 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.error("请求齐悟接口出错:"+e.toString());
+// return null;
+// } finally {
+// try {
+// if (httpClient != null) httpClient.close();
+// if (httpResponse != null) httpResponse.close();
+// } catch (IOException e) {
+// log.error("关闭与齐悟接口时出错:"+e.toString());
+// }
+// }
+// store.setAudioUrl(audioUrl);
+// store.setText(textContent);
+// return store;
+// }
}
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 5807205..733f9ce 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
@@ -5,12 +5,10 @@ import ai.qiwu.baidu.xiaodu.common.Constants.ErrorMsg;
import ai.qiwu.baidu.xiaodu.common.Constants.EndMsg;
import ai.qiwu.baidu.xiaodu.common.Constants.WelcomeWord;
import ai.qiwu.baidu.xiaodu.common.OkHttp3Utils;
-import ai.qiwu.baidu.xiaodu.common.TokenHolder;
import ai.qiwu.baidu.xiaodu.common.Utils;
import ai.qiwu.baidu.xiaodu.pojo.AudioUrlAndText;
import ai.qiwu.baidu.xiaodu.pojo.GetTokenByRefreshToken;
import ai.qiwu.baidu.xiaodu.pojo.GetUserInfoByToken;
-import ai.qiwu.baidu.xiaodu.service.productManager.ProductManager;
import com.alibaba.fastjson.JSON;
import com.baidu.dueros.bot.AudioPlayer;
import com.baidu.dueros.data.request.*;
@@ -29,10 +27,6 @@ import com.baidu.dueros.data.response.directive.audioplayer.AudioPlayerDirective
import com.baidu.dueros.data.response.directive.audioplayer.Content;
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.audioplayer.control.BaseButton;
-import com.baidu.dueros.data.response.directive.display.Hint;
-import com.baidu.dueros.data.response.directive.display.RenderTemplate;
-import com.baidu.dueros.data.response.directive.display.templates.*;
import com.baidu.dueros.data.response.directive.pay.Buy;
import com.baidu.dueros.data.response.directive.pay.Charge;
import com.baidu.dueros.model.Request;
@@ -48,10 +42,6 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ScheduledThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.locks.ReentrantLock;
import static ai.qiwu.baidu.xiaodu.common.Constants.EndMsg.BYE_BYE;
@@ -224,12 +214,24 @@ public class ResponseEncapsulation extends AudioPlayer {
}
}
}else {
- AudioUrlAndText data = RequestTerminal.requestTerminate(userWord, userId);
+ AudioUrlAndText data = null;
+ try {
+ data = RequestTerminal.requestTerminate(userWord, userId);
+ } catch (IOException e) {
+ logger.error("请求终端接口出错:", e.toString());
+ }
if (data == null) {
return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
}
- String audioUrl = data.getAudioUrl();
- addDirective(buildPlayDirective(audioUrl, data.getText(), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL));
+ 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));
+ }
// String uri = "https://aliyun-hz1.chewrobot.com/xiaodu/image/5b2d0a11/lvzhou/1564033095964d39f.jpg";
// ImageStructure imageStructure = new ImageStructure(uri, 512, 512);
@@ -366,6 +368,10 @@ public class ResponseEncapsulation extends AudioPlayer {
return play;
}
+ private Play buildNoScreenPlayDirec(String audioUrl, AudioPlayerDirective.PlayBehaviorType type) {
+ return new Play(type, audioUrl, 0);
+ }
+
/**
* 不想对每个事件都进行处理,通过重写onDefaultEvent方法来统一处理。
* 任何事件都不允许开麦
diff --git a/xiaodu/src/main/resources/application.properties b/xiaodu/src/main/resources/application.properties
index 7423c16..5399f21 100644
--- a/xiaodu/src/main/resources/application.properties
+++ b/xiaodu/src/main/resources/application.properties
@@ -1,13 +1,18 @@
-#logging.path=/usr/mqw/logs/xiaodu
-#logging.level.root = info
-#spring.output.ansi.enabled=detect
+logging.path=/usr/mqw/logs/xiaodu
+logging.level.root = info
+spring.output.ansi.enabled=detect
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
#开发时关闭缓存,不然没法看到实时页面
-spring.thymeleaf.cache=false
+#spring.thymeleaf.cache=false
image.upload.path = /root/GameEditor/mqw/xiaodu/image/
-server.port=8088
+#server.port=8088
+
+#spring.datasource.name=root
+#spring.datasource.password=mysql
+#spring.datasource.url=jdbc:mysql://127.0.0.1:3306/do_product
+#spring.datasource.driver-class-name=com.mysql.jdbc.Driver