功能: - 在系统设置中添加备用API配置选项 - 支持管理员切换使用主API或备用Real-ESRGAN API - 备用API使用Base64方式发送图片 - 支持配置放大倍数(2x/4x/8x)和模型选择 Real-ESRGAN API特点: - 基于深度学习的图像超分辨率模型 - 支持RealESRGAN_x2plus/x4plus/x8plus模型 - 支持动漫视频模型 - 处理时间1-10秒 后台切换对前端用户透明无感知
822 lines
31 KiB
TypeScript
822 lines
31 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
||
import { getSystemSetting } from "@/lib/db/queries";
|
||
import { auth } from "@/app/(auth)/auth";
|
||
import { uploadFile } from "@/lib/storage/service";
|
||
import { db } from "@/lib/db";
|
||
import { generatedImage } from "@/lib/db/schema";
|
||
|
||
// 变清晰API配置类型
|
||
type EnhanceApiConfig = {
|
||
apiUrl?: string;
|
||
apiKey?: string;
|
||
type?: string; // "clean" | "face"
|
||
scaleFactor?: number | string; // 1 | 2 | 4 | "auto"
|
||
// 备用API配置 (Real-ESRGAN)
|
||
useBackupApi?: boolean;
|
||
backupApiUrl?: string;
|
||
backupApiKey?: string;
|
||
backupScale?: string; // "2" | "4" | "8"
|
||
backupModel?: string;
|
||
};
|
||
|
||
/**
|
||
* 压缩图片生成缩略图(使用 sharp)
|
||
*/
|
||
async function createThumbnail(buffer: Buffer, mimeType: string): Promise<Buffer> {
|
||
try {
|
||
const sharp = await import("sharp");
|
||
|
||
// 创建缩略图(宽度 500px,高度按比例,质量 80%)
|
||
const thumbnailBuffer = await sharp.default(buffer)
|
||
.resize(500, null, {
|
||
fit: "inside",
|
||
withoutEnlargement: true,
|
||
})
|
||
.jpeg({ quality: 80 }) // JPEG格式
|
||
.toBuffer();
|
||
|
||
console.log(`[Enhance] Thumbnail created, size: ${thumbnailBuffer.length} bytes (original: ${buffer.length} bytes)`);
|
||
return thumbnailBuffer;
|
||
} catch (error) {
|
||
console.error("[Enhance] Failed to create thumbnail:", error);
|
||
// 如果失败,返回原图
|
||
return buffer;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 将 base64 图片上传到 S3,返回缩略图和原图的 URL
|
||
*/
|
||
async function uploadBase64ToS3(base64Data: string, mimeType: string = "image/jpeg"): Promise<{ thumbnail: string; original: string }> {
|
||
try {
|
||
// 解析 base64 数据
|
||
const buffer = Buffer.from(base64Data, "base64");
|
||
|
||
// 生成文件名
|
||
const ext = mimeType.split("/")[1] || "jpg";
|
||
const timestamp = Date.now();
|
||
const randomStr = Math.random().toString(36).slice(2, 8);
|
||
const thumbnailFilename = `enhance-thumb-${timestamp}-${randomStr}.${ext}`;
|
||
const originalFilename = `enhance-orig-${timestamp}-${randomStr}.${ext}`;
|
||
|
||
console.log(`[Enhance] Original size: ${buffer.length} bytes`);
|
||
|
||
// 生成缩略图
|
||
const thumbnailBuffer = await createThumbnail(buffer, mimeType);
|
||
|
||
// 转换为 ArrayBuffer
|
||
const thumbnailArrayBuffer = thumbnailBuffer.buffer.slice(
|
||
thumbnailBuffer.byteOffset,
|
||
thumbnailBuffer.byteOffset + thumbnailBuffer.byteLength
|
||
) as ArrayBuffer;
|
||
const originalArrayBuffer = buffer.buffer.slice(
|
||
buffer.byteOffset,
|
||
buffer.byteOffset + buffer.byteLength
|
||
) as ArrayBuffer;
|
||
|
||
// 并行上传缩略图和原图到 S3
|
||
console.log(`[Enhance] Uploading thumbnail and original to S3...`);
|
||
const [thumbnailResult, originalResult] = await Promise.all([
|
||
uploadFile(thumbnailFilename, thumbnailArrayBuffer),
|
||
uploadFile(originalFilename, originalArrayBuffer),
|
||
]);
|
||
|
||
console.log(`[Enhance] Uploaded to S3:`);
|
||
console.log(` - Thumbnail: ${thumbnailResult.url}`);
|
||
console.log(` - Original: ${originalResult.url}`);
|
||
|
||
return {
|
||
thumbnail: thumbnailResult.url,
|
||
original: originalResult.url,
|
||
};
|
||
} catch (error) {
|
||
console.error("[Enhance] Failed to upload to S3:", error);
|
||
throw new Error(`图片上传到存储桶失败: ${error instanceof Error ? error.message : "未知错误"}。请检查系统设置中的存储配置。`);
|
||
}
|
||
}
|
||
|
||
// 设置API路由最大执行时间为3分钟(180秒)
|
||
export const maxDuration = 180;
|
||
|
||
/**
|
||
* 使用Real-ESRGAN备用API处理图片(通过URL方式)
|
||
* @param imageUrl 图片URL(需要公开可访问)
|
||
* @param config 备用API配置
|
||
* @returns 处理后的图片Base64和S3 URL
|
||
*/
|
||
async function processWithRealESRGAN(
|
||
imageUrl: string,
|
||
config: {
|
||
backupApiUrl: string;
|
||
backupApiKey: string;
|
||
backupScale: string;
|
||
backupModel: string;
|
||
}
|
||
): Promise<{ imageBase64: string; imageUrl: string; processingTime: number }> {
|
||
const startTime = Date.now();
|
||
const apiUrl = config.backupApiUrl.endsWith("/")
|
||
? config.backupApiUrl.slice(0, -1)
|
||
: config.backupApiUrl;
|
||
|
||
const upscaleUrl = `${apiUrl}/upscale/url`;
|
||
console.log(`[Enhance-RealESRGAN] 调用URL方式API: ${upscaleUrl}`);
|
||
console.log(`[Enhance-RealESRGAN] 图片URL: ${imageUrl}`);
|
||
console.log(`[Enhance-RealESRGAN] 放大倍数: ${config.backupScale}x, 模型: ${config.backupModel}`);
|
||
|
||
const response = await fetch(upscaleUrl, {
|
||
method: "POST",
|
||
headers: {
|
||
"Content-Type": "application/json",
|
||
"X-API-Key": config.backupApiKey,
|
||
},
|
||
body: JSON.stringify({
|
||
image_url: imageUrl,
|
||
scale: Number.parseInt(config.backupScale) || 4,
|
||
model_name: config.backupModel || "RealESRGAN_x4plus",
|
||
}),
|
||
});
|
||
|
||
if (!response.ok) {
|
||
const errorText = await response.text();
|
||
console.error(`[Enhance-RealESRGAN] API请求失败: ${response.status} ${response.statusText}`);
|
||
console.error(`[Enhance-RealESRGAN] 错误详情: ${errorText}`);
|
||
throw new Error(`Real-ESRGAN API请求失败: ${response.status} - ${errorText || response.statusText}`);
|
||
}
|
||
|
||
const result = await response.json();
|
||
console.log(`[Enhance-RealESRGAN] API响应:`, {
|
||
success: result.success,
|
||
hasImageUrl: !!result.image_url,
|
||
processingTime: result.processing_time,
|
||
totalTime: result.total_time,
|
||
});
|
||
|
||
if (!result.success || !result.image_url) {
|
||
throw new Error(`Real-ESRGAN处理失败: ${JSON.stringify(result)}`);
|
||
}
|
||
|
||
// Real-ESRGAN API直接返回S3 URL,我们需要下载图片并转换为Base64
|
||
console.log(`[Enhance-RealESRGAN] 下载处理后的图片: ${result.image_url}`);
|
||
const imageResponse = await fetch(result.image_url);
|
||
if (!imageResponse.ok) {
|
||
throw new Error(`无法下载Real-ESRGAN处理后的图片: ${imageResponse.status}`);
|
||
}
|
||
|
||
const imageBuffer = await imageResponse.arrayBuffer();
|
||
const imageBase64 = Buffer.from(imageBuffer).toString("base64");
|
||
|
||
const processingTime = (Date.now() - startTime) / 1000;
|
||
console.log(`[Enhance-RealESRGAN] ✅ 处理完成,总耗时: ${processingTime.toFixed(2)}秒`);
|
||
console.log(`[Enhance-RealESRGAN] ✅ 处理后图片大小: ${imageBuffer.byteLength} bytes`);
|
||
|
||
return {
|
||
imageBase64,
|
||
imageUrl: result.image_url,
|
||
processingTime,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 使用Real-ESRGAN备用API处理图片(通过Base64方式,用于没有公开URL的图片)
|
||
* @param imageBase64 图片Base64数据
|
||
* @param config 备用API配置
|
||
* @returns 处理后的图片Base64
|
||
*/
|
||
async function processWithRealESRGANBase64(
|
||
imageBase64: string,
|
||
config: {
|
||
backupApiUrl: string;
|
||
backupApiKey: string;
|
||
backupScale: string;
|
||
backupModel: string;
|
||
}
|
||
): Promise<{ imageBase64: string; processingTime: number }> {
|
||
const startTime = Date.now();
|
||
const apiUrl = config.backupApiUrl.endsWith("/")
|
||
? config.backupApiUrl.slice(0, -1)
|
||
: config.backupApiUrl;
|
||
|
||
const upscaleUrl = `${apiUrl}/upscale/base64`;
|
||
console.log(`[Enhance-RealESRGAN] 调用Base64方式API: ${upscaleUrl}`);
|
||
console.log(`[Enhance-RealESRGAN] 放大倍数: ${config.backupScale}x, 模型: ${config.backupModel}`);
|
||
console.log(`[Enhance-RealESRGAN] 输入图片Base64长度: ${imageBase64.length}`);
|
||
|
||
const response = await fetch(upscaleUrl, {
|
||
method: "POST",
|
||
headers: {
|
||
"Content-Type": "application/json",
|
||
"X-API-Key": config.backupApiKey,
|
||
},
|
||
body: JSON.stringify({
|
||
image_base64: imageBase64,
|
||
scale: Number.parseInt(config.backupScale) || 4,
|
||
model_name: config.backupModel || "RealESRGAN_x4plus",
|
||
}),
|
||
});
|
||
|
||
if (!response.ok) {
|
||
const errorText = await response.text();
|
||
console.error(`[Enhance-RealESRGAN] API请求失败: ${response.status} ${response.statusText}`);
|
||
console.error(`[Enhance-RealESRGAN] 错误详情: ${errorText}`);
|
||
throw new Error(`Real-ESRGAN API请求失败: ${response.status} - ${errorText || response.statusText}`);
|
||
}
|
||
|
||
const result = await response.json();
|
||
console.log(`[Enhance-RealESRGAN] API响应:`, {
|
||
success: result.success,
|
||
hasImageBase64: !!result.image_base64,
|
||
processingTime: result.processing_time,
|
||
});
|
||
|
||
if (!result.success || !result.image_base64) {
|
||
throw new Error(`Real-ESRGAN处理失败: ${JSON.stringify(result)}`);
|
||
}
|
||
|
||
const processingTime = (Date.now() - startTime) / 1000;
|
||
console.log(`[Enhance-RealESRGAN] ✅ 处理完成,总耗时: ${processingTime.toFixed(2)}秒`);
|
||
console.log(`[Enhance-RealESRGAN] ✅ 处理后图片Base64长度: ${result.image_base64.length}`);
|
||
|
||
return {
|
||
imageBase64: result.image_base64,
|
||
processingTime,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 轮询获取任务结果(根据官方示例)
|
||
*/
|
||
async function pollTaskResult(
|
||
apiUrl: string,
|
||
apiKey: string,
|
||
taskId: string,
|
||
delay: number = 1000,
|
||
timeout: number = 120000 // 增加到120秒(2分钟)
|
||
): Promise<any> {
|
||
const pollUrl = `${apiUrl}/api/tasks/visual/scale/${taskId}`;
|
||
|
||
const getTaskResult = async (): Promise<any> => {
|
||
const response = await fetch(pollUrl, {
|
||
method: "GET",
|
||
headers: {
|
||
"X-API-KEY": apiKey,
|
||
},
|
||
});
|
||
|
||
if (!response.ok) {
|
||
throw new Error(`轮询请求失败: ${response.status} ${response.statusText}`);
|
||
}
|
||
|
||
const result = await response.json();
|
||
|
||
if (!result.data) {
|
||
throw result;
|
||
}
|
||
|
||
const { progress, state } = result.data;
|
||
console.log(`[Enhance] 轮询进度: progress=${progress}%, state=${state}, task_id=${taskId}`);
|
||
|
||
// state < 0 表示失败
|
||
if (state < 0) {
|
||
throw result;
|
||
}
|
||
|
||
// progress >= 100 表示完成
|
||
if (progress >= 100) {
|
||
console.log(`[Enhance] 任务完成,task_id=${taskId}`);
|
||
return result;
|
||
}
|
||
|
||
// 否则继续轮询
|
||
throw null;
|
||
};
|
||
|
||
try {
|
||
const result = await getTaskResult();
|
||
return result;
|
||
} catch (error) {
|
||
if (error && typeof error === 'object' && 'data' in error) {
|
||
throw new Error(JSON.stringify(error, null, 2));
|
||
}
|
||
if (timeout <= 0) {
|
||
throw new Error('轮询超时');
|
||
}
|
||
await new Promise((resolve) => {
|
||
setTimeout(() => {
|
||
resolve(undefined);
|
||
}, delay);
|
||
});
|
||
return pollTaskResult(apiUrl, apiKey, taskId, delay, timeout - delay);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 图片变清晰API路由
|
||
* 从数据库读取变清晰API配置,调用外部API进行图片增强处理
|
||
* 将处理后的图片上传到S3并保存到数据库
|
||
*/
|
||
export async function POST(request: NextRequest) {
|
||
console.log("[Enhance API] ===== 收到请求 =====");
|
||
try {
|
||
// 0. 获取用户会话
|
||
console.log("[Enhance API] 开始获取用户会话...");
|
||
const session = await auth();
|
||
console.log("[Enhance API] 用户会话获取完成:", session?.user?.id ? "已登录" : "未登录");
|
||
if (!session?.user?.id) {
|
||
return NextResponse.json(
|
||
{ error: "未授权,请先登录" },
|
||
{ status: 401 }
|
||
);
|
||
}
|
||
|
||
const userId = session.user.id;
|
||
console.log("[Enhance API] 用户ID:", userId);
|
||
// 1. 从数据库获取变清晰API配置
|
||
console.log("[Enhance API] 开始获取配置...");
|
||
const enhanceConfig = await getSystemSetting({ key: "enhance_api_config" });
|
||
console.log("[Enhance API] 配置获取完成:", enhanceConfig ? "已找到" : "未找到");
|
||
|
||
if (!enhanceConfig || !enhanceConfig.value) {
|
||
return NextResponse.json(
|
||
{ error: "变清晰API配置未设置,请在系统设置中配置" },
|
||
{ status: 400 }
|
||
);
|
||
}
|
||
|
||
const config = enhanceConfig.value as EnhanceApiConfig;
|
||
|
||
// 检查是否使用备用API
|
||
const useBackupApi = config.useBackupApi === true;
|
||
console.log(`[Enhance API] 使用${useBackupApi ? "备用API (Real-ESRGAN)" : "主API"}`);
|
||
|
||
if (useBackupApi) {
|
||
// 验证备用API配置
|
||
if (!config.backupApiUrl || !config.backupApiKey) {
|
||
return NextResponse.json(
|
||
{ error: "备用变清晰API地址或密钥未配置" },
|
||
{ status: 400 }
|
||
);
|
||
}
|
||
} else {
|
||
// 验证主API配置
|
||
if (!config.apiUrl || !config.apiKey) {
|
||
return NextResponse.json(
|
||
{ error: "变清晰API地址或密钥未配置" },
|
||
{ status: 400 }
|
||
);
|
||
}
|
||
}
|
||
|
||
// 2. 获取请求体(Base64图片或FormData)
|
||
console.log("[Enhance API] 开始获取请求体...");
|
||
const contentType = request.headers.get("content-type") || "";
|
||
console.log("[Enhance API] Content-Type:", contentType);
|
||
|
||
let imageBase64: string;
|
||
let prompt = ""; // 用户提示词(可选)
|
||
let chatId: string | null = null; // 聊天ID(可选)
|
||
let messageId: string | null = null; // 消息ID(可选)
|
||
|
||
if (contentType.includes("application/json")) {
|
||
// JSON格式:Base64图片
|
||
console.log("[Enhance API] 解析JSON请求体...");
|
||
const body = await request.json();
|
||
console.log("[Enhance API] JSON请求体解析完成,image_base64长度:", body.image_base64?.length || 0);
|
||
imageBase64 = body.image_base64;
|
||
prompt = body.prompt || "图片变清晰处理";
|
||
chatId = body.chatId || null;
|
||
messageId = body.messageId || null;
|
||
|
||
if (!imageBase64) {
|
||
return NextResponse.json(
|
||
{ error: "缺少image_base64参数" },
|
||
{ status: 400 }
|
||
);
|
||
}
|
||
} else if (contentType.includes("multipart/form-data")) {
|
||
// FormData格式:文件上传
|
||
const formData = await request.formData();
|
||
const file = formData.get("file") as File;
|
||
|
||
if (!file) {
|
||
return NextResponse.json(
|
||
{ error: "缺少file参数" },
|
||
{ status: 400 }
|
||
);
|
||
}
|
||
|
||
// 将文件转换为Base64
|
||
const arrayBuffer = await file.arrayBuffer();
|
||
const buffer = Buffer.from(arrayBuffer);
|
||
imageBase64 = buffer.toString("base64");
|
||
prompt = (formData.get("prompt") as string) || "图片变清晰处理";
|
||
chatId = (formData.get("chatId") as string) || null;
|
||
messageId = (formData.get("messageId") as string) || null;
|
||
} else {
|
||
return NextResponse.json(
|
||
{ error: "不支持的Content-Type,请使用application/json或multipart/form-data" },
|
||
{ status: 400 }
|
||
);
|
||
}
|
||
|
||
// ========== 备用API处理路径 (Real-ESRGAN) ==========
|
||
if (useBackupApi) {
|
||
console.log("[Enhance API] 使用Real-ESRGAN备用API处理...");
|
||
|
||
try {
|
||
// 使用Base64方式调用Real-ESRGAN API
|
||
const result = await processWithRealESRGANBase64(imageBase64, {
|
||
backupApiUrl: config.backupApiUrl!,
|
||
backupApiKey: config.backupApiKey!,
|
||
backupScale: config.backupScale || "4",
|
||
backupModel: config.backupModel || "RealESRGAN_x4plus",
|
||
});
|
||
|
||
// 上传处理后的图片到S3
|
||
let thumbnailUrl: string;
|
||
let originalUrl: string;
|
||
|
||
try {
|
||
console.log(`[Enhance-RealESRGAN] 📤 上传处理后的图片到S3...`);
|
||
const uploadResult = await uploadBase64ToS3(result.imageBase64, "image/png");
|
||
thumbnailUrl = uploadResult.thumbnail;
|
||
originalUrl = uploadResult.original;
|
||
console.log(`[Enhance-RealESRGAN] ✅ 上传成功: ${originalUrl}`);
|
||
} catch (uploadError) {
|
||
console.error("[Enhance-RealESRGAN] ❌ 上传到S3失败:", uploadError);
|
||
return NextResponse.json(
|
||
{
|
||
error: "图片上传到存储桶失败",
|
||
detail: uploadError instanceof Error ? uploadError.message : "未知错误"
|
||
},
|
||
{ status: 500 }
|
||
);
|
||
}
|
||
|
||
// 保存到数据库
|
||
try {
|
||
const [savedImage] = await db.insert(generatedImage).values({
|
||
userId,
|
||
chatId: chatId || null,
|
||
messageId: messageId || null,
|
||
thumbnailUrl,
|
||
originalUrl,
|
||
imageSize: `${config.backupScale}x放大`,
|
||
prompt: prompt || "Real-ESRGAN图片变清晰处理",
|
||
modelId: `realesrgan-${config.backupModel}`,
|
||
}).returning();
|
||
console.log(`[Enhance-RealESRGAN] ✅ 保存到数据库成功,ID: ${savedImage.id}`);
|
||
} catch (dbError) {
|
||
console.error("[Enhance-RealESRGAN] ⚠️ 保存到数据库失败:", dbError);
|
||
// 继续返回成功,图片已处理并上传
|
||
}
|
||
|
||
// 返回结果
|
||
return NextResponse.json({
|
||
success: true,
|
||
image_base64: result.imageBase64,
|
||
thumbnail_url: thumbnailUrl,
|
||
original_url: originalUrl,
|
||
processing_time: result.processingTime,
|
||
api_type: "realesrgan",
|
||
});
|
||
|
||
} catch (error) {
|
||
console.error("[Enhance-RealESRGAN] ❌ 处理失败:", error);
|
||
return NextResponse.json(
|
||
{
|
||
error: "Real-ESRGAN变清晰处理失败",
|
||
detail: error instanceof Error ? error.message : "未知错误",
|
||
},
|
||
{ status: 500 }
|
||
);
|
||
}
|
||
}
|
||
|
||
// ========== 主API处理路径 ==========
|
||
// 3. 调用变清晰API(使用异步模式,根据官方示例)
|
||
console.log("[Enhance API] 开始准备主API调用...");
|
||
const apiUrl = config.apiUrl!.endsWith("/")
|
||
? config.apiUrl!.slice(0, -1)
|
||
: config.apiUrl!;
|
||
|
||
const enhanceUrl = `${apiUrl}/api/tasks/visual/scale`;
|
||
console.log("[Enhance API] API URL:", enhanceUrl);
|
||
|
||
// 将Base64转换为Buffer
|
||
console.log("[Enhance API] 转换Base64为Buffer,长度:", imageBase64.length);
|
||
const imageBuffer = Buffer.from(imageBase64, "base64");
|
||
console.log("[Enhance API] Buffer创建完成,大小:", imageBuffer.length, "bytes");
|
||
|
||
// 创建FormData(使用form-data包,Node.js环境)
|
||
console.log("[Enhance API] 创建FormData...");
|
||
const FormDataLib = await import("form-data");
|
||
const formData = new FormDataLib.default();
|
||
console.log("[Enhance API] FormData创建完成");
|
||
formData.append("image_file", imageBuffer, {
|
||
filename: "image.jpg",
|
||
contentType: "image/jpeg",
|
||
});
|
||
// 使用异步模式(sync=0),根据官方示例
|
||
formData.append("sync", "0");
|
||
formData.append("type", config.type || "clean"); // 默认通用清晰化
|
||
const scaleFactorValue = typeof config.scaleFactor === "number" ? config.scaleFactor : (config.scaleFactor === "auto" ? undefined : Number.parseInt(String(config.scaleFactor)));
|
||
if (scaleFactorValue) {
|
||
formData.append("scale_factor", String(scaleFactorValue));
|
||
}
|
||
formData.append("return_type", "2"); // 返回base64
|
||
|
||
const headers: Record<string, string> = {
|
||
"X-API-KEY": config.apiKey!,
|
||
...formData.getHeaders(), // 包含Content-Type和boundary
|
||
};
|
||
|
||
const startTime = Date.now();
|
||
let taskId: string;
|
||
|
||
try {
|
||
console.log("[Enhance API] 开始创建任务...");
|
||
// 添加超时控制(60秒)
|
||
const controller = new AbortController();
|
||
const timeoutId = setTimeout(() => controller.abort(), 60000);
|
||
|
||
// 将FormData转换为Buffer(form-data包是stream)
|
||
console.log("[Enhance API] 转换FormData为Buffer...");
|
||
const formDataBuffer = await new Promise<Buffer>((resolve, reject) => {
|
||
const chunks: Buffer[] = [];
|
||
formData.on("data", (chunk: any) => {
|
||
// 确保chunk是Buffer类型
|
||
if (Buffer.isBuffer(chunk)) {
|
||
chunks.push(chunk);
|
||
} else if (typeof chunk === "string") {
|
||
chunks.push(Buffer.from(chunk, "utf-8"));
|
||
} else if (chunk instanceof Uint8Array) {
|
||
chunks.push(Buffer.from(chunk));
|
||
} else {
|
||
console.warn("[Enhance API] 未知的chunk类型:", typeof chunk, chunk);
|
||
chunks.push(Buffer.from(String(chunk), "utf-8"));
|
||
}
|
||
});
|
||
formData.on("end", () => {
|
||
console.log("[Enhance API] FormData stream结束,chunks数量:", chunks.length);
|
||
resolve(Buffer.concat(chunks));
|
||
});
|
||
formData.on("error", (error) => {
|
||
console.error("[Enhance API] FormData stream错误:", error);
|
||
reject(error);
|
||
});
|
||
|
||
// 重要:form-data包需要被pipe或手动触发才能开始流式传输
|
||
// 使用PassThrough来触发stream
|
||
const { PassThrough } = require("stream");
|
||
const passThrough = new PassThrough();
|
||
passThrough.on("data", () => {}); // 忽略数据,我们已经在formData上监听
|
||
formData.pipe(passThrough);
|
||
});
|
||
|
||
console.log("[Enhance API] FormData Buffer转换完成,大小:", formDataBuffer.length, "bytes");
|
||
|
||
// 将Buffer转换为Uint8Array用于fetch(更兼容)
|
||
const uint8Array = new Uint8Array(formDataBuffer);
|
||
|
||
console.log("[Enhance API] 发送创建任务请求...");
|
||
const createResponse = await fetch(enhanceUrl, {
|
||
method: "POST",
|
||
headers,
|
||
body: uint8Array,
|
||
signal: controller.signal,
|
||
});
|
||
|
||
console.log("[Enhance API] 创建任务响应状态:", createResponse.status, createResponse.statusText);
|
||
clearTimeout(timeoutId);
|
||
|
||
if (!createResponse.ok) {
|
||
const errorText = await createResponse.text();
|
||
throw new Error(`创建任务失败: ${errorText || createResponse.statusText}`);
|
||
}
|
||
|
||
const createResult = await createResponse.json();
|
||
|
||
if (!createResult.data || !createResult.data.task_id) {
|
||
throw new Error(`API未返回task_id: ${JSON.stringify(createResult)}`);
|
||
}
|
||
|
||
taskId = createResult.data.task_id;
|
||
console.log(`[Enhance] 任务已创建,task_id: ${taskId}`);
|
||
} catch (fetchError) {
|
||
const processingTime = (Date.now() - startTime) / 1000;
|
||
console.error("[Enhance API] 网络请求失败:", {
|
||
error: fetchError,
|
||
enhanceUrl,
|
||
processingTime,
|
||
});
|
||
|
||
// 检查是否是网络连接错误
|
||
if (fetchError instanceof Error) {
|
||
if (fetchError.name === 'AbortError') {
|
||
return NextResponse.json(
|
||
{
|
||
error: "变清晰API请求超时",
|
||
detail: "创建任务请求超过60秒未响应,请检查API服务器状态或网络连接",
|
||
},
|
||
{ status: 504 }
|
||
);
|
||
}
|
||
|
||
// 检查错误消息和cause中的网络错误
|
||
const errorMessage = fetchError.message || '';
|
||
const errorCause = (fetchError as any).cause;
|
||
const causeMessage = errorCause?.message || '';
|
||
const causeCode = errorCause?.code || '';
|
||
|
||
// 检查各种网络连接错误
|
||
if (errorMessage.includes('EHOSTUNREACH') ||
|
||
errorMessage.includes('ENOTFOUND') ||
|
||
errorMessage.includes('ECONNREFUSED') ||
|
||
errorMessage.includes('No route to host') ||
|
||
causeMessage.includes('EHOSTUNREACH') ||
|
||
causeMessage.includes('ENOTFOUND') ||
|
||
causeMessage.includes('ECONNREFUSED') ||
|
||
causeMessage.includes('No route to host') ||
|
||
causeCode === 'EHOSTUNREACH' ||
|
||
causeCode === 'ENOTFOUND' ||
|
||
causeCode === 'ECONNREFUSED') {
|
||
return NextResponse.json(
|
||
{
|
||
error: "无法连接到变清晰API服务器",
|
||
detail: `服务器无法访问 ${enhanceUrl},请检查:\n1. API服务器是否在线\n2. 网络连接是否正常\n3. 防火墙设置是否正确\n4. API地址和密钥是否正确`,
|
||
},
|
||
{ status: 503 }
|
||
);
|
||
}
|
||
}
|
||
|
||
return NextResponse.json(
|
||
{
|
||
error: "变清晰API请求失败",
|
||
detail: fetchError instanceof Error ? fetchError.message : "未知网络错误",
|
||
},
|
||
{ status: 500 }
|
||
);
|
||
}
|
||
|
||
// 4. 轮询获取任务结果(根据官方示例)
|
||
console.log(`[Enhance] 开始轮询任务结果,task_id: ${taskId}`);
|
||
const taskResult = await pollTaskResult(apiUrl, config.apiKey!, taskId);
|
||
|
||
const finalProcessingTime = (Date.now() - startTime) / 1000;
|
||
|
||
// 5. 处理返回结果
|
||
if (taskResult.status !== 200 || !taskResult.data) {
|
||
return NextResponse.json(
|
||
{ error: "变清晰处理失败", detail: taskResult.message || "未知错误" },
|
||
{ status: 500 }
|
||
);
|
||
}
|
||
|
||
// ✅ 记录原始输入图片大小(用于对比)
|
||
const originalImageSize = imageBuffer.length;
|
||
console.log(`[Enhance] 📊 原始输入图片大小: ${originalImageSize} bytes (${(originalImageSize / 1024 / 1024).toFixed(2)}MB)`);
|
||
|
||
// ✅ 打印外部API返回的完整数据结构(用于调试)
|
||
console.log(`[Enhance] 📋 外部API返回的taskResult.data结构:`, {
|
||
hasImageBase64: !!taskResult.data.image_base64,
|
||
hasImage: !!taskResult.data.image,
|
||
imageType: typeof taskResult.data.image,
|
||
imagePreview: typeof taskResult.data.image === "string" ? taskResult.data.image.substring(0, 100) : "非字符串",
|
||
status: taskResult.data.status,
|
||
progress: taskResult.data.progress,
|
||
state: taskResult.data.state,
|
||
});
|
||
|
||
let enhancedImageBase64: string;
|
||
|
||
if (taskResult.data.image_base64) {
|
||
// 返回的是base64
|
||
enhancedImageBase64 = taskResult.data.image_base64;
|
||
console.log(`[Enhance] ✅ API返回了image_base64,长度: ${enhancedImageBase64.length} 字符`);
|
||
} else if (taskResult.data.image) {
|
||
// 检查是否是URL(以http://或https://开头)
|
||
const imageData = taskResult.data.image;
|
||
console.log(`[Enhance] 📥 API返回了image字段,类型: ${typeof imageData}, 值: ${typeof imageData === "string" ? imageData.substring(0, 100) : "非字符串"}`);
|
||
|
||
if (typeof imageData === "string" && (imageData.startsWith("http://") || imageData.startsWith("https://"))) {
|
||
// 返回的是URL,需要下载
|
||
console.log(`[Enhance] 📥 从URL下载处理后的图片: ${imageData}`);
|
||
const imageResponse = await fetch(imageData);
|
||
if (!imageResponse.ok) {
|
||
return NextResponse.json(
|
||
{ error: "变清晰处理失败", detail: "无法下载处理后的图片" },
|
||
{ status: 500 }
|
||
);
|
||
}
|
||
const downloadedBuffer = await imageResponse.arrayBuffer();
|
||
enhancedImageBase64 = Buffer.from(downloadedBuffer).toString("base64");
|
||
const downloadedSize = downloadedBuffer.byteLength;
|
||
console.log(`[Enhance] ✅ 从URL下载完成,Base64长度: ${enhancedImageBase64.length} 字符,文件大小: ${downloadedSize} bytes`);
|
||
|
||
// ✅ 对比下载的图片和原图大小
|
||
if (Math.abs(downloadedSize - originalImageSize) < 100) {
|
||
console.warn(`[Enhance] ⚠️ 警告:下载的图片大小(${downloadedSize})和原图大小(${originalImageSize})几乎相同,可能外部API返回的是原图!`);
|
||
}
|
||
} else {
|
||
// 返回的是base64字符串(直接使用)
|
||
enhancedImageBase64 = imageData;
|
||
console.log(`[Enhance] ✅ API返回了base64字符串,长度: ${enhancedImageBase64.length} 字符`);
|
||
}
|
||
} else {
|
||
console.error(`[Enhance] ❌ 轮询结果未包含图片数据,taskResult.data:`, JSON.stringify(taskResult.data, null, 2));
|
||
return NextResponse.json(
|
||
{ error: "变清晰处理失败", detail: "轮询结果未包含图片数据" },
|
||
{ status: 500 }
|
||
);
|
||
}
|
||
|
||
if (!enhancedImageBase64) {
|
||
return NextResponse.json(
|
||
{ error: "变清晰处理失败", detail: "无法获取处理后的图片" },
|
||
{ status: 500 }
|
||
);
|
||
}
|
||
|
||
// ✅ 验证:检查处理后的图片大小(应该和原图不同)
|
||
const enhancedBuffer = Buffer.from(enhancedImageBase64, "base64");
|
||
const enhancedImageSize = enhancedBuffer.length;
|
||
console.log(`[Enhance] 📊 处理后的图片大小: ${enhancedImageSize} bytes (${(enhancedImageSize / 1024 / 1024).toFixed(2)}MB)`);
|
||
console.log(`[Enhance] 📊 处理后的图片Base64长度: ${enhancedImageBase64.length} 字符`);
|
||
|
||
// ✅ 对比:如果处理后的图片大小和原图完全相同,可能是返回了原图
|
||
if (Math.abs(enhancedImageSize - originalImageSize) < 100) {
|
||
console.warn(`[Enhance] ⚠️ 警告:处理后的图片大小(${enhancedImageSize})和原图大小(${originalImageSize})几乎相同,可能API返回的是原图!`);
|
||
} else {
|
||
const sizeDiff = ((enhancedImageSize - originalImageSize) / originalImageSize * 100).toFixed(1);
|
||
console.log(`[Enhance] ✅ 图片大小变化: ${sizeDiff}% (${sizeDiff.startsWith("-") ? "减小" : "增大"})`);
|
||
}
|
||
|
||
// 5. 上传处理后的图片到S3存储桶
|
||
let thumbnailUrl: string;
|
||
let originalUrl: string;
|
||
|
||
try {
|
||
// ✅ 确认:上传的是处理后的图片(enhancedImageBase64)
|
||
console.log(`[Enhance] 📤 准备上传处理后的图片到S3,Base64长度: ${enhancedImageBase64.length}`);
|
||
const uploadResult = await uploadBase64ToS3(enhancedImageBase64, "image/jpeg");
|
||
thumbnailUrl = uploadResult.thumbnail;
|
||
originalUrl = uploadResult.original;
|
||
console.log(`[Enhance] ✅ Images uploaded to S3 successfully`);
|
||
console.log(`[Enhance] ✅ 处理后的原图URL: ${originalUrl}`);
|
||
console.log(`[Enhance] ✅ 处理后的缩略图URL: ${thumbnailUrl}`);
|
||
} catch (uploadError) {
|
||
console.error("[Enhance] ❌ Failed to upload to S3:", uploadError);
|
||
return NextResponse.json(
|
||
{
|
||
error: "图片上传到存储桶失败",
|
||
detail: uploadError instanceof Error ? uploadError.message : "未知错误"
|
||
},
|
||
{ status: 500 }
|
||
);
|
||
}
|
||
|
||
// 6. 保存图片记录到数据库(相册和生图记录)
|
||
try {
|
||
const [savedImage] = await db.insert(generatedImage).values({
|
||
userId,
|
||
chatId: chatId || null,
|
||
messageId: messageId || null,
|
||
thumbnailUrl,
|
||
originalUrl,
|
||
imageSize: "2K", // 默认尺寸
|
||
prompt: prompt || "图片变清晰处理",
|
||
modelId: "enhance-1.0", // 标记为变清晰处理
|
||
}).returning();
|
||
console.log(`[Enhance] ✅ 图片已保存到相册和生图记录,ID: ${savedImage.id}`);
|
||
} catch (dbError) {
|
||
console.error("[Enhance] ❌ 保存到数据库失败:", dbError);
|
||
// 数据库保存失败时仍然返回成功,但记录错误(图片已上传到S3,用户可以访问)
|
||
// 如果希望严格保证数据一致性,可以取消注释下面的代码来返回错误
|
||
// return NextResponse.json(
|
||
// {
|
||
// error: "图片已处理但保存到相册失败",
|
||
// detail: dbError instanceof Error ? dbError.message : "未知错误"
|
||
// },
|
||
// { status: 500 }
|
||
// );
|
||
}
|
||
|
||
// 7. 返回结果(包含S3 URL和Base64,前端可以选择使用)
|
||
return NextResponse.json({
|
||
success: true,
|
||
image_base64: enhancedImageBase64, // 保留Base64用于前端立即显示
|
||
thumbnail_url: thumbnailUrl, // S3缩略图URL
|
||
original_url: originalUrl, // S3原图URL
|
||
processing_time: finalProcessingTime,
|
||
});
|
||
} catch (error) {
|
||
console.error("[Enhance API] 处理错误:", error);
|
||
return NextResponse.json(
|
||
{ error: "服务器内部错误", detail: error instanceof Error ? error.message : "未知错误" },
|
||
{ status: 500 }
|
||
);
|
||
}
|
||
}
|
||
|