/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
/**
* 图像生成管理钩子
* @param {Function} onImageGenerated 图片生成成功后的回调函数
* @returns {Object} 图像生成相关状态和方法
*/
const useImageGeneration = (onImageGenerated) => {
const { t } = useTranslation();
// 状态管理
const [generatedImages, setGeneratedImages] = useState([]);
const [isGenerating, setIsGenerating] = useState(false);
const [error, setError] = useState('');
const [generationParams, setGenerationParams] = useState({});
// 加载状态管理
const [isLoading, setIsLoading] = useState(false);
const [loadingProgress, setLoadingProgress] = useState(0);
// 用于存储上一次成功生成的参数
const lastSuccessfulParamsRef = useRef({});
// 清除错误信息
const clearError = useCallback(() => {
setError('');
}, []);
// 清除生成的图片
const clearGeneratedImages = useCallback(() => {
setGeneratedImages([]);
clearError();
}, [clearError]);
/**
* 生成图片
* @param {Object} params 生成参数
* @param {string} params.prompt 提示词
* @param {string} params.model 模型名称
* @param {string} params.size 图片尺寸
* @param {string} params.quality 图片质量
* @param {string} params.negativePrompt 反向提示词
* @param {number} params.n 生成图片数量
*/
const generateImage = useCallback(
async (params) => {
const {
prompt,
model,
size,
quality,
negativePrompt = '',
n = 1,
} = params;
// 参数验证
if (!prompt || !prompt.trim()) {
setError(t('请输入提示词'));
return false;
}
if (!model) {
setError(t('请选择生成模型'));
return false;
}
if (!size) {
setError(t('请选择图片尺寸'));
return false;
}
// 重置状态
setIsGenerating(true);
setError('');
setIsLoading(true);
setLoadingProgress(0);
// 保存当前参数
setGenerationParams(params);
try {
// 模拟进度更新
const progressInterval = setInterval(() => {
setLoadingProgress((prev) => {
if (prev >= 90) {
clearInterval(progressInterval);
return prev;
}
return prev + Math.random() * 10;
});
}, 200);
// 这里是模拟API调用,实际实现需要替换为真实的API请求
// 模拟网络延迟
await new Promise((resolve) => setTimeout(resolve, 3000));
clearInterval(progressInterval);
// 模拟生成的图片数据
const mockImages = Array.from({ length: n }, (_, index) => ({
id: Date.now() + index,
url: `https://picsum.photos/seed/${Date.now() + index}/${size.split('x')[0]}/${size.split('x')[1]}`,
revised_prompt: prompt,
created_at: new Date().toISOString(),
metadata: {
model,
size,
quality,
negative_prompt: negativePrompt,
},
}));
setGeneratedImages(mockImages);
// 更新上一次成功生成的参数
lastSuccessfulParamsRef.current = params;
// 调用回调函数
if (onImageGenerated) {
onImageGenerated(mockImages, params);
}
return true;
} catch (err) {
console.error('Image generation failed:', err);
setError(t('图片生成失败,请重试') + ': ' + (err.message || ''));
return false;
} finally {
setIsGenerating(false);
setIsLoading(false);
setLoadingProgress(100);
}
},
[t, onImageGenerated],
);
/**
* 重新生成图片
* 使用上一次成功生成的参数或当前保存的参数
*/
const regenerateImage = useCallback(async () => {
// 获取有效的参数
const params =
Object.keys(lastSuccessfulParamsRef.current).length > 0
? lastSuccessfulParamsRef.current
: Object.keys(generationParams).length > 0
? generationParams
: null;
if (!params) {
setError(t('没有可用的生成参数'));
return false;
}
// 确保参数完整
if (!params.prompt || !params.model || !params.size) {
setError(t('参数不完整,无法重新生成'));
return false;
}
return generateImage(params);
}, [generateImage, generationParams, t]);
/**
* 下载单个图片
* @param {string} imageUrl 图片URL
* @param {number} index 图片索引
* @param {string} prompt 提示词(用于生成文件名)
*/
const downloadImage = useCallback((imageUrl, index = 0, prompt = '') => {
const link = document.createElement('a');
// 生成文件名
let filename = 'generated-image';
// 如果有提示词,使用前20个字符作为文件名的一部分
if (prompt && prompt.trim()) {
const safePrompt = prompt
.trim()
.replace(/[^a-z0-9]/gi, '_')
.substring(0, 20);
filename = `${filename}-${safePrompt}`;
}
// 添加索引和时间戳
filename = `${filename}-${index}-${Date.now()}.png`;
link.href = imageUrl;
link.download = filename;
// 模拟点击下载
document.body.appendChild(link);
link.click();
// 清理
setTimeout(() => {
document.body.removeChild(link);
}, 100);
}, []);
/**
* 批量下载所有生成的图片
* @param {string} prompt 提示词(用于生成文件名前缀)
*/
const downloadAllImages = useCallback(
(prompt = '') => {
if (generatedImages.length === 0) {
setError(t('没有可下载的图片'));
return;
}
// 为每个图片创建下载
generatedImages.forEach((image, index) => {
downloadImage(image.url, index, prompt);
});
},
[generatedImages, downloadImage, t],
);
/**
* 将图片转换为Blob对象
* @param {string} imageUrl 图片URL
* @returns {Promise} Blob对象
*/
const imageUrlToBlob = useCallback(async (imageUrl) => {
try {
const response = await fetch(imageUrl);
const blob = await response.blob();
return blob;
} catch (error) {
console.error('Failed to convert image to blob:', error);
throw error;
}
}, []);
/**
* 将图片复制到剪贴板
* @param {string} imageUrl 图片URL
*/
const copyImageToClipboard = useCallback(
async (imageUrl) => {
try {
const blob = await imageUrlToBlob(imageUrl);
// 检查浏览器是否支持剪贴板API
if (navigator.clipboard && window.ClipboardItem) {
await navigator.clipboard.write([
new ClipboardItem({
'image/png': blob,
}),
]);
return true;
} else {
setError(t('您的浏览器不支持复制图片到剪贴板'));
return false;
}
} catch (error) {
console.error('Failed to copy image to clipboard:', error);
setError(t('复制图片失败: {{error}}', { error: error.message }));
return false;
}
},
[imageUrlToBlob, t],
);
/**
* 查看图片详情
* @param {Object} image 图片对象
*/
const viewImageDetails = useCallback((image) => {
// 可以在这里实现图片详情查看逻辑,比如打开模态框显示大图
console.log('Viewing image details:', image);
// 如果是浏览器环境,可以在新标签页打开图片
if (typeof window !== 'undefined' && window.open) {
window.open(image.url, '_blank');
}
}, []);
/**
* 获取图片信息
* @param {string} imageId 图片ID
* @returns {Object|null} 图片对象
*/
const getImageById = useCallback(
(imageId) => {
return generatedImages.find((image) => image.id === imageId) || null;
},
[generatedImages],
);
return {
// 状态
generatedImages,
isGenerating,
error,
loadingProgress,
isLoading,
generationParams,
// 操作方法
generateImage,
regenerateImage,
downloadImage,
downloadAllImages,
copyImageToClipboard,
viewImageDetails,
clearGeneratedImages,
clearError,
getImageById,
};
};
export default useImageGeneration;