Commit 0487b6d5 authored by 何处是我家's avatar 何处是我家
Browse files

提交

parents
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 日志存放路径 -->
<property name="log.path" value="./logs/biz"/>
<!-- 日志输出格式 -->
<property name="log.pattern"
value="[%X{trace}] %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n"/>
<!-- 控制台输出 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
</appender>
<!-- 系统日志输出 -->
<appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/sys-info.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/sys-info.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>INFO</level>
<!-- 匹配时的操作:接收(记录) -->
<onMatch>ACCEPT</onMatch>
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/sys-error.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/sys-error.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>ERROR</level>
<!-- 匹配时的操作:接收(记录) -->
<onMatch>ACCEPT</onMatch>
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 用户访问日志输出 -->
<appender name="sys-user" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/sys-user.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 按天回滚 daily -->
<fileNamePattern>${log.path}/sys-user.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
</appender>
<!-- 系统模块日志级别控制 -->
<logger name="com.ewaytek" level="info"/>
<!-- Spring日志级别控制 -->
<logger name="org.springframework" level="info"/>
<root level="info">
<appender-ref ref="console"/>
</root>
<!--系统操作日志-->
<root level="info">
<appender-ref ref="file_info"/>
<appender-ref ref="file_error"/>
</root>
<!--系统用户操作日志-->
<logger name="sys-user" level="info">
<appender-ref ref="sys-user"/>
</logger>
</configuration>
\ No newline at end of file
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>流式聊天Demo</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f5f5f5;
}
.chat-container {
max-width: 800px;
margin: 0 auto;
background-color: white;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
padding: 20px;
}
.chat-messages {
height: 500px;
overflow-y: auto;
border: 1px solid #ddd;
border-radius: 5px;
padding: 10px;
margin-bottom: 20px;
}
.message {
margin-bottom: 15px;
padding: 10px;
border-radius: 5px;
}
.user-message {
background-color: #e3f2fd;
text-align: right;
}
.bot-message {
background-color: #f5f5f5;
}
.input-container {
display: flex;
gap: 10px;
}
#userInput {
flex: 1;
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
font-size: 16px;
}
button {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
}
button:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<div class="chat-container">
<div class="chat-messages" id="chatMessages"></div>
<div class="input-container">
<input type="text" id="userInput" placeholder="请输入消息...">
<button onclick="sendMessage()">发送</button>
</div>
</div>
<script>
function sendMessage() {
const userInput = document.getElementById('userInput');
const message = userInput.value.trim();
if (!message) return;
addMessage(message, 'user');
userInput.value = '';
// 创建唯一ID的占位消息用于增量更新
const placeholderId = `bot-${Date.now()}`;
addMessage('', 'bot', placeholderId); // 初始为空内容
fetch('http://127.0.0.1:26061/dify/stream/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
query: message,
userId: 123,
conversationId: null
})
})
.then(response => {
const reader = response.body.getReader();
const decoder = new TextDecoder('utf-8');
let buffer = '';
let partialChunk = '';
const processData = (dataStr) => {
const lines = (partialChunk + dataStr).split('\n');
partialChunk = lines.pop() || ''; // 保存未完成的行
for (const line of lines) {
if (line.startsWith('data: ')) {
try {
const data = JSON.parse(line.slice(6)); // 提取JSON数据
const answerChunk = data.answer;
// 关键修改:追加内容而非覆盖
const el = document.getElementById(placeholderId);
if (el) {
el.textContent += answerChunk; // 使用 += 实现增量
el.scrollIntoView({ behavior: 'smooth' });
}
} catch (e) {
console.error('解析错误:', e);
}
}
}
};
const readStream = () => {
reader.read().then(({ done, value }) => {
if (done) {
// 流结束后的清理工作
if (partialChunk) processData('');
return;
}
buffer += decoder.decode(value, { stream: true });
processData(buffer);
buffer = '';
readStream();
});
};
readStream();
})
.catch(err => {
console.error('请求失败:', err);
addMessage('请求出错,请稍后重试', 'bot');
});
}
// 辅助函数:添加消息到聊天窗口
function addMessage(text, sender, messageId) {
const chatMessages = document.getElementById('chatMessages');
const messageDiv = document.createElement('div');
messageDiv.id = messageId || '';
messageDiv.className = `message ${sender}-message`;
messageDiv.textContent = text;
chatMessages.appendChild(messageDiv);
messageDiv.scrollIntoView({ behavior: 'smooth' });
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>语音交互系统</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
}
.section {
margin-bottom: 20px;
padding: 15px;
border: 1px solid #ddd;
border-radius: 8px;
background-color: white;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
h2 {
color: #333;
border-bottom: 1px solid #eee;
padding-bottom: 10px;
}
button {
padding: 10px 15px;
margin-right: 10px;
margin-bottom: 10px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
transition: background-color 0.3s;
}
button:hover {
background-color: #45a049;
}
button:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
#transcript, #response {
margin-top: 10px;
padding: 12px;
border: 1px solid #ccc;
min-height: 100px;
border-radius: 4px;
background-color: #f9f9f9;
font-size: 14px;
line-height: 1.5;
}
input[type="text"] {
width: 100%;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 14px;
}
.audio-controls {
margin-top: 10px;
display: flex;
gap: 10px;
}
.audio-player {
margin-top: 15px;
}
.loading {
display: none;
margin: 15px 0;
padding: 10px;
background-color: #f0f0f0;
border-radius: 4px;
text-align: center;
color: #666;
}
.save-controls {
margin-top: 15px;
display: flex;
gap: 10px;
}
.interaction-history {
margin-top: 20px;
padding: 10px;
background-color: #f0f0f0;
border-radius: 4px;
max-height: 200px;
overflow-y: auto;
}
.user-message {
background-color: #e3f2fd;
padding: 10px;
border-radius: 4px;
margin-bottom: 10px;
}
.system-message {
background-color: #e8f5e9;
padding: 10px;
border-radius: 4px;
margin-bottom: 10px;
}
</style>
</head>
<body>
<div class="section">
<h2>语音交互系统</h2>
<p>支持语音输入和文字输入,系统将自动回答您的问题。</p>
</div>
<div class="section">
<h2>语音输入</h2>
<div class="audio-controls">
<button id="startRecording">开始录音</button>
<button id="stopRecording" disabled>停止录音</button>
</div>
<div id="transcript" contenteditable="true">录音转写内容将显示在这里...</div>
</div>
<div class="section">
<h2>文字输入</h2>
<input type="text" id="textInput" placeholder="请输入文字">
<button id="textSubmit">提交文字</button>
<div id="response">系统回答将显示在这里...</div>
</div>
<div class="section">
<h2>音频播放</h2>
<div class="audio-player">
<h3>用户录音:</h3>
<audio id="userAudio" controls></audio>
<h3>系统回答:</h3>
<audio id="systemAudio" controls></audio>
</div>
<div class="loading" id="loading">正在处理请求,请稍候...</div>
<div class="save-controls">
<button id="saveWav">保存为WAV</button>
<button id="savePcm">保存为PCM</button>
</div>
</div>
<div class="section">
<h2>交互历史</h2>
<div id="interactionHistory" class="interaction-history"></div>
</div>
<script>
let audioContext;
let mediaStream;
let scriptProcessor;
let audioBuffer = [];
let isRecording = false;
const TARGET_SAMPLE_RATE = 16000;
let lastRecordedPcmData = null;
let lastRecordedWavBlob = null;
// 初始化音频上下文
function initAudioContext() {
audioContext = new (window.AudioContext || window.webkitAudioContext)({
sampleRate: TARGET_SAMPLE_RATE
});
}
// 开始录音
document.getElementById('startRecording').addEventListener('click', async () => {
try {
const stream = await navigator.mediaDevices.getUserMedia({
audio: {
sampleRate: TARGET_SAMPLE_RATE,
channelCount: 1,
echoCancellation: true,
noiseSuppression: true
}
});
mediaStream = stream;
initAudioContext();
const source = audioContext.createMediaStreamSource(stream);
scriptProcessor = audioContext.createScriptProcessor(16384, 1, 1);
scriptProcessor.onaudioprocess = handleAudioProcess;
source.connect(scriptProcessor);
scriptProcessor.connect(audioContext.destination);
isRecording = true;
document.getElementById('startRecording').disabled = true;
document.getElementById('stopRecording').disabled = false;
} catch (err) {
console.error('录音错误:', err);
alert('无法启动录音,请检查麦克风权限。');
}
});
// 处理音频数据
function handleAudioProcess(event) {
if (!isRecording) return;
const inputBuffer = event.inputBuffer;
const data = inputBuffer.getChannelData(0);
audioBuffer.push(new Float32Array(data));
}
// 停止录音
document.getElementById('stopRecording').addEventListener('click', () => {
if (mediaStream && isRecording) {
mediaStream.getTracks().forEach(track => track.stop());
scriptProcessor.disconnect();
isRecording = false;
document.getElementById('startRecording').disabled = false;
document.getElementById('stopRecording').disabled = true;
// 将音频数据转换为PCM
convertAudioBufferToPCM();
}
});
// 将音频数据转换为PCM
function convertAudioBufferToPCM() {
// 计算总采样点数
let totalSamples = 0;
for (let i = 0; i < audioBuffer.length; i++) {
totalSamples += audioBuffer[i].length;
}
// 创建正确大小的数组
const audioData = new Float32Array(totalSamples);
let offset = 0;
// 复制音频数据
for (let i = 0; i < audioBuffer.length; i++) {
audioData.set(audioBuffer[i], offset);
offset += audioBuffer[i].length;
}
// 将Float32Array转换为Int16Array(PCM格式)
const pcmData = new Int16Array(audioData.length);
for (let i = 0; i < audioData.length; i++) {
pcmData[i] = Math.max(-1, Math.min(1, audioData[i])) * 0x7FFF;
}
// 创建WAV文件头
const wavHeader = new Uint8Array([
82, 73, 70, 70, // "RIFF" 标识
0, 0, 0, 0, // 文件大小(待填充)
87, 65, 86, 69, // "WAVE" 标识
102, 109, 116, 32, // "fmt " 标识
16, 0, 0, 0, // fmt块大小
1, 0, // 音频格式,1表示PCM
1, 0, // 声道数,1表示单声道
TARGET_SAMPLE_RATE & 0xFF, (TARGET_SAMPLE_RATE >> 8) & 0xFF, (TARGET_SAMPLE_RATE >> 16) & 0xFF, (TARGET_SAMPLE_RATE >> 24) & 0xFF, // 采样率
(TARGET_SAMPLE_RATE * 2) & 0xFF, ((TARGET_SAMPLE_RATE * 2) >> 8) & 0xFF, ((TARGET_SAMPLE_RATE * 2) >> 16) & 0xFF, ((TARGET_SAMPLE_RATE * 2) >> 24) & 0xFF, // 字节率
2, 0, // 块对齐
16, 0, // 位深度
100, 97, 116, 97, // "data" 标识
0, 0, 0, 0 // 数据大小(待填充)
]);
// 填充文件大小和数据大小
const dataSize = pcmData.length * 2; // 16位 = 2字节
const fileSize = dataSize + 36; // 文件总大小 = 数据大小 + 头部大小(44字节)
// 填充文件大小(4-7字节)
wavHeader[4] = fileSize & 0xFF;
wavHeader[5] = (fileSize >> 8) & 0xFF;
wavHeader[6] = (fileSize >> 16) & 0xFF;
wavHeader[7] = (fileSize >> 24) & 0xFF;
// 填充数据大小(40-43字节)
wavHeader[40] = dataSize & 0xFF;
wavHeader[41] = (dataSize >> 8) & 0xFF;
wavHeader[42] = (dataSize >> 16) & 0xFF;
wavHeader[43] = (dataSize >> 24) & 0xFF;
// 创建WAV Blob
lastRecordedWavBlob = new Blob([wavHeader, pcmData.buffer], { type: 'audio/wav' });
lastRecordedPcmData = pcmData;
// 创建音频URL并播放
const audioUrl = URL.createObjectURL(lastRecordedWavBlob);
document.getElementById('userAudio').src = audioUrl;
document.getElementById('userAudio').load();
// 上传PCM数据
const formData = new FormData();
const pcmBlob = new Blob([pcmData.buffer], { type: 'audio/pcm' });
formData.append('audio', pcmBlob, 'recording.pcm');
// 显示加载提示
document.getElementById('loading').style.display = 'block';
// 发送到后端进行处理
fetchAudioResponse(formData);
}
// 保存WAV文件
document.getElementById('saveWav').addEventListener('click', () => {
if (lastRecordedWavBlob) {
const url = URL.createObjectURL(lastRecordedWavBlob);
const a = document.createElement('a');
a.href = url;
a.download = `recording_${new Date().toISOString().replace(/[:.]/g, '-')}.wav`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
} else {
alert('没有可保存的录音!');
}
});
// 保存PCM文件
document.getElementById('savePcm').addEventListener('click', () => {
if (lastRecordedPcmData) {
const pcmBlob = new Blob([lastRecordedPcmData.buffer], { type: 'audio/pcm' });
const url = URL.createObjectURL(pcmBlob);
const a = document.createElement('a');
a.href = url;
a.download = `recording_${new Date().toISOString().replace(/[:.]/g, '-')}.pcm`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
} else {
alert('没有可保存的录音!');
}
});
// 文字输入功能
document.getElementById('textSubmit').addEventListener('click', () => {
const text = document.getElementById('textInput').value.trim();
if (!text) {
alert('请输入文字内容!');
return;
}
// 创建表单数据
const formData = new FormData();
formData.append('context', text);
// 显示加载提示
document.getElementById('loading').style.display = 'block';
// 发送到后端进行处理
fetchAudioResponse(formData);
});
// 获取音频响应
function fetchAudioResponse(formData) {
const systemAudio = document.getElementById('systemAudio');
const loading = document.getElementById('loading');
// 创建MediaSource
const mediaSource = new MediaSource();
systemAudio.src = URL.createObjectURL(mediaSource);
// 准备接收数据
mediaSource.addEventListener('sourceopen', () => {
// 检查浏览器是否支持所需的MIME类型
if (!MediaSource.isTypeSupported('audio/mpeg')) {
console.error('浏览器不支持audio/mpeg格式');
loading.style.display = 'none';
return;
}
const sourceBuffer = mediaSource.addSourceBuffer('audio/mpeg');
const queue = [];
let isAppending = false;
function appendNextChunk() {
if (queue.length > 0 && !isAppending && !sourceBuffer.updating) {
isAppending = true;
const chunk = queue.shift();
sourceBuffer.appendBuffer(chunk);
}
}
sourceBuffer.addEventListener('updateend', () => {
isAppending = false;
appendNextChunk();
});
sourceBuffer.addEventListener('error', (e) => {
console.error('SourceBuffer error:', e);
loading.style.display = 'none';
});
// 发送请求到后端
fetch('http://localhost:26061/dify/audio/voice', {
method: 'POST',
body: formData
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.body;
})
.then(stream => {
const reader = stream.getReader();
return readStream(reader, queue, appendNextChunk, sourceBuffer, loading);
})
.catch(error => {
console.error('Error fetching audio response:', error);
loading.style.display = 'none';
});
});
}
function readStream(reader, queue, appendNextChunk, sourceBuffer, loading) {
function processResult() {
reader.read().then(({ done, value }) => {
if (done) {
sourceBuffer.abort();
loading.style.display = 'none';
return;
}
if (value && value.byteLength > 0) {
queue.push(value);
appendNextChunk();
}
processResult();
}).catch(error => {
console.error('Error reading stream:', error);
loading.style.display = 'none';
});
}
processResult();
}
// 添加消息到历史记录
function addToHistory(type, content) {
const historyDiv = document.getElementById('interactionHistory');
const messageDiv = document.createElement('div');
if (type === 'user') {
messageDiv.className = 'user-message';
messageDiv.textContent = `用户: ${content}`;
} else if (type === 'system') {
messageDiv.className = 'system-message';
messageDiv.textContent = `系统: ${content}`;
}
historyDiv.appendChild(messageDiv);
historyDiv.scrollTop = historyDiv.scrollHeight;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>语音交互系统</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
}
.section {
margin-bottom: 20px;
padding: 15px;
border: 1px solid #ddd;
border-radius: 8px;
background-color: white;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
h2 {
color: #333;
border-bottom: 1px solid #eee;
padding-bottom: 10px;
}
button {
padding: 10px 15px;
margin-right: 10px;
margin-bottom: 10px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
transition: background-color 0.3s;
}
button:hover {
background-color: #45a049;
}
button:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
#transcript, #response {
margin-top: 10px;
padding: 12px;
border: 1px solid #ccc;
min-height: 100px;
border-radius: 4px;
background-color: #f9f9f9;
font-size: 14px;
line-height: 1.5;
}
input[type="text"] {
width: 100%;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 14px;
}
.audio-controls {
margin-top: 10px;
display: flex;
gap: 10px;
}
.audio-player {
margin-top: 15px;
}
.loading {
display: none;
margin: 15px 0;
padding: 10px;
background-color: #f0f0f0;
border-radius: 4px;
text-align: center;
color: #666;
}
.save-controls {
margin-top: 15px;
display: flex;
gap: 10px;
}
.interaction-history {
margin-top: 20px;
padding: 10px;
background-color: #f0f0f0;
border-radius: 4px;
max-height: 200px;
overflow-y: auto;
}
.user-message {
background-color: #e3f2fd;
padding: 10px;
border-radius: 4px;
margin-bottom: 10px;
}
.system-message {
background-color: #e8f5e9;
padding: 10px;
border-radius: 4px;
margin-bottom: 10px;
}
</style>
</head>
<body>
<div class="section">
<h2>语音交互系统</h2>
<p>支持语音输入和文字输入,系统将自动回答您的问题。</p>
</div>
<div class="section">
<h2>语音输入</h2>
<div class="audio-controls">
<button id="startRecording">开始录音</button>
<button id="stopRecording" disabled>停止录音</button>
</div>
<div id="transcript" contenteditable="true">录音转写内容将显示在这里...</div>
</div>
<div class="section">
<h2>文字输入</h2>
<input type="text" id="textInput" placeholder="请输入文字">
<button id="textSubmit">提交文字</button>
<div id="response">系统回答将显示在这里...</div>
</div>
<div class="section">
<h2>音频播放</h2>
<div class="audio-player">
<h3>用户录音:</h3>
<audio id="userAudio" controls></audio>
<h3>系统回答:</h3>
<audio id="systemAudio" controls></audio>
</div>
<div class="loading" id="loading">正在处理请求,请稍候...</div>
<div class="save-controls">
<button id="saveWav">保存为WAV</button>
<button id="savePcm">保存为PCM</button>
</div>
</div>
<div class="section">
<h2>交互历史</h2>
<div id="interactionHistory" class="interaction-history"></div>
</div>
<script>
let audioContext;
let mediaStream;
let scriptProcessor;
let audioBuffer = [];
let isRecording = false;
const TARGET_SAMPLE_RATE = 16000;
let lastRecordedPcmData = null;
let lastRecordedWavBlob = null;
// 初始化音频上下文
function initAudioContext() {
audioContext = new (window.AudioContext || window.webkitAudioContext)({
sampleRate: TARGET_SAMPLE_RATE
});
}
// 开始录音
document.getElementById('startRecording').addEventListener('click', async () => {
try {
const stream = await navigator.mediaDevices.getUserMedia({
audio: {
sampleRate: TARGET_SAMPLE_RATE,
channelCount: 1,
echoCancellation: true,
noiseSuppression: true
}
});
mediaStream = stream;
initAudioContext();
const source = audioContext.createMediaStreamSource(stream);
scriptProcessor = audioContext.createScriptProcessor(16384, 1, 1);
scriptProcessor.onaudioprocess = handleAudioProcess;
source.connect(scriptProcessor);
scriptProcessor.connect(audioContext.destination);
isRecording = true;
document.getElementById('startRecording').disabled = true;
document.getElementById('stopRecording').disabled = false;
} catch (err) {
console.error('录音错误:', err);
alert('无法启动录音,请检查麦克风权限。');
}
});
// 处理音频数据
function handleAudioProcess(event) {
if (!isRecording) return;
const inputBuffer = event.inputBuffer;
const data = inputBuffer.getChannelData(0);
audioBuffer.push(new Float32Array(data));
}
// 停止录音
document.getElementById('stopRecording').addEventListener('click', () => {
if (mediaStream && isRecording) {
mediaStream.getTracks().forEach(track => track.stop());
scriptProcessor.disconnect();
isRecording = false;
document.getElementById('startRecording').disabled = false;
document.getElementById('stopRecording').disabled = true;
// 将音频数据转换为PCM
convertAudioBufferToPCM();
}
});
// 将音频数据转换为PCM
function convertAudioBufferToPCM() {
// 计算总采样点数
let totalSamples = 0;
for (let i = 0; i < audioBuffer.length; i++) {
totalSamples += audioBuffer[i].length;
}
// 创建正确大小的数组
const audioData = new Float32Array(totalSamples);
let offset = 0;
// 复制音频数据
for (let i = 0; i < audioBuffer.length; i++) {
audioData.set(audioBuffer[i], offset);
offset += audioBuffer[i].length;
}
// 将Float32Array转换为Int16Array(PCM格式)
const pcmData = new Int16Array(audioData.length);
for (let i = 0; i < audioData.length; i++) {
pcmData[i] = Math.max(-1, Math.min(1, audioData[i])) * 0x7FFF;
}
// 创建WAV文件头
const wavHeader = new Uint8Array([
82, 73, 70, 70, // "RIFF" 标识
0, 0, 0, 0, // 文件大小(待填充)
87, 65, 86, 69, // "WAVE" 标识
102, 109, 116, 32, // "fmt " 标识
16, 0, 0, 0, // fmt块大小
1, 0, // 音频格式,1表示PCM
1, 0, // 声道数,1表示单声道
TARGET_SAMPLE_RATE & 0xFF, (TARGET_SAMPLE_RATE >> 8) & 0xFF, (TARGET_SAMPLE_RATE >> 16) & 0xFF, (TARGET_SAMPLE_RATE >> 24) & 0xFF, // 采样率
(TARGET_SAMPLE_RATE * 2) & 0xFF, ((TARGET_SAMPLE_RATE * 2) >> 8) & 0xFF, ((TARGET_SAMPLE_RATE * 2) >> 16) & 0xFF, ((TARGET_SAMPLE_RATE * 2) >> 24) & 0xFF, // 字节率
2, 0, // 块对齐
16, 0, // 位深度
100, 97, 116, 97, // "data" 标识
0, 0, 0, 0 // 数据大小(待填充)
]);
// 填充文件大小和数据大小
const dataSize = pcmData.length * 2; // 16位 = 2字节
const fileSize = dataSize + 36; // 文件总大小 = 数据大小 + 头部大小(44字节)
// 填充文件大小(4-7字节)
wavHeader[4] = fileSize & 0xFF;
wavHeader[5] = (fileSize >> 8) & 0xFF;
wavHeader[6] = (fileSize >> 16) & 0xFF;
wavHeader[7] = (fileSize >> 24) & 0xFF;
// 填充数据大小(40-43字节)
wavHeader[40] = dataSize & 0xFF;
wavHeader[41] = (dataSize >> 8) & 0xFF;
wavHeader[42] = (dataSize >> 16) & 0xFF;
wavHeader[43] = (dataSize >> 24) & 0xFF;
// 创建WAV Blob
lastRecordedWavBlob = new Blob([wavHeader, pcmData.buffer], { type: 'audio/wav' });
lastRecordedPcmData = pcmData;
// 创建音频URL并播放
const audioUrl = URL.createObjectURL(lastRecordedWavBlob);
document.getElementById('userAudio').src = audioUrl;
document.getElementById('userAudio').load();
// 上传PCM数据
const formData = new FormData();
const pcmBlob = new Blob([pcmData.buffer], { type: 'audio/pcm' });
formData.append('audio', pcmBlob, 'recording.pcm');
// 显示加载提示
document.getElementById('loading').style.display = 'block';
// 发送到后端进行处理
fetchAudioResponse(formData);
}
// 保存WAV文件
document.getElementById('saveWav').addEventListener('click', () => {
if (lastRecordedWavBlob) {
const url = URL.createObjectURL(lastRecordedWavBlob);
const a = document.createElement('a');
a.href = url;
a.download = `recording_${new Date().toISOString().replace(/[:.]/g, '-')}.wav`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
} else {
alert('没有可保存的录音!');
}
});
// 保存PCM文件
document.getElementById('savePcm').addEventListener('click', () => {
if (lastRecordedPcmData) {
const pcmBlob = new Blob([lastRecordedPcmData.buffer], { type: 'audio/pcm' });
const url = URL.createObjectURL(pcmBlob);
const a = document.createElement('a');
a.href = url;
a.download = `recording_${new Date().toISOString().replace(/[:.]/g, '-')}.pcm`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
} else {
alert('没有可保存的录音!');
}
});
// 文字输入功能
document.getElementById('textSubmit').addEventListener('click', () => {
const text = document.getElementById('textInput').value.trim();
if (!text) {
alert('请输入文字内容!');
return;
}
// 创建表单数据
const formData = new FormData();
formData.append('context', text);
// 显示加载提示
document.getElementById('loading').style.display = 'block';
// 发送到后端进行处理
fetchAudioResponse(formData);
});
// 获取音频响应
function fetchAudioResponse(formData) {
const systemAudio = document.getElementById('systemAudio');
const loading = document.getElementById('loading');
// 发送请求到后端
fetch('http://localhost:26061/dify/audio/voice', {
method: 'POST',
body: formData
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.body;
})
.then(body => {
const reader = body.getReader();
const decoder = new TextDecoder('utf-8');
let buffer = '';
let partialChunk = '';
const processData = (dataStr) => {
const lines = (partialChunk + dataStr).split('\n');
partialChunk = lines.pop() || ''; // 保存未完成的行
for (const line of lines) {
if (line.startsWith('data: ')) {
try {
const data = JSON.parse(line.slice(6)); // 提取JSON数据
const audioName = data.name;
const context = data.context;
// 更新交互历史
addToHistory('system', context);
// 获取音频流并播放
fetchAudioStream(audioName);
} catch (e) {
console.error('解析错误:', e);
}
}
}
};
const readStream = () => {
reader.read().then(({ done, value }) => {
if (done) {
// 流结束后的清理工作
if (partialChunk) processData('');
loading.style.display = 'none';
return;
}
buffer += decoder.decode(value, { stream: true });
processData(buffer);
buffer = '';
readStream();
});
};
readStream();
})
.catch(error => {
console.error('Error fetching audio response:', error);
loading.style.display = 'none';
});
}
// 获取音频流并播放
function fetchAudioStream(audioName) {
const systemAudio = document.getElementById('systemAudio');
const loading = document.getElementById('loading');
// 创建MediaSource
const mediaSource = new MediaSource();
systemAudio.src = URL.createObjectURL(mediaSource);
// 准备接收数据
mediaSource.addEventListener('sourceopen', () => {
// 检查浏览器是否支持所需的MIME类型
if (!MediaSource.isTypeSupported('audio/mpeg')) {
console.error('浏览器不支持audio/mpeg格式');
loading.style.display = 'none';
return;
}
const sourceBuffer = mediaSource.addSourceBuffer('audio/mpeg');
const queue = [];
let isAppending = false;
function appendNextChunk() {
if (queue.length > 0 && !isAppending && !sourceBuffer.updating) {
isAppending = true;
const chunk = queue.shift();
sourceBuffer.appendBuffer(chunk);
}
}
sourceBuffer.addEventListener('updateend', () => {
isAppending = false;
appendNextChunk();
});
sourceBuffer.addEventListener('error', (e) => {
console.error('SourceBuffer error:', e);
loading.style.display = 'none';
});
// 发送请求到后端获取音频流
fetch(`http://localhost:26061/${audioName}`)
.then(response => {
if (!response.ok) {
throw new Error('Failed to fetch audio file');
}
return response.body;
})
.then(stream => {
const reader = stream.getReader();
return readAudioStream(reader, queue, appendNextChunk, sourceBuffer, loading);
})
.catch(error => {
console.error('Error fetching audio stream:', error);
loading.style.display = 'none';
});
});
}
function readAudioStream(reader, queue, appendNextChunk, sourceBuffer, loading) {
function processResult() {
reader.read().then(({ done, value }) => {
if (done) {
sourceBuffer.abort();
loading.style.display = 'none';
return;
}
if (value && value.byteLength > 0) {
queue.push(value);
appendNextChunk();
}
processResult();
}).catch(error => {
console.error('Error reading stream:', error);
loading.style.display = 'none';
});
}
processResult();
}
// 添加消息到历史记录
function addToHistory(type, content) {
const historyDiv = document.getElementById('interactionHistory');
const messageDiv = document.createElement('div');
if (type === 'user') {
messageDiv.className = 'user-message';
messageDiv.textContent = `用户: ${content}`;
} else if (type === 'system') {
messageDiv.className = 'system-message';
messageDiv.textContent = `系统: ${content}`;
}
historyDiv.appendChild(messageDiv);
historyDiv.scrollTop = historyDiv.scrollHeight;
}
</script>
</body>
</html>
app:
description: 测试一下问答
icon: 🤖
icon_background: '#FFEAD5'
mode: chat
name: 测试问答
use_icon_as_answer_icon: false
kind: app
model_config:
agent_mode:
enabled: false
max_iteration: 5
strategy: react
tools: []
annotation_reply:
enabled: false
chat_prompt_config: {}
completion_prompt_config: {}
dataset_configs:
datasets:
datasets:
- dataset:
enabled: true
id: 0f61ee54-11bc-466f-bace-87e121d1a14e
reranking_enable: false
reranking_mode: weighted_score
reranking_model:
reranking_model_name: ''
reranking_provider_name: ''
retrieval_model: multiple
top_k: 4
weights:
keyword_setting:
keyword_weight: 0.3
vector_setting:
embedding_model_name: quentinz/bge-large-zh-v1.5:latest
embedding_provider_name: openai_api_compatible
vector_weight: 0.7
dataset_query_variable: ''
external_data_tools: []
file_upload:
allowed_file_extensions:
- .JPG
- .JPEG
- .PNG
- .GIF
- .WEBP
- .SVG
- .MP4
- .MOV
- .MPEG
- .MPGA
allowed_file_types: []
allowed_file_upload_methods:
- remote_url
- local_file
enabled: false
image:
detail: high
enabled: false
number_limits: 3
transfer_methods:
- remote_url
- local_file
number_limits: 3
model:
completion_params:
stop: []
mode: chat
name: deepseek-r1:14b
provider: openai_api_compatible
more_like_this:
enabled: false
opening_statement: 你好啊,我是deepseek助手,快来提问吧
pre_prompt: ''
prompt_type: simple
retriever_resource:
enabled: true
sensitive_word_avoidance:
enabled: false
speech_to_text:
enabled: false
suggested_questions: []
suggested_questions_after_answer:
enabled: false
text_to_speech:
enabled: false
language: ''
voice: ''
user_input_form: []
version: 0.1.5
#!/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
#
# http://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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.3.2
#
# Optional ENV vars
# -----------------
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
# MVNW_REPOURL - repo url base for downloading maven distribution
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
# ----------------------------------------------------------------------------
set -euf
[ "${MVNW_VERBOSE-}" != debug ] || set -x
# OS specific support.
native_path() { printf %s\\n "$1"; }
case "$(uname)" in
CYGWIN* | MINGW*)
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
native_path() { cygpath --path --windows "$1"; }
;;
esac
# set JAVACMD and JAVACCMD
set_java_home() {
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
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"
JAVACCMD="$JAVA_HOME/jre/sh/javac"
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACCMD="$JAVA_HOME/bin/javac"
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
return 1
fi
fi
else
JAVACMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v java
)" || :
JAVACCMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v javac
)" || :
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
return 1
fi
fi
}
# hash string like Java String::hashCode
hash_string() {
str="${1:-}" h=0
while [ -n "$str" ]; do
char="${str%"${str#?}"}"
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
str="${str#?}"
done
printf %x\\n $h
}
verbose() { :; }
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
die() {
printf %s\\n "$1" >&2
exit 1
}
trim() {
# MWRAPPER-139:
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
# Needed for removing poorly interpreted newline sequences when running in more
# exotic environments such as mingw bash on Windows.
printf "%s" "${1}" | tr -d '[:space:]'
}
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
while IFS="=" read -r key value; do
case "${key-}" in
distributionUrl) distributionUrl=$(trim "${value-}") ;;
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
esac
done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties"
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties"
case "${distributionUrl##*/}" in
maven-mvnd-*bin.*)
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
*)
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
distributionPlatform=linux-amd64
;;
esac
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
;;
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
esac
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
distributionUrlName="${distributionUrl##*/}"
distributionUrlNameMain="${distributionUrlName%.*}"
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
exec_maven() {
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
}
if [ -d "$MAVEN_HOME" ]; then
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
exec_maven "$@"
fi
case "${distributionUrl-}" in
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
esac
# prepare tmp dir
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
trap clean HUP INT TERM EXIT
else
die "cannot create temp dir"
fi
mkdir -p -- "${MAVEN_HOME%/*}"
# Download and Install Apache Maven
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
verbose "Downloading from: $distributionUrl"
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
# select .zip or .tar.gz
if ! command -v unzip >/dev/null; then
distributionUrl="${distributionUrl%.zip}.tar.gz"
distributionUrlName="${distributionUrl##*/}"
fi
# verbose opt
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
# normalize http auth
case "${MVNW_PASSWORD:+has-password}" in
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
esac
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
verbose "Found wget ... using wget"
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
verbose "Found curl ... using curl"
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
elif set_java_home; then
verbose "Falling back to use Java to download"
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
cat >"$javaSource" <<-END
public class Downloader extends java.net.Authenticator
{
protected java.net.PasswordAuthentication getPasswordAuthentication()
{
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
}
public static void main( String[] args ) throws Exception
{
setDefault( new Downloader() );
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
}
}
END
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
verbose " - Compiling Downloader.java ..."
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
verbose " - Running Downloader.java ..."
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
fi
# If specified, validate the SHA-256 sum of the Maven distribution zip file
if [ -n "${distributionSha256Sum-}" ]; then
distributionSha256Result=false
if [ "$MVN_CMD" = mvnd.sh ]; then
echo "Checksum validation is not supported for maven-mvnd." >&2
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
elif command -v sha256sum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
elif command -v shasum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
else
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
fi
if [ $distributionSha256Result = false ]; then
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
exit 1
fi
fi
# unzip and move
if command -v unzip >/dev/null; then
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
else
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
fi
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url"
mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
clean || :
exec_maven "$@"
<# : batch portion
@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 http://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 Apache Maven Wrapper startup batch script, version 3.3.2
@REM
@REM Optional ENV vars
@REM MVNW_REPOURL - repo url base for downloading maven distribution
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
@REM ----------------------------------------------------------------------------
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
@SET __MVNW_CMD__=
@SET __MVNW_ERROR__=
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
@SET PSModulePath=
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
)
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
@SET __MVNW_PSMODULEP_SAVE=
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
$ErrorActionPreference = "Stop"
if ($env:MVNW_VERBOSE -eq "true") {
$VerbosePreference = "Continue"
}
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
if (!$distributionUrl) {
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
}
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
"maven-mvnd-*" {
$USE_MVND = $true
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
$MVN_CMD = "mvnd.cmd"
break
}
default {
$USE_MVND = $false
$MVN_CMD = $script -replace '^mvnw','mvn'
break
}
}
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
if ($env:MVNW_REPOURL) {
$MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain"
if ($env:MAVEN_USER_HOME) {
$MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain"
}
$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
exit $?
}
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
}
# prepare tmp dir
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
trap {
if ($TMP_DOWNLOAD_DIR.Exists) {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
}
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
# Download and Install Apache Maven
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
Write-Verbose "Downloading from: $distributionUrl"
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
$webclient = New-Object System.Net.WebClient
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
# If specified, validate the SHA-256 sum of the Maven distribution zip file
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
if ($distributionSha256Sum) {
if ($USE_MVND) {
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
}
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
}
}
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
Write-Error "fail to move MAVEN_HOME"
}
} finally {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ewaytek.deepseek</groupId>
<artifactId>ewaytek-deepseek</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name>ewaytek-deepseek</name>
<description>ewaytek-deepseek</description>
<modules>
<module>ewaytek-deepseek-common</module>
<module>ewaytek-deepseek-web</module>
</modules>
<properties>
<java.version>1.8</java.version>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<ewaytek.version>0.0.1-SNAPSHOT</ewaytek.version>
<spring-boot.version>2.5.15</spring-boot.version>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
<spring-ai.version>1.0.0-M5</spring-ai.version>
<druid.version>1.2.23</druid.version>
<bitwalker.version>1.21</bitwalker.version>
<swagger.version>3.0.0</swagger.version>
<kaptcha.version>2.3.3</kaptcha.version>
<pagehelper.boot.version>1.4.7</pagehelper.boot.version>
<fastjson.version>2.0.53</fastjson.version>
<oshi.version>6.6.5</oshi.version>
<commons.io.version>2.13.0</commons.io.version>
<poi.version>4.1.2</poi.version>
<velocity.version>2.3</velocity.version>
<jwt.version>0.9.1</jwt.version>
<!-- override dependency version -->
<tomcat.version>9.0.96</tomcat.version>
<logback.version>1.2.13</logback.version>
<spring-security.version>5.7.12</spring-security.version>
<spring-framework.version>5.3.39</spring-framework.version>
</properties>
<!-- 依赖声明 -->
<dependencyManagement>
<dependencies>
<!-- 覆盖SpringFramework的依赖配置-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>${spring-framework.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- 覆盖SpringSecurity的依赖配置-->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-bom</artifactId>
<version>${spring-security.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- SpringBoot的依赖配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- 覆盖logback的依赖配置-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<!-- 覆盖tomcat的依赖配置-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-el</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-websocket</artifactId>
<version>${tomcat.version}</version>
</dependency>
<!-- 阿里数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<!-- 解析客户端操作系统、浏览器等 -->
<dependency>
<groupId>eu.bitwalker</groupId>
<artifactId>UserAgentUtils</artifactId>
<version>${bitwalker.version}</version>
</dependency>
<!-- 获取系统信息 -->
<dependency>
<groupId>com.github.oshi</groupId>
<artifactId>oshi-core</artifactId>
<version>${oshi.version}</version>
</dependency>
<!-- Swagger3依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>${swagger.version}</version>
<exclusions>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- io常用工具类 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons.io.version}</version>
</dependency>
<!-- excel工具 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<!-- velocity代码生成使用模板 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>${velocity.version}</version>
</dependency>
<!-- 阿里JSON解析器 -->
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>${fastjson.version}</version>
</dependency>
<!-- Token生成与解析-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>${jwt.version}</version>
</dependency>
<!-- 验证码 -->
<dependency>
<groupId>pro.fessional</groupId>
<artifactId>kaptcha</artifactId>
<version>${kaptcha.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba.nls</groupId>
<artifactId>nls-sdk-tts</artifactId>
<version>2.2.14</version>
</dependency>
<dependency>
<groupId>com.alibaba.nls</groupId>
<artifactId>nls-sdk-common</artifactId>
<version>2.2.14</version>
</dependency>
<dependency>
<groupId>com.alibaba.nls</groupId>
<artifactId>nls-sdk-recognizer</artifactId>
<version>2.2.1</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>public</id>
<name>aliyun nexus</name>
<url>https://maven.aliyun.com/repository/public</url>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>public</id>
<name>aliyun nexus</name>
<url>https://maven.aliyun.com/repository/public</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
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