Commit 7df5f4da by 苗权威

8.3

parent 70c123c2
...@@ -12,6 +12,7 @@ ...@@ -12,6 +12,7 @@
<module name="ruoqi" /> <module name="ruoqi" />
<module name="spirit" /> <module name="spirit" />
<module name="third_party_load" /> <module name="third_party_load" />
<module name="tts_service" />
<module name="xiaoai" /> <module name="xiaoai" />
<module name="xiaodu" /> <module name="xiaodu" />
<module name="xiaoduhome" /> <module name="xiaoduhome" />
...@@ -32,6 +33,7 @@ ...@@ -32,6 +33,7 @@
<module name="ruoqi" options="-parameters" /> <module name="ruoqi" options="-parameters" />
<module name="spirit" options="-parameters -extdirs /usr/local/intellij/workplace/smartbox/spirit/src/main/resources/lib" /> <module name="spirit" options="-parameters -extdirs /usr/local/intellij/workplace/smartbox/spirit/src/main/resources/lib" />
<module name="third_party_load" options="-parameters" /> <module name="third_party_load" options="-parameters" />
<module name="tts_service" options="-parameters" />
<module name="xiaoai" options="-parameters" /> <module name="xiaoai" options="-parameters" />
<module name="xiaodu" options="-parameters" /> <module name="xiaodu" options="-parameters" />
<module name="xiaoduhome" options="-parameters" /> <module name="xiaoduhome" options="-parameters" />
......
...@@ -7,6 +7,7 @@ ...@@ -7,6 +7,7 @@
<file url="file://$PROJECT_DIR$/ruoqi" charset="UTF-8" /> <file url="file://$PROJECT_DIR$/ruoqi" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/spirit" charset="UTF-8" /> <file url="file://$PROJECT_DIR$/spirit" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/third_party_load" charset="UTF-8" /> <file url="file://$PROJECT_DIR$/third_party_load" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/tts_service" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/xiaoai" charset="UTF-8" /> <file url="file://$PROJECT_DIR$/xiaoai" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/xiaodu" charset="UTF-8" /> <file url="file://$PROJECT_DIR$/xiaodu" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/xiaoduhome" charset="UTF-8" /> <file url="file://$PROJECT_DIR$/xiaoduhome" charset="UTF-8" />
......
...@@ -25,6 +25,7 @@ ...@@ -25,6 +25,7 @@
<option value="$PROJECT_DIR$/open/pom.xml" /> <option value="$PROJECT_DIR$/open/pom.xml" />
<option value="$PROJECT_DIR$/third_party_load/pom.xml" /> <option value="$PROJECT_DIR$/third_party_load/pom.xml" />
<option value="$PROJECT_DIR$/xiaoduhome/pom.xml" /> <option value="$PROJECT_DIR$/xiaoduhome/pom.xml" />
<option value="$PROJECT_DIR$/tts_service/pom.xml" />
</list> </list>
</option> </option>
</component> </component>
......
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/src/test/**
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
### VS Code ###
.vscode/
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.Properties;
public class MavenWrapperDownloader {
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL =
"https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: : " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
# TODO classpath?
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
wget "$jarUrl" -O "$wrapperJarPath"
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
curl -o "$wrapperJarPath" "$jarUrl"
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
echo Found %WRAPPER_JAR%
) else (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"
echo Finished downloading %WRAPPER_JAR%
)
@REM End of extension
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>ai.qiwu.com</groupId>
<artifactId>tts_service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>tts_service</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>2.1.6.RELEASE</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
<!--&lt;!&ndash; https://mvnrepository.com/artifact/org.python/jython-standalone &ndash;&gt;-->
<!--<dependency>-->
<!--<groupId>org.python</groupId>-->
<!--<artifactId>jython-standalone</artifactId>-->
<!--<version>2.7.1</version>-->
<!--</dependency>-->
</dependencies>
<build>
<finalName>tts</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
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);
}
}
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<String> file_ls, String tmp_audio_name) throws IOException {
StringBuilder builder = new StringBuilder();
for (String file : file_ls) builder.append(file).append(",");
String fileList = builder.toString().substring(0, builder.length()-1);
String[] args = {INTERPRETER, COMBINE_FILE, fileList, tmp_audio_name};
Process process = Runtime.getRuntime().exec(args);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
StringBuilder result = new StringBuilder();
while ((line = reader.readLine()) != null) {
result.append(line);
}
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);
}
}
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();
}
}
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;
}
}
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<String, String> params) throws IOException {
return doGet(url, params, new HashMap<>());
}
public static String doGet(String url, Map<String, String> params, Map<String, String> header) throws IOException {
Request.Builder builder = new Request.Builder();
Request request = builder.url(url).build();
HttpUrl.Builder urlBuild = request.url().newBuilder();
Headers.Builder headerBuilder = request.headers().newBuilder();
Iterator<Map.Entry<String, String>> headIterator = header.entrySet().iterator();
headIterator.forEachRemaining(e -> headerBuilder.add(e.getKey(), e.getValue()));
Iterator<Map.Entry<String, String>> paramsIterator = params.entrySet().iterator();
paramsIterator.forEachRemaining(e -> urlBuild.addQueryParameter(e.getKey(), e.getValue()));
builder.url(urlBuild.build()).headers(headerBuilder.build());
try (Response response = client.newCall(builder.build()).execute()){
return response.body().string();
}
}
public static String doPost(String url, Map<String, String> params) throws IOException {
return doPost(url, new HashMap<>(), params,null);
}
public static String doPost(String url, Map<String, String> params, Map<String, String> headers) throws IOException {
return doPost(url, headers, params, null);
}
public static String doPost(String url, File file) throws IOException {
return doPost(url , new HashMap<>(), new HashMap<>(), file);
}
public static String doPostJsonStr(String url, Map<String, String> headers, String requestJsonStr) throws IOException {
Request.Builder builder = new Request.Builder();
Request request = builder.url(url).build();
Headers.Builder headBuilder = request.headers().newBuilder();
Iterator<Map.Entry<String, String>> headIterator = headers.entrySet().iterator();
headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
builder.headers(headBuilder.build()).post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr));
try (Response response = client.newCall(builder.build()).execute()){
return response.body().string();
}
}
public static ResponseCodeWithData doPostTimeout(String url, Map<String, String> 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<Map.Entry<String, String>> headIterator = headers.entrySet().iterator();
headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
builder.headers(headBuilder.build()).post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr));
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<String, String> headers, Map<String, String> params, File file) throws IOException {
Request.Builder builder = new Request.Builder();
Request request = builder.url(url).build();
Headers.Builder headBuilder = request.headers().newBuilder();
Iterator<Map.Entry<String, String>> headIterator = headers.entrySet().iterator();
headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
MultipartBody.Builder requestBuilder = new MultipartBody.Builder();
Iterator<Map.Entry<String, String>> paramsIterator = params.entrySet().iterator();
paramsIterator.forEachRemaining(e -> requestBuilder.addFormDataPart(e.getKey(), e.getValue()));
if (file != null) {
requestBuilder.addFormDataPart("uploadFiles", file.getName(),
RequestBody.create(MediaType.parse("application/octet-stream"), file));
}
builder.headers(headBuilder.build()).post(requestBuilder.build());
try (Response response = client.newCall(builder.build()).execute()){
return response.body().string();
}
}
public static String doPost(String url, Map<String, String> headers, Map<String, String> params,
String fileName, byte[] fileByte) throws IOException {
Request.Builder builder = new Request.Builder();
Request request = builder.url(url).build();
Headers.Builder headBuilder = request.headers().newBuilder();
Iterator<Map.Entry<String, String>> headIterator = headers.entrySet().iterator();
headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
MultipartBody.Builder requestBuilder = new MultipartBody.Builder();
Iterator<Map.Entry<String, String>> paramsIterator = params.entrySet().iterator();
paramsIterator.forEachRemaining(e -> requestBuilder.addFormDataPart(e.getKey(), e.getValue()));
if (fileByte.length > 0) {
requestBuilder.addFormDataPart("uploadFiles", fileName,
RequestBody.create(MediaType.parse("application/octet-stream"), fileByte));
}
builder.headers(headBuilder.build()).post(requestBuilder.build());
try (Response response = client.newCall(builder.build()).execute()){
return response.body().string();
}
}
public static String doPut(String url, Map<String, String> headers, String jsonStr) throws IOException {
Request.Builder builder = new Request.Builder();
Request request = builder.url(url).build();
Headers.Builder headBuilder = request.headers().newBuilder();
Iterator<Map.Entry<String, String>> headIterator = headers.entrySet().iterator();
headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
builder.headers(headBuilder.build()).put(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonStr));
try (Response response = client.newCall(builder.build()).execute()){
return response.body().string();
}
}
public static String doDelete(String url, Map<String, String> headers, String jsonStr) throws IOException {
Request.Builder builder = new Request.Builder();
Request request = builder.url(url).build();
Headers.Builder headBuilder = request.headers().newBuilder();
Iterator<Map.Entry<String, String>> headIterator = headers.entrySet().iterator();
headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
builder.headers(headBuilder.build()).delete(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonStr));
try (Response response = client.newCall(builder.build()).execute()){
return response.body().string();
}
}
public static Integer deDeleteReturnCode(String url, Map<String, String> headers, String jsonStr) throws IOException {
Request.Builder builder = new Request.Builder();
Request request = builder.url(url).build();
Headers.Builder headBuilder = request.headers().newBuilder();
Iterator<Map.Entry<String, String>> headIterator = headers.entrySet().iterator();
headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
builder.headers(headBuilder.build()).delete(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonStr));
try (Response response = client.newCall(builder.build()).execute()){
return response.code();
}
}
}
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 = "正常";
}
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<String> file_ls) {
StringBuilder builder = new StringBuilder("['");
for (String str : file_ls) {
builder.append(str).append("', '");
}
String bStr = builder.toString();
String res = bStr.substring(0, bStr.length()-3)+"]";
return buildMP3Filename(res);
}
public static boolean doesFileExist(String filePath) {
File file = new File(filePath);
return file.exists();
}
public static 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));
}
}
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<String> 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());
}
}
}
}
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);
}
}
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'
}
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;
}
}
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;
}
}
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;
}
}
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;
}
}
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;
}
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<String> mood = new ArrayList<>();
public PersonInfo(String name, String sex) {
this.name = name;
this.sex = sex;
}
}
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;
}
}
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<String> audio;
public ResponseStatusWithList(Integer status, List<String> audio) {
this.status = status;
this.audio = audio;
}
}
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;
}
}
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<TextInfo> text_info_ls;
private String botname;
private String person;
}
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;
}
}
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;
}
}
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;
}
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<SpeakersInfo, Integer> {
List<SpeakersInfo> findByIsDelete(String isDelete);
}
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<String> URL_LS;
private static final Map<String, PersonInfo> PERSON_INFO_ONLINE; //speakers_online
private static final Map<String, PersonInfo> PERSON_INFO_OFFLINE; //speakers_offline
private static final Map<String, Map<String, String>> PERSON_MOODURL; //api
private static final Map<String, Map<String, String>> OFFLINE_2_ONLINE;
private 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<String, String> mood_url = PERSON_MOODURL.computeIfAbsent(person, k -> new HashMap<>());
mood_url.put(mood, url);
}
PersonInfo personInfo_offline = PERSON_INFO_OFFLINE.computeIfAbsent(person_offline, k -> new PersonInfo(name, sex));
personInfo_offline.getMood().add(mood);
if (jump != null) {
Map<String, String> mood2jumpUrl = OFFLINE_2_ONLINE.computeIfAbsent(person_offline, k -> new HashMap<>());
mood2jumpUrl.put(mood, String.format("%s:9%03d/synthesize", Config.getProperty("online_sever"), jump));
}
Map<String, String> mood_url = PERSON_MOODURL.computeIfAbsent(person_offline, k -> new HashMap<>());
mood_url.putIfAbsent(mood, String.format("%s/synthesize", Config.getProperty("offline_server")));
}
@Override
public void afterPropertiesSet() throws Exception {
List<SpeakersInfo> 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<String> moodList = PERSON_INFO_ONLINE.get(init_person).getMood();
if (!moodList.contains(init_tone)) {
init_tone = moodList.get(0);
}
init_url = PERSON_MOODURL.get(init_person).get(init_tone);
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<String, Map<String, String>> getPersonMoodurl() {
return PERSON_MOODURL;
}
String getDefault_tone() {
return TTSConstants.DEFAULT_MOOD;
}
String getInit_tone() {
return init_tone;
}
Map<String, String> getThePersonJumpUrls(String person) {
return OFFLINE_2_ONLINE.get(person);
}
boolean doesThisMoodUrlWithOnline0(String url) {
return !URL_LS.contains(url);
}
String getInit_url() {
return init_url;
}
}
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
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
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);
}
}
...@@ -11,7 +11,7 @@ ...@@ -11,7 +11,7 @@
<groupId>ai.qiwu.baidu</groupId> <groupId>ai.qiwu.baidu</groupId>
<artifactId>xiaodu</artifactId> <artifactId>xiaodu</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<!--<packaging>war</packaging>--> <packaging>war</packaging>
<name>xiaodu</name> <name>xiaodu</name>
<description>Demo project for Spring Boot</description> <description>Demo project for Spring Boot</description>
...@@ -23,14 +23,21 @@ ...@@ -23,14 +23,21 @@
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
<!--<exclusions>--> <exclusions>
<!--<exclusion>--> <exclusion>
<!--<groupId>org.springframework.boot</groupId>--> <groupId>org.springframework.boot</groupId>
<!--<artifactId>spring-boot-starter-tomcat</artifactId>--> <artifactId>spring-boot-starter-tomcat</artifactId>
<!--</exclusion>--> </exclusion>
<!--</exclusions>--> </exclusions>
</dependency> </dependency>
<!--<dependency>-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-starter-jdbc</artifactId>-->
<!--<version>2.1.6.RELEASE</version>-->
<!--</dependency>-->
<!--添加servlet-api的依赖,用来打war包--> <!--添加servlet-api的依赖,用来打war包-->
<dependency> <dependency>
<groupId>javax.servlet</groupId> <groupId>javax.servlet</groupId>
...@@ -45,6 +52,12 @@ ...@@ -45,6 +52,12 @@
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<!--<dependency>-->
<!--<groupId>mysql</groupId>-->
<!--<artifactId>mysql-connector-java</artifactId>-->
<!--<version>8.0.16</version>-->
<!--<scope>runtime</scope>-->
<!--</dependency>-->
<dependency> <dependency>
<groupId>com.baidu.dueros</groupId> <groupId>com.baidu.dueros</groupId>
<artifactId>bot-sdk</artifactId> <artifactId>bot-sdk</artifactId>
...@@ -57,11 +70,6 @@ ...@@ -57,11 +70,6 @@
<version>1.2.0</version> <version>1.2.0</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.8</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId> <artifactId>fastjson</artifactId>
<version>1.2.58</version> <version>1.2.58</version>
...@@ -72,11 +80,6 @@ ...@@ -72,11 +80,6 @@
<version>1.18.8</version> <version>1.18.8</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf --> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
...@@ -99,21 +102,21 @@ ...@@ -99,21 +102,21 @@
<artifactId>commons-fileupload</artifactId> <artifactId>commons-fileupload</artifactId>
<version>1.4</version> <version>1.4</version>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/com.github.ipld/java-cid --> <!--&lt;!&ndash; https://mvnrepository.com/artifact/com.github.ipld/java-cid &ndash;&gt;-->
<dependency> <!--<dependency>-->
<groupId>com.github.ipld</groupId> <!--<groupId>com.github.ipld</groupId>-->
<artifactId>java-cid</artifactId> <!--<artifactId>java-cid</artifactId>-->
<version>v1.1.1</version> <!--<version>v1.1.1</version>-->
</dependency> <!--</dependency>-->
</dependencies> </dependencies>
<repositories> <!--<repositories>-->
<repository> <!--<repository>-->
<id>jitpack.io</id> <!--<id>jitpack.io</id>-->
<url>https://jitpack.io</url> <!--<url>https://jitpack.io</url>-->
</repository> <!--</repository>-->
</repositories> <!--</repositories>-->
<build> <build>
<finalName>xiaodu</finalName> <finalName>xiaodu</finalName>
......
...@@ -8,14 +8,14 @@ import org.springframework.scheduling.annotation.EnableScheduling; ...@@ -8,14 +8,14 @@ import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication @SpringBootApplication
@EnableScheduling @EnableScheduling
public class XiaoduApplication{ public class XiaoduApplication extends SpringBootServletInitializer {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(XiaoduApplication.class, args); SpringApplication.run(XiaoduApplication.class, args);
} }
// @Override @Override
// protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
// return builder.sources(XiaoduApplication.class); return builder.sources(XiaoduApplication.class);
// } }
} }
package ai.qiwu.baidu.xiaodu.common; package ai.qiwu.baidu.xiaodu.common;
import ai.qiwu.baidu.xiaodu.pojo.product.response.ProductIdRequest; import ai.qiwu.baidu.xiaodu.pojo.product.response.ProductIdRequest;
import io.ipfs.cid.Cid;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
...@@ -9,8 +8,6 @@ import org.springframework.web.context.request.ServletRequestAttributes; ...@@ -9,8 +8,6 @@ import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Objects; import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** /**
* @author 苗权威 * @author 苗权威
......
package ai.qiwu.baidu.xiaodu.pojo; package ai.qiwu.baidu.xiaodu.pojo;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/** /**
* @author 苗权威 * @author 苗权威
* @dateTime 19-6-29 下午4:32 * @dateTime 19-6-29 下午4:32
*/ */
@Getter
@Setter
@ToString
public class AudioUrlAndText { public class AudioUrlAndText {
private String audioUrl; private String audio;
private String text; 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;
}
} }
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;
}
package ai.qiwu.baidu.xiaodu.service; package ai.qiwu.baidu.xiaodu.service;
import ai.qiwu.baidu.xiaodu.common.Constants; 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.AudioUrlAndText;
import ai.qiwu.baidu.xiaodu.pojo.QiWuRequest;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
...@@ -21,52 +25,63 @@ import java.util.HashMap; ...@@ -21,52 +25,63 @@ import java.util.HashMap;
* @author 苗权威 * @author 苗权威
* @dateTime 19-6-29 下午3:49 * @dateTime 19-6-29 下午3:49
*/ */
@Slf4j
class RequestTerminal { class RequestTerminal {
private static final Logger logger = LoggerFactory.getLogger(RequestTerminal.class); static AudioUrlAndText requestTerminate(String userWord, String userId) throws IOException {
QiWuRequest requestPojo = new QiWuRequest();
static AudioUrlAndText requestTerminate(String word, String userId) { requestPojo.setUser_id(userId);
AudioUrlAndText store = new AudioUrlAndText(); requestPojo.setAccess(Constants.SERVICE_NAME);
String audioUrl = ""; requestPojo.setText(userWord);
String textContent = "请说推荐作品"; String requestJsonStr = JSON.toJSONString(requestPojo);
CloseableHttpClient httpClient = null; HashMap<String, String> headers = new HashMap<>();
CloseableHttpResponse httpResponse = null; headers.put("Content-Type", "application/json; charset=utf-8");
try { String resStr = OkHttp3Utils.doPostJsonStr(Constants.QI_WU_INTERFACE, headers, requestJsonStr);
httpClient = HttpClientBuilder.create().build(); return JSON.parseObject(resStr, AudioUrlAndText.class);
HttpPost post = new HttpPost(Constants.QI_WU_INTERFACE);
HashMap<String, String> 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 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<String, String> 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;
// }
} }
...@@ -5,12 +5,10 @@ import ai.qiwu.baidu.xiaodu.common.Constants.ErrorMsg; ...@@ -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.EndMsg;
import ai.qiwu.baidu.xiaodu.common.Constants.WelcomeWord; import ai.qiwu.baidu.xiaodu.common.Constants.WelcomeWord;
import ai.qiwu.baidu.xiaodu.common.OkHttp3Utils; 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.common.Utils;
import ai.qiwu.baidu.xiaodu.pojo.AudioUrlAndText; import ai.qiwu.baidu.xiaodu.pojo.AudioUrlAndText;
import ai.qiwu.baidu.xiaodu.pojo.GetTokenByRefreshToken; import ai.qiwu.baidu.xiaodu.pojo.GetTokenByRefreshToken;
import ai.qiwu.baidu.xiaodu.pojo.GetUserInfoByToken; import ai.qiwu.baidu.xiaodu.pojo.GetUserInfoByToken;
import ai.qiwu.baidu.xiaodu.service.productManager.ProductManager;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.baidu.dueros.bot.AudioPlayer; import com.baidu.dueros.bot.AudioPlayer;
import com.baidu.dueros.data.request.*; import com.baidu.dueros.data.request.*;
...@@ -29,10 +27,6 @@ import com.baidu.dueros.data.response.directive.audioplayer.AudioPlayerDirective ...@@ -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.Content;
import com.baidu.dueros.data.response.directive.audioplayer.Play; 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.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.Buy;
import com.baidu.dueros.data.response.directive.pay.Charge; import com.baidu.dueros.data.response.directive.pay.Charge;
import com.baidu.dueros.model.Request; import com.baidu.dueros.model.Request;
...@@ -48,10 +42,6 @@ import java.util.ArrayList; ...@@ -48,10 +42,6 @@ import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Random; 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; import static ai.qiwu.baidu.xiaodu.common.Constants.EndMsg.BYE_BYE;
...@@ -224,12 +214,24 @@ public class ResponseEncapsulation extends AudioPlayer { ...@@ -224,12 +214,24 @@ public class ResponseEncapsulation extends AudioPlayer {
} }
} }
}else { }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) { if (data == null) {
return buildErrorResponse(ErrorMsg.SORRY_UNCATCH); return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
} }
String audioUrl = data.getAudioUrl(); logger.info("请求终端接口:"+data);
addDirective(buildPlayDirective(audioUrl, data.getText(), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL)); 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"; // String uri = "https://aliyun-hz1.chewrobot.com/xiaodu/image/5b2d0a11/lvzhou/1564033095964d39f.jpg";
// ImageStructure imageStructure = new ImageStructure(uri, 512, 512); // ImageStructure imageStructure = new ImageStructure(uri, 512, 512);
...@@ -366,6 +368,10 @@ public class ResponseEncapsulation extends AudioPlayer { ...@@ -366,6 +368,10 @@ public class ResponseEncapsulation extends AudioPlayer {
return play; return play;
} }
private Play buildNoScreenPlayDirec(String audioUrl, AudioPlayerDirective.PlayBehaviorType type) {
return new Play(type, audioUrl, 0);
}
/** /**
* 不想对每个事件都进行处理,通过重写onDefaultEvent方法来统一处理。 * 不想对每个事件都进行处理,通过重写onDefaultEvent方法来统一处理。
* 任何事件都不允许开麦 * 任何事件都不允许开麦
......
#logging.path=/usr/mqw/logs/xiaodu logging.path=/usr/mqw/logs/xiaodu
#logging.level.root = info logging.level.root = info
#spring.output.ansi.enabled=detect spring.output.ansi.enabled=detect
spring.thymeleaf.mode=HTML spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html spring.thymeleaf.servlet.content-type=text/html
#开发时关闭缓存,不然没法看到实时页面 #开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false #spring.thymeleaf.cache=false
image.upload.path = /root/GameEditor/mqw/xiaodu/image/ 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
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment