新功能: - 创建AI聊天助手组件(AIChatWidget) - 支持文字+图片多模态对话 - 集成Gemini AI API - 支持图片编辑和内容生成 - 实时对话历史管理 - 优雅的UI设计,支持黑夜模式 技术实现: - 后端API代理Gemini API(/api/ai-chat) - 支持最多5张图片上传 - 流式响应处理 - 对话历史管理 - Base64图片处理 配置: - 在.env中添加Gemini API配置 - GEMINI_API_KEY - GEMINI_API_BASE_URL - GEMINI_MODEL 替换原弹幕功能,提供更强大的AI助手体验!
224 lines
7.9 KiB
JavaScript
224 lines
7.9 KiB
JavaScript
#!/usr/bin/env node
|
||
|
||
/**
|
||
* 测试图像拓展功能(使用 GENERATE_BG_API_KEY)
|
||
*/
|
||
|
||
const fs = require('fs');
|
||
const path = require('path');
|
||
const sharp = require('sharp');
|
||
require('dotenv').config();
|
||
|
||
async function testImageExtend() {
|
||
console.log('🚀 测试图像拓展功能');
|
||
console.log('='.repeat(60));
|
||
|
||
// 检查 API KEY
|
||
if (!process.env.GENERATE_BG_API_KEY) {
|
||
console.error('❌ 未找到 GENERATE_BG_API_KEY 配置');
|
||
process.exit(1);
|
||
}
|
||
|
||
console.log('✅ API KEY 已配置:', process.env.GENERATE_BG_API_KEY.substring(0, 15) + '...');
|
||
|
||
// 准备测试图片
|
||
const testImagePath = 'uploads/temp/test_image_600.jpg';
|
||
|
||
if (!fs.existsSync(testImagePath)) {
|
||
console.log('\n📸 准备测试图片...');
|
||
|
||
// 查找任意一张图片
|
||
const tempDir = 'uploads/temp';
|
||
const files = fs.readdirSync(tempDir);
|
||
const jpgFile = files.find(f => f.endsWith('.jpg'));
|
||
|
||
if (!jpgFile) {
|
||
console.error('❌ 未找到测试图片');
|
||
console.log('💡 请先在 uploads/temp 目录放置一张图片');
|
||
process.exit(1);
|
||
}
|
||
|
||
const sourceImage = path.join(tempDir, jpgFile);
|
||
await sharp(sourceImage)
|
||
.resize(600, null, {
|
||
fit: 'inside',
|
||
withoutEnlargement: true
|
||
})
|
||
.jpeg({ quality: 90 })
|
||
.toFile(testImagePath);
|
||
|
||
console.log('✅ 测试图片已准备:', testImagePath);
|
||
}
|
||
|
||
// 获取原始图片信息
|
||
const metadata = await sharp(testImagePath).metadata();
|
||
const stats = fs.statSync(testImagePath);
|
||
|
||
console.log('\n📁 测试图片信息:');
|
||
console.log(' 路径:', testImagePath);
|
||
console.log(' 尺寸:', `${metadata.width}x${metadata.height}`);
|
||
console.log(' 大小:', `${(stats.size / 1024).toFixed(2)}KB`);
|
||
|
||
// 读取并转换为 base64
|
||
console.log('\n🔄 转换为 base64...');
|
||
const imageBuffer = fs.readFileSync(testImagePath);
|
||
const imageBase64 = imageBuffer.toString('base64');
|
||
console.log(' Base64 长度:', imageBase64.length, '字符');
|
||
|
||
// 调用 API
|
||
console.log('\n🎨 调用图像拓展 API...');
|
||
const startTime = Date.now();
|
||
|
||
const requestBody = {
|
||
model: "image-out-painting",
|
||
input: {
|
||
image_base64: imageBase64
|
||
},
|
||
parameters: {
|
||
x_scale: 1.5,
|
||
y_scale: 1.5,
|
||
best_quality: false, // 与系统配置保持一致
|
||
limit_image_size: true,
|
||
add_watermark: false
|
||
}
|
||
};
|
||
|
||
console.log(' 参数: 1.5倍等比例扩展, 最佳质量');
|
||
|
||
const response = await fetch('https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/out-painting', {
|
||
method: 'POST',
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
'Authorization': `Bearer ${process.env.GENERATE_BG_API_KEY}`,
|
||
'X-DashScope-Async': 'enable'
|
||
},
|
||
body: JSON.stringify(requestBody)
|
||
});
|
||
|
||
const initialResult = await response.json();
|
||
console.log('\n📝 API 响应:');
|
||
console.log(JSON.stringify(initialResult, null, 2));
|
||
|
||
if (initialResult.code) {
|
||
console.error('\n❌ API 调用失败:', initialResult.message);
|
||
process.exit(1);
|
||
}
|
||
|
||
// 获取任务信息
|
||
const taskId = initialResult.output.task_id;
|
||
const taskStatusUrl = `https://dashscope.aliyuncs.com/api/v1/tasks/${taskId}`;
|
||
|
||
console.log('\n⏳ 任务已提交:');
|
||
console.log(' 任务 ID:', taskId);
|
||
console.log(' 状态查询:', taskStatusUrl);
|
||
console.log(' 等待处理...\n');
|
||
|
||
// 先等待3秒,给API足够的初始化时间
|
||
console.log(' [0秒] 等待API初始化...');
|
||
await new Promise(resolve => setTimeout(resolve, 3000));
|
||
|
||
// 轮询获取结果
|
||
let result;
|
||
let attempts = 0;
|
||
const maxAttempts = 60; // 最多轮询60次
|
||
const pollInterval = 2000; // 每2秒轮询一次(总计最多123秒)
|
||
|
||
while (attempts < maxAttempts) {
|
||
const statusResponse = await fetch(taskStatusUrl, {
|
||
headers: {
|
||
'Authorization': `Bearer ${process.env.GENERATE_BG_API_KEY}`
|
||
}
|
||
});
|
||
|
||
result = await statusResponse.json();
|
||
|
||
// 显示当前状态
|
||
const elapsedTime = attempts * 2 + 3;
|
||
const status = result.output?.task_status || 'UNKNOWN';
|
||
console.log(` [${elapsedTime}秒] 任务状态: ${status}`);
|
||
|
||
if (result.output && result.output.task_status === 'SUCCEEDED') {
|
||
console.log(`\n✅ 任务完成!(总用时 ${elapsedTime} 秒)`);
|
||
break;
|
||
} else if (result.output && result.output.task_status === 'FAILED') {
|
||
console.error('\n❌ 任务失败:', result.output.message || result.output.code);
|
||
console.error('完整错误信息:', JSON.stringify(result.output, null, 2));
|
||
process.exit(1);
|
||
}
|
||
|
||
attempts++;
|
||
|
||
// 未完成,继续等待
|
||
if (attempts < maxAttempts) {
|
||
await new Promise(resolve => setTimeout(resolve, pollInterval));
|
||
}
|
||
}
|
||
|
||
if (attempts >= maxAttempts) {
|
||
console.error(`\n❌ 任务超时(等待${maxAttempts * 2 + 3}秒)`);
|
||
console.error('最后状态:', result?.output?.task_status || 'UNKNOWN');
|
||
process.exit(1);
|
||
}
|
||
|
||
// 获取结果
|
||
if (!result.output || !result.output.output_image_url) {
|
||
console.error('\n❌ 未获取到拓展后的图片');
|
||
console.error('输出内容:', JSON.stringify(result.output, null, 2));
|
||
process.exit(1);
|
||
}
|
||
|
||
const extendedImageUrl = result.output.output_image_url;
|
||
console.log('\n📥 下载拓展后的图片...');
|
||
console.log(' URL:', extendedImageUrl);
|
||
|
||
const imageResponse = await fetch(extendedImageUrl);
|
||
if (!imageResponse.ok) {
|
||
console.error('❌ 下载失败:', imageResponse.status, imageResponse.statusText);
|
||
process.exit(1);
|
||
}
|
||
|
||
const arrayBuffer = await imageResponse.arrayBuffer();
|
||
const buffer = Buffer.from(arrayBuffer);
|
||
|
||
// 保存
|
||
const extendedPath = testImagePath.replace('.jpg', '_extended.jpg');
|
||
fs.writeFileSync(extendedPath, buffer);
|
||
|
||
// 验证
|
||
const extendedMetadata = await sharp(extendedPath).metadata();
|
||
const extendedStats = fs.statSync(extendedPath);
|
||
|
||
const endTime = Date.now();
|
||
const totalTime = ((endTime - startTime) / 1000).toFixed(2);
|
||
|
||
console.log('\n' + '='.repeat(60));
|
||
console.log('✅ 测试成功!');
|
||
console.log('='.repeat(60));
|
||
console.log('\n📊 结果对比:');
|
||
console.log(' 原图:');
|
||
console.log(' - 尺寸:', `${metadata.width}x${metadata.height}`);
|
||
console.log(' - 大小:', `${(stats.size / 1024).toFixed(2)}KB`);
|
||
console.log(' - 文件:', testImagePath);
|
||
console.log(' 拓展后:');
|
||
console.log(' - 尺寸:', `${extendedMetadata.width}x${extendedMetadata.height}`);
|
||
console.log(' - 大小:', `${(extendedStats.size / 1024).toFixed(2)}KB`);
|
||
console.log(' - 文件:', extendedPath);
|
||
console.log(' 放大倍数:');
|
||
console.log(' - 宽度:', `${(extendedMetadata.width / metadata.width).toFixed(2)}x`);
|
||
console.log(' - 高度:', `${(extendedMetadata.height / metadata.height).toFixed(2)}x`);
|
||
console.log(' - 像素:', `${((extendedMetadata.width * extendedMetadata.height) / (metadata.width * metadata.height)).toFixed(2)}x`);
|
||
console.log('\n⏱️ 总耗时:', totalTime, '秒');
|
||
console.log('='.repeat(60));
|
||
}
|
||
|
||
// 运行测试
|
||
testImageExtend().catch(error => {
|
||
console.error('\n❌ 测试失败:', error.message);
|
||
if (error.stack) {
|
||
console.error('\n堆栈信息:');
|
||
console.error(error.stack);
|
||
}
|
||
process.exit(1);
|
||
});
|
||
|