{"repo_name": "easy-dataset", "file_name": "/easy-dataset/components/distill/ConfirmDialog.js", "inference_info": {"prefix_code": "'use client';\n\nimport { Dialog, DialogActions, DialogTitle, Button } from '@mui/material';\n\n/**\n * 通用确认对话框组件\n * @param {Object} props\n * @param {boolean} props.open - 对话框是否打开\n * @param {Function} props.onClose - 关闭对话框的回调\n * @param {Function} props.onConfirm - 确认操作的回调\n * @param {string} props.title - 对话框标题\n * @param {string} props.cancelText - 取消按钮文本\n * @param {string} props.confirmText - 确认按钮文本\n */\nexport default ", "suffix_code": "\n", "middle_code": "function ConfirmDialog({\n open,\n onClose,\n onConfirm,\n title,\n cancelText = '取消',\n confirmText = '确认',\n confirmColor = 'error'\n}) {\n return (\n \n {title}\n \n \n \n \n \n );\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "javascript", "sub_task_type": null}, "context_code": [["/easy-dataset/components/text-split/BatchEditChunkDialog.js", "'use client';\n\nimport { useState } from 'react';\nimport {\n Dialog,\n DialogTitle,\n DialogContent,\n DialogActions,\n Button,\n TextField,\n RadioGroup,\n FormControlLabel,\n Radio,\n FormControl,\n FormLabel,\n Box,\n Typography,\n Alert,\n CircularProgress\n} from '@mui/material';\nimport { useTranslation } from 'react-i18next';\n\n/**\n * 批量编辑文本块对话框\n * @param {Object} props\n * @param {boolean} props.open - 对话框是否打开\n * @param {Function} props.onClose - 关闭对话框的回调\n * @param {Function} props.onConfirm - 确认编辑的回调\n * @param {Array} props.selectedChunks - 选中的文本块ID数组\n * @param {number} props.totalChunks - 文本块总数\n * @param {boolean} props.loading - 是否正在处理\n */\nexport default function BatchEditChunksDialog({\n open,\n onClose,\n onConfirm,\n selectedChunks = [],\n totalChunks = 0,\n loading = false\n}) {\n const { t } = useTranslation();\n const [position, setPosition] = useState('start'); // 'start' 或 'end'\n const [content, setContent] = useState('');\n const [error, setError] = useState('');\n\n // 处理位置变更\n const handlePositionChange = event => {\n setPosition(event.target.value);\n };\n\n // 处理内容变更\n const handleContentChange = event => {\n setContent(event.target.value);\n if (error) setError('');\n };\n\n // 处理确认\n const handleConfirm = () => {\n if (!content.trim()) {\n setError(t('batchEdit.contentRequired'));\n return;\n }\n\n onConfirm({\n position,\n content: content.trim(),\n chunkIds: selectedChunks\n });\n };\n\n // 处理关闭\n const handleClose = () => {\n if (!loading) {\n setContent('');\n setError('');\n setPosition('start');\n onClose();\n }\n };\n\n return (\n \n {t('batchEdit.title')}\n\n \n \n {/* 选择提示 */}\n \n \n {selectedChunks.length === totalChunks\n ? t('batchEdit.allChunksSelected', { count: totalChunks })\n : t('batchEdit.selectedChunks', {\n selected: selectedChunks.length,\n total: totalChunks\n })}\n \n \n\n {/* 位置选择 */}\n \n \n {t('batchEdit.position')}\n \n \n } label={t('batchEdit.atBeginning')} />\n } label={t('batchEdit.atEnd')} />\n \n \n\n {/* 内容输入 */}\n \n\n {/* 预览示例 */}\n {content.trim() && (\n \n \n {t('batchEdit.preview')}:\n \n \n {position === 'start' ? (\n <>\n {content}\n {'\\n\\n[原始文本块内容...]'}\n \n ) : (\n <>\n {'[原始文本块内容...]\\n\\n'}\n {content}\n \n )}\n \n \n )}\n \n \n\n \n \n : null}\n >\n {loading ? t('batchEdit.processing') : t('batchEdit.applyToChunks', { count: selectedChunks.length })}\n \n \n \n );\n}\n"], ["/easy-dataset/components/distill/QuestionGenerationDialog.js", "'use client';\n\nimport React, { useState, useEffect } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport {\n Dialog,\n DialogTitle,\n DialogContent,\n DialogActions,\n Button,\n TextField,\n Typography,\n Box,\n CircularProgress,\n Alert,\n List,\n ListItem,\n ListItemText,\n Paper,\n IconButton,\n Divider\n} from '@mui/material';\nimport CloseIcon from '@mui/icons-material/Close';\nimport axios from 'axios';\nimport i18n from '@/lib/i18n';\n\n/**\n * 问题生成对话框组件\n * @param {Object} props\n * @param {boolean} props.open - 对话框是否打开\n * @param {Function} props.onClose - 关闭对话框的回调函数\n * @param {Function} props.onGenerated - 问题生成完成的回调函数\n * @param {string} props.projectId - 项目ID\n * @param {Object} props.tag - 标签对象\n * @param {string} props.tagPath - 标签路径\n * @param {Object} props.model - 选择的模型配置\n */\nexport default function QuestionGenerationDialog({ open, onClose, onGenerated, projectId, tag, tagPath, model }) {\n const { t } = useTranslation();\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState('');\n const [count, setCount] = useState(5);\n const [generatedQuestions, setGeneratedQuestions] = useState([]);\n\n // 处理生成问题\n const handleGenerateQuestions = async () => {\n try {\n setLoading(true);\n setError('');\n\n const response = await axios.post(`/api/projects/${projectId}/distill/questions`, {\n tagPath,\n currentTag: tag.label,\n tagId: tag.id,\n count,\n model,\n language: i18n.language\n });\n\n setGeneratedQuestions(response.data);\n } catch (error) {\n console.error('生成问题失败:', error);\n setError(error.response?.data?.error || t('distill.generateQuestionsError'));\n } finally {\n setLoading(false);\n }\n };\n\n // 处理生成完成\n const handleGenerateComplete = async () => {\n if (onGenerated) {\n onGenerated(generatedQuestions);\n }\n handleClose();\n };\n\n // 处理关闭对话框\n const handleClose = () => {\n setGeneratedQuestions([]);\n setError('');\n setCount(5);\n if (onClose) {\n onClose();\n }\n };\n\n // 处理数量变化\n const handleCountChange = event => {\n const value = parseInt(event.target.value);\n if (!isNaN(value) && value >= 1 && value <= 100) {\n setCount(value);\n }\n };\n\n return (\n \n \n \n {t('distill.generateQuestionsTitle', { tag: tag?.label || t('distill.unknownTag') })}\n \n \n \n \n \n\n \n {error && (\n \n {error}\n \n )}\n\n \n \n {t('distill.tagPath')}:\n \n \n {tagPath || tag?.label || t('distill.unknownTag')}\n \n \n\n \n \n {t('distill.questionCount')}:\n \n \n \n\n {generatedQuestions.length > 0 && (\n \n \n {t('distill.generatedQuestions')}:\n \n \n \n {generatedQuestions.map((question, index) => (\n \n {index > 0 && }\n \n \n \n \n ))}\n \n \n \n )}\n \n\n \n \n {generatedQuestions.length > 0 ? (\n \n ) : (\n }\n >\n {loading ? t('common.generating') : t('distill.generateQuestions')}\n \n )}\n \n \n );\n}\n"], ["/easy-dataset/components/distill/TagGenerationDialog.js", "'use client';\n\nimport { useState, useEffect } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport {\n Dialog,\n DialogTitle,\n DialogContent,\n DialogActions,\n Button,\n TextField,\n Typography,\n Box,\n CircularProgress,\n Alert,\n Chip,\n Paper,\n IconButton\n} from '@mui/material';\nimport CloseIcon from '@mui/icons-material/Close';\nimport axios from 'axios';\nimport i18n from '@/lib/i18n';\n\n/**\n * 标签生成对话框组件\n * @param {Object} props\n * @param {boolean} props.open - 对话框是否打开\n * @param {Function} props.onClose - 关闭对话框的回调函数\n * @param {Function} props.onGenerated - 标签生成完成的回调函数\n * @param {string} props.projectId - 项目ID\n * @param {Object} props.parentTag - 父标签对象,为null时表示生成根标签\n * @param {string} props.tagPath - 标签链路\n * @param {Object} props.model - 选择的模型配置\n */\nexport default function TagGenerationDialog({ open, onClose, onGenerated, projectId, parentTag, tagPath, model }) {\n const { t } = useTranslation();\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState('');\n const [count, setCount] = useState(5);\n const [generatedTags, setGeneratedTags] = useState([]);\n const [parentTagName, setParentTagName] = useState('');\n const [project, setProject] = useState(null);\n\n // 获取项目信息,如果是顶级标签,默认填写项目名称\n useEffect(() => {\n if (projectId && !parentTag) {\n axios\n .get(`/api/projects/${projectId}`)\n .then(response => {\n setProject(response.data);\n setParentTagName(response.data.name || '');\n })\n .catch(error => {\n console.error('获取项目信息失败:', error);\n });\n } else if (parentTag) {\n setParentTagName(parentTag.label || '');\n }\n }, [projectId, parentTag]);\n\n // 处理生成标签\n const handleGenerateTags = async () => {\n try {\n setLoading(true);\n setError('');\n\n const response = await axios.post(`/api/projects/${projectId}/distill/tags`, {\n parentTag: parentTagName,\n parentTagId: parentTag ? parentTag.id : null,\n tagPath: tagPath || parentTagName,\n count,\n model,\n language: i18n.language\n });\n\n setGeneratedTags(response.data);\n } catch (error) {\n console.error('生成标签失败:', error);\n setError(error.response?.data?.error || t('distill.generateTagsError'));\n } finally {\n setLoading(false);\n }\n };\n\n // 处理生成完成\n const handleGenerateComplete = async () => {\n if (onGenerated) {\n onGenerated(generatedTags);\n }\n handleClose();\n };\n\n // 处理关闭对话框\n const handleClose = () => {\n setGeneratedTags([]);\n setError('');\n setCount(5);\n if (onClose) {\n onClose();\n }\n };\n\n // 处理数量变化\n const handleCountChange = event => {\n const value = parseInt(event.target.value);\n if (!isNaN(value) && value >= 1 && value <= 100) {\n setCount(value);\n }\n };\n\n return (\n \n \n \n {parentTag\n ? t('distill.generateSubTagsTitle', { parentTag: parentTag.label })\n : t('distill.generateRootTagsTitle')}\n \n \n \n \n \n\n \n {error && (\n \n {error}\n \n )}\n\n {/* 标签路径显示 */}\n {parentTag && tagPath && (\n \n \n {t('distill.tagPath')}:\n \n \n {tagPath || parentTag.label}\n \n \n )}\n\n \n \n {t('distill.parentTag')}:\n \n\n setParentTagName(e.target.value)}\n placeholder={t('distill.parentTagPlaceholder')}\n disabled={loading || !parentTag}\n // 如果是顶级标签,设置为只读\n InputProps={{\n readOnly: !parentTag\n }}\n // 显示适当的帮助文本\n helperText={\n !parentTag\n ? t('distill.rootTopicHelperText', { defaultValue: '使用项目名称作为顶级主题' })\n : t('distill.parentTagHelp')\n }\n />\n \n\n \n \n {t('distill.tagCount')}:\n \n \n \n\n {generatedTags.length > 0 && (\n \n \n {t('distill.generatedTags')}:\n \n \n \n {generatedTags.map((tag, index) => (\n \n ))}\n \n \n \n )}\n \n\n \n \n {generatedTags.length > 0 ? (\n \n ) : (\n }\n >\n {loading ? t('common.generating') : t('distill.generateTags')}\n \n )}\n \n \n );\n}\n"], ["/easy-dataset/components/home/MigrationDialog.js", "'use client';\n\nimport { useState } from 'react';\nimport {\n Dialog,\n DialogTitle,\n DialogContent,\n DialogActions,\n Button,\n Box,\n Typography,\n CircularProgress,\n List,\n ListItem,\n ListItemText,\n ListItemSecondaryAction,\n IconButton,\n Alert,\n Paper,\n useTheme,\n Tooltip\n} from '@mui/material';\nimport WarningAmberIcon from '@mui/icons-material/WarningAmber';\nimport FolderOpenIcon from '@mui/icons-material/FolderOpen';\nimport DeleteIcon from '@mui/icons-material/Delete';\nimport { useTranslation } from 'react-i18next';\n\n/**\n * 项目迁移对话框组件\n * @param {Object} props - 组件属性\n * @param {boolean} props.open - 对话框是否打开\n * @param {Function} props.onClose - 关闭对话框的回调函数\n * @param {Array} props.projectIds - 需要迁移的项目ID列表\n */\nexport default function MigrationDialog({ open, onClose, projectIds = [] }) {\n const { t } = useTranslation();\n const theme = useTheme();\n const [migrating, setMigrating] = useState(false);\n const [success, setSuccess] = useState(false);\n const [error, setError] = useState(null);\n const [migratedCount, setMigratedCount] = useState(0);\n const [taskId, setTaskId] = useState(null);\n const [progress, setProgress] = useState(0);\n const [statusText, setStatusText] = useState('');\n const [processingIds, setProcessingIds] = useState([]);\n\n // 打开项目目录\n const handleOpenDirectory = async projectId => {\n try {\n setProcessingIds(prev => [...prev, projectId]);\n\n const response = await fetch('/api/projects/open-directory', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({ projectId })\n });\n\n if (!response.ok) {\n const data = await response.json();\n throw new Error(data.error || t('migration.openDirectoryFailed'));\n }\n\n // 成功打开目录,不需要特别处理\n } catch (err) {\n console.error('打开目录错误:', err);\n setError(err.message);\n } finally {\n setProcessingIds(prev => prev.filter(id => id !== projectId));\n }\n };\n\n // 删除项目目录\n const handleDeleteDirectory = async projectId => {\n try {\n if (!window.confirm(t('migration.confirmDelete'))) {\n return;\n }\n\n setProcessingIds(prev => [...prev, projectId]);\n\n const response = await fetch('/api/projects/delete-directory', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({ projectId })\n });\n\n if (!response.ok) {\n const data = await response.json();\n throw new Error(data.error || t('migration.deleteDirectoryFailed'));\n }\n\n // 从列表中移除已删除的项目\n const updatedProjectIds = projectIds.filter(id => id !== projectId);\n // 这里我们不能直接修改 projectIds,因为它是从父组件传入的\n // 但我们可以通知用户界面刷新\n window.location.reload();\n } catch (err) {\n console.error('删除目录错误:', err);\n setError(err.message);\n } finally {\n setProcessingIds(prev => prev.filter(id => id !== projectId));\n }\n };\n\n // 处理迁移操作\n const handleMigration = async () => {\n try {\n setMigrating(true);\n setError(null);\n setSuccess(false);\n setProgress(0);\n setStatusText(t('migration.starting'));\n\n // 调用异步迁移接口启动迁移任务\n const response = await fetch('/api/projects/migrate', {\n method: 'POST'\n });\n\n if (!response.ok) {\n throw new Error(t('migration.failed'));\n }\n\n const { success, taskId: newTaskId } = await response.json();\n\n if (!success || !newTaskId) {\n throw new Error(t('migration.startFailed'));\n }\n\n // 保存任务ID\n setTaskId(newTaskId);\n setStatusText(t('migration.processing'));\n\n // 开始轮询任务状态\n await pollMigrationStatus(newTaskId);\n } catch (err) {\n console.error('迁移错误:', err);\n setError(err.message);\n setMigrating(false);\n }\n };\n\n // 轮询迁移任务状态\n const pollMigrationStatus = async id => {\n try {\n // 定义轮询间隔(毫秒)\n const pollInterval = 1000;\n\n // 发送请求获取任务状态\n const response = await fetch(`/api/projects/migrate?taskId=${id}`);\n\n if (!response.ok) {\n throw new Error(t('migration.statusFailed'));\n }\n\n const { success, task } = await response.json();\n\n if (!success || !task) {\n throw new Error(t('migration.taskNotFound'));\n }\n\n // 更新进度\n setProgress(task.progress || 0);\n\n // 根据任务状态更新UI\n if (task.status === 'completed') {\n // 任务完成\n setMigratedCount(task.completed);\n setSuccess(true);\n setMigrating(false);\n setStatusText(t('migration.completed'));\n\n // 迁移成功后,延迟关闭对话框并刷新页面\n setTimeout(() => {\n onClose();\n window.location.reload();\n }, 2000);\n } else if (task.status === 'failed') {\n // 任务失败\n throw new Error(task.error || t('migration.failed'));\n } else {\n // 任务仍在进行中,继续轮询\n setTimeout(() => pollMigrationStatus(id), pollInterval);\n\n // 更新状态文本\n if (task.total > 0) {\n setStatusText(\n t('migration.progressStatus', {\n completed: task.completed || 0,\n total: task.total\n })\n );\n }\n }\n } catch (err) {\n console.error('获取迁移状态错误:', err);\n setError(err.message);\n setMigrating(false);\n }\n };\n\n return (\n \n \n \n {t('migration.title')}\n \n\n \n {success ? (\n \n {t('migration.success', { count: migratedCount })}\n \n ) : error ? (\n \n {error}\n \n ) : null}\n\n \n {t('migration.description')}\n \n\n {projectIds.length > 0 && (\n \n \n {t('migration.projectsList')}:\n \n \n \n {projectIds.map(id => (\n \n \n \n \n handleOpenDirectory(id)}\n disabled={processingIds.includes(id)}\n size=\"small\"\n >\n \n \n \n \n handleDeleteDirectory(id)}\n disabled={processingIds.includes(id)}\n size=\"small\"\n sx={{ ml: 1, color: 'error.main' }}\n >\n \n \n \n \n \n ))}\n \n \n \n )}\n\n {migrating && (\n \n 0 ? 'determinate' : 'indeterminate'} value={progress} />\n \n {statusText || t('migration.migrating')}\n \n {progress > 0 && (\n \n {progress}%\n \n )}\n \n )}\n \n\n \n \n \n \n \n );\n}\n"], ["/easy-dataset/components/distill/AutoDistillDialog.js", "'use client';\n\nimport { useState, useEffect } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport {\n Dialog,\n DialogTitle,\n DialogContent,\n DialogActions,\n TextField,\n Button,\n Typography,\n Box,\n Alert,\n Paper,\n Divider\n} from '@mui/material';\n\n/**\n * 全自动蒸馏数据集配置弹框\n * @param {Object} props\n * @param {boolean} props.open - 对话框是否打开\n * @param {Function} props.onClose - 关闭对话框的回调\n * @param {Function} props.onStart - 开始蒸馏任务的回调\n * @param {string} props.projectId - 项目ID\n * @param {Object} props.project - 项目信息\n * @param {Object} props.stats - 当前统计信息\n */\nexport default function AutoDistillDialog({ open, onClose, onStart, projectId, project, stats = {} }) {\n const { t } = useTranslation();\n\n // 表单状态\n const [topic, setTopic] = useState('');\n const [levels, setLevels] = useState(2);\n const [tagsPerLevel, setTagsPerLevel] = useState(10);\n const [questionsPerTag, setQuestionsPerTag] = useState(10);\n\n // 计算信息\n const [estimatedTags, setEstimatedTags] = useState(0); // 所有标签总数(包括根节点和中间节点)\n const [leafTags, setLeafTags] = useState(0); // 叶子节点数量(即最后一层标签数)\n const [estimatedQuestions, setEstimatedQuestions] = useState(0);\n const [newTags, setNewTags] = useState(0);\n const [newQuestions, setNewQuestions] = useState(0);\n const [error, setError] = useState('');\n\n // 初始化默认主题\n useEffect(() => {\n if (project && project.name) {\n setTopic(project.name);\n }\n }, [project]);\n\n // 计算预估标签和问题数量\n useEffect(() => {\n /*\n * 根据公式:总问题数 = \\left( \\prod_{i=1}^{n} L_i \\right) \\times Q\n * 当每层标签数量相同(L)时:总问题数 = L^n \\times Q\n */\n\n const leafTags = Math.pow(tagsPerLevel, levels);\n\n // 总问题数 = 叶子节点数 * 每个节点的问题数\n const totalQuestions = leafTags * questionsPerTag;\n\n let totalTags;\n if (tagsPerLevel === 1) {\n // 如果每层只有1个标签,总数就是 levels+1\n totalTags = levels + 1;\n } else {\n // 使用等比数列求和公式\n totalTags = (1 - Math.pow(tagsPerLevel, levels + 1)) / (1 - tagsPerLevel);\n }\n\n setLeafTags(leafTags);\n setEstimatedTags(leafTags); // 改为只显示叶子节点数量,而非所有节点数量\n setEstimatedQuestions(totalQuestions);\n\n // 计算新增标签和问题数量\n const currentTags = stats.tagsCount || 0;\n const currentQuestions = stats.questionsCount || 0;\n\n // 只考虑最后一层的标签数量\n setNewTags(Math.max(0, leafTags - currentTags));\n setNewQuestions(Math.max(0, totalQuestions - currentQuestions));\n\n // 验证是否可以执行任务\n if (leafTags <= currentTags && totalQuestions <= currentQuestions) {\n setError(t('distill.autoDistillInsufficientError'));\n } else {\n setError('');\n }\n }, [levels, tagsPerLevel, questionsPerTag, stats, t]);\n\n // 处理开始任务\n const handleStart = () => {\n if (error) return;\n\n onStart({\n topic,\n levels,\n tagsPerLevel,\n questionsPerTag,\n estimatedTags,\n estimatedQuestions\n });\n };\n\n return (\n \n {t('distill.autoDistillTitle')}\n \n \n {/* 左侧:输入区域 */}\n \n setTopic(e.target.value)}\n fullWidth\n margin=\"normal\"\n required\n disabled\n helperText={t('distill.rootTopicHelperText')}\n />\n\n \n {t('distill.tagLevels')}\n {\n const value = Math.min(5, Math.max(1, Number(e.target.value)));\n setLevels(value);\n }}\n helperText={t('distill.tagLevelsHelper', { max: 5 })}\n />\n \n\n \n {t('distill.tagsPerLevel')}\n {\n const value = Math.min(50, Math.max(1, Number(e.target.value)));\n setTagsPerLevel(value);\n }}\n helperText={t('distill.tagsPerLevelHelper', { max: 50 })}\n />\n \n\n \n {t('distill.questionsPerTag')}\n {\n const value = Math.min(50, Math.max(1, Number(e.target.value)));\n setQuestionsPerTag(value);\n }}\n helperText={t('distill.questionsPerTagHelper', { max: 50 })}\n />\n \n \n\n {/* 右侧:预估信息区域 */}\n \n \n \n {t('distill.estimationInfo')}\n \n\n \n \n \n {t('distill.estimatedTags')}:\n \n {estimatedTags}\n \n \n\n \n {t('distill.estimatedQuestions')}:\n \n {estimatedQuestions}\n \n \n\n \n\n \n {t('distill.currentTags')}:\n \n {stats.tagsCount || 0}\n \n \n\n \n {t('distill.currentQuestions')}:\n \n {stats.questionsCount || 0}\n \n \n \n\n \n \n \n {t('distill.newTags')}:\n \n \n {newTags}\n \n \n\n \n \n {t('distill.newQuestions')}:\n \n \n {newQuestions}\n \n \n \n \n \n\n {error && (\n \n {error}\n \n )}\n \n \n \n \n \n \n \n \n );\n}\n"], ["/easy-dataset/components/text-split/DomainAnalysis.js", "'use client';\n\nimport { useEffect, useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport {\n Box,\n Paper,\n Typography,\n Divider,\n CircularProgress,\n Tabs,\n Tab,\n List,\n ListItem,\n ListItemText,\n Collapse,\n IconButton,\n TextField,\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogContentText,\n DialogTitle,\n Tooltip,\n Menu,\n MenuItem\n} from '@mui/material';\nimport { useTheme } from '@mui/material/styles';\nimport TabPanel from './components/TabPanel';\nimport ReactMarkdown from 'react-markdown';\nimport ExpandLess from '@mui/icons-material/ExpandLess';\nimport ExpandMore from '@mui/icons-material/ExpandMore';\nimport AddIcon from '@mui/icons-material/Add';\nimport EditIcon from '@mui/icons-material/Edit';\nimport DeleteIcon from '@mui/icons-material/Delete';\nimport MoreVertIcon from '@mui/icons-material/MoreVert';\nimport axios from 'axios';\nimport { toast } from 'sonner';\n\n/**\n * 领域分析组件\n * @param {Object} props\n * @param {string} props.projectId - 项目ID\n * @param {Array} props.toc - 目录结构数组\n * @param {Array} props.tags - 标签树数组\n * @param {boolean} props.loading - 是否加载中\n * @param {Function} props.onTagsUpdate - 标签更新回调\n */\n\n// 领域树节点组件\nfunction TreeNode({ node, level = 0, onEdit, onDelete, onAddChild }) {\n const [open, setOpen] = useState(true);\n const theme = useTheme();\n const hasChildren = node.child && node.child.length > 0;\n const [anchorEl, setAnchorEl] = useState(null);\n const menuOpen = Boolean(anchorEl);\n const { t } = useTranslation();\n\n const handleClick = () => {\n if (hasChildren) {\n setOpen(!open);\n }\n };\n\n const handleMenuOpen = event => {\n event.stopPropagation();\n setAnchorEl(event.currentTarget);\n };\n\n const handleMenuClose = event => {\n if (event) event.stopPropagation();\n setAnchorEl(null);\n };\n\n const handleEdit = event => {\n event.stopPropagation();\n onEdit(node);\n handleMenuClose();\n };\n\n const handleDelete = event => {\n event.stopPropagation();\n onDelete(node);\n handleMenuClose();\n };\n\n const handleAddChild = event => {\n event.stopPropagation();\n onAddChild(node);\n handleMenuClose();\n };\n\n return (\n <>\n \n \n \n \n \n \n {hasChildren && (open ? : )}\n \n\n e.stopPropagation()}>\n \n \n {t('textSplit.editTag')}\n \n \n \n {t('textSplit.deleteTag')}\n \n {level === 0 && (\n \n \n {t('textSplit.addTag')}\n \n )}\n \n \n\n {hasChildren && (\n \n \n {node.child.map((childNode, index) => (\n \n ))}\n \n \n )}\n \n );\n}\n\n// 领域树组件\nfunction DomainTree({ tags, onEdit, onDelete, onAddChild }) {\n return (\n \n {tags.map((node, index) => (\n \n ))}\n \n );\n}\n\nexport default function DomainAnalysis({ projectId, toc = '', loading = false }) {\n const theme = useTheme();\n const { t } = useTranslation();\n const [activeTab, setActiveTab] = useState(0);\n const [dialogOpen, setDialogOpen] = useState(false);\n const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);\n const [currentNode, setCurrentNode] = useState(null);\n const [parentNode, setParentNode] = useState('');\n const [dialogMode, setDialogMode] = useState('add');\n const [labelValue, setLabelValue] = useState({});\n const [saving, setSaving] = useState(false);\n const [tags, setTags] = useState([]);\n const [snackbar, setSnackbar] = useState({\n open: false,\n message: '',\n severity: 'success'\n });\n\n const handleCloseSnackbar = () => {\n setSnackbar(prev => ({ ...prev, open: false }));\n };\n\n useEffect(() => {\n getTags();\n }, []);\n const getTags = async () => {\n const response = await axios.get(`/api/projects/${projectId}/tags`);\n setTags(response.data.tags);\n };\n // 处理标签切换\n const handleTabChange = (event, newValue) => {\n setActiveTab(newValue);\n };\n\n // 打开添加标签对话框\n const handleAddTag = () => {\n setDialogMode('add');\n setCurrentNode(null);\n setParentNode(null);\n setLabelValue({});\n setDialogOpen(true);\n };\n\n // 打开编辑标签对话框\n const handleEditTag = node => {\n setDialogMode('edit');\n setCurrentNode({ id: node.id, label: node.label });\n setLabelValue({ id: node.id, label: node.label });\n setDialogOpen(true);\n };\n\n // 打开添加子标签对话框\n const handleAddChildTag = parentNode => {\n setDialogMode('addChild');\n setParentNode(parentNode.label);\n setLabelValue({ parentId: parentNode.id });\n setDialogOpen(true);\n };\n\n // 打开删除标签对话框\n const handleDeleteTag = node => {\n setCurrentNode(node);\n setDeleteDialogOpen(true);\n };\n\n // 关闭对话框\n const handleCloseDialog = () => {\n setDialogOpen(false);\n setDeleteDialogOpen(false);\n };\n\n // 查找并更新节点\n const findAndUpdateNode = (nodes, targetNode, newLabel) => {\n return nodes.map(node => {\n if (node === targetNode) {\n return { ...node, label: newLabel };\n }\n if (node.child && node.child.length > 0) {\n return { ...node, child: findAndUpdateNode(node.child, targetNode, newLabel) };\n }\n return node;\n });\n };\n\n // 查找并删除节点\n const findAndDeleteNode = (nodes, targetNode) => {\n return nodes\n .filter(node => node !== targetNode)\n .map(node => {\n if (node.child && node.child.length > 0) {\n return { ...node, child: findAndDeleteNode(node.child, targetNode) };\n }\n return node;\n });\n };\n\n // 查找并添加子节点\n const findAndAddChildNode = (nodes, parentNode, childLabel) => {\n return nodes.map(node => {\n if (node === parentNode) {\n const childArray = node.child || [];\n return {\n ...node,\n child: [...childArray, { label: childLabel, child: [] }]\n };\n }\n if (node.child && node.child.length > 0) {\n return { ...node, child: findAndAddChildNode(node.child, parentNode, childLabel) };\n }\n return node;\n });\n };\n\n // 保存标签更改\n const saveTagChanges = async updatedTags => {\n console.log('保存标签更改:', updatedTags);\n setSaving(true);\n try {\n const response = await fetch(`/api/projects/${projectId}/tags`, {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({ tags: updatedTags })\n });\n\n if (!response.ok) {\n const errorData = await response.json();\n throw new Error(errorData.error || t('domain.errors.saveFailed'));\n }\n getTags();\n setSnackbar({\n open: true,\n message: t('domain.messages.updateSuccess'),\n severity: 'success'\n });\n } catch (error) {\n console.error('保存标签失败:', error);\n setSnackbar({\n open: true,\n message: error.message || '保存标签失败',\n severity: 'error'\n });\n } finally {\n setSaving(false);\n }\n };\n\n // 提交表单\n const handleSubmit = async () => {\n if (!labelValue.label.trim()) {\n setSnackbar({\n open: true,\n message: '标签名称不能为空',\n severity: 'error'\n });\n return;\n }\n\n await saveTagChanges(labelValue);\n handleCloseDialog();\n };\n\n const handleConfirmDelete = async () => {\n if (!currentNode) return;\n\n const res = await axios.delete(`/api/projects/${projectId}/tags?id=${currentNode.id}`);\n if (res.status === 200) {\n toast.success('删除成功');\n getTags();\n }\n\n setDeleteDialogOpen(false);\n };\n\n if (loading) {\n return (\n \n \n \n );\n }\n\n if (toc.length === 0) {\n return (\n \n \n {t('domain.noToc')}\n \n \n );\n }\n\n return (\n \n \n \n \n \n \n\n \n \n \n \n {t('domain.tabs.tree')}\n \n \n \n \n \n \n {tags && tags.length > 0 ? (\n \n ) : (\n \n \n {t('domain.noTags')}\n \n }\n onClick={handleAddTag}\n sx={{ mt: 1 }}\n >\n {t('domain.addFirstTag')}\n \n \n )}\n \n \n \n \n \n \n {t('domain.docStructure')}\n \n \n \n (\n \n {children}\n \n )\n }}\n >\n {toc}\n \n \n \n \n \n \n\n {/* 添加/编辑标签对话框 */}\n \n \n {dialogMode === 'add'\n ? t('domain.dialog.addTitle')\n : dialogMode === 'edit'\n ? t('domain.dialog.editTitle')\n : t('domain.dialog.addChildTitle')}\n \n \n \n {dialogMode === 'add'\n ? t('domain.dialog.inputRoot')\n : dialogMode === 'edit'\n ? t('domain.dialog.inputEdit')\n : t('domain.dialog.inputChild', { label: parentNode })}\n \n setLabelValue({ ...labelValue, label: e.target.value })}\n />\n \n \n \n \n \n \n\n {/* 删除确认对话框 */}\n \n {t('common.confirmDelete')}\n \n \n {t('domain.dialog.deleteConfirm', { label: currentNode?.label })}\n {currentNode?.child && currentNode.child.length > 0 && t('domain.dialog.deleteWarning')}\n \n \n \n \n \n \n \n \n );\n}\n"], ["/easy-dataset/components/text-split/MarkdownViewDialog.js", "'use client';\n\nimport React, { useState, useEffect, useRef } from 'react';\nimport {\n Box,\n Button,\n Dialog,\n DialogTitle,\n DialogContent,\n DialogActions,\n CircularProgress,\n Typography,\n Divider,\n Chip,\n IconButton,\n Switch,\n FormControlLabel,\n Tooltip,\n Alert,\n DialogContentText\n} from '@mui/material';\nimport DeleteIcon from '@mui/icons-material/Delete';\nimport AddIcon from '@mui/icons-material/Add';\nimport SaveIcon from '@mui/icons-material/Save';\nimport ReactMarkdown from 'react-markdown';\nimport { useTranslation } from 'react-i18next';\n\nexport default function MarkdownViewDialog({ open, text, onClose, projectId, onSaveSuccess }) {\n const { t } = useTranslation();\n const [customSplitMode, setCustomSplitMode] = useState(false);\n const [splitPoints, setSplitPoints] = useState([]);\n const [selectedText, setSelectedText] = useState('');\n const [savedMessage, setSavedMessage] = useState('');\n const [confirmDialogOpen, setConfirmDialogOpen] = useState(false);\n const [saving, setSaving] = useState(false);\n const [error, setError] = useState('');\n const contentRef = useRef(null);\n const [chunksPreview, setChunksPreview] = useState([]);\n\n // 根据分块点计算每个块的字数\n const calculateChunksPreview = points => {\n if (!text || !text.content) return [];\n\n const content = text.content;\n const sortedPoints = [...points].sort((a, b) => a.position - b.position);\n\n const chunks = [];\n let startPos = 0;\n\n // 计算每个分块\n for (let i = 0; i < sortedPoints.length; i++) {\n const endPos = sortedPoints[i].position;\n const chunkContent = content.substring(startPos, endPos);\n\n if (chunkContent.trim().length > 0) {\n chunks.push({\n index: i + 1,\n length: chunkContent.length,\n preview: chunkContent.substring(0, 20) + (chunkContent.length > 20 ? '...' : '')\n });\n }\n\n startPos = endPos;\n }\n\n // 添加最后一个分块\n const lastChunkContent = content.substring(startPos);\n if (lastChunkContent.trim().length > 0) {\n chunks.push({\n index: chunks.length + 1,\n length: lastChunkContent.length,\n preview: lastChunkContent.substring(0, 20) + (lastChunkContent.length > 20 ? '...' : '')\n });\n }\n\n return chunks;\n };\n\n // 重置组件状态\n useEffect(() => {\n if (!open) {\n setSplitPoints([]);\n setCustomSplitMode(false);\n setSelectedText('');\n setSavedMessage('');\n }\n }, [open]);\n\n // 当分块点变化时更新预览\n useEffect(() => {\n if (splitPoints.length > 0 && text?.content) {\n const preview = calculateChunksPreview(splitPoints);\n setChunksPreview(preview);\n } else {\n setChunksPreview([]);\n }\n }, [splitPoints, text?.content]);\n\n // 处理用户选择文本事件\n const handleTextSelection = () => {\n if (!customSplitMode) return;\n\n const selection = window.getSelection();\n if (!selection.toString().trim()) return;\n\n // 获取选择的文本内容和位置\n const selectedContent = selection.toString();\n\n // 计算选择位置在文档中的偏移量\n const range = selection.getRangeAt(0);\n const preCaretRange = range.cloneRange();\n preCaretRange.selectNodeContents(contentRef.current);\n preCaretRange.setEnd(range.endContainer, range.endOffset);\n const position = preCaretRange.toString().length;\n\n // 添加到分割点列表\n const newPoint = {\n id: Date.now(),\n position,\n preview: selectedContent.substring(0, 40) + (selectedContent.length > 40 ? '...' : '')\n };\n\n setSplitPoints(prev => [...prev, newPoint].sort((a, b) => a.position - b.position));\n setSelectedText('');\n };\n\n // 删除分割点\n const handleDeletePoint = id => {\n setSplitPoints(prev => prev.filter(point => point.id !== id));\n };\n\n // 弹出确认对话框\n const handleConfirmSave = () => {\n setConfirmDialogOpen(true);\n };\n\n // 取消保存\n const handleCancelSave = () => {\n setConfirmDialogOpen(false);\n };\n\n // 确认并执行保存\n const handleSavePoints = async () => {\n // 输出调试信息\n console.log('保存分块点时的数据:', {\n projectId,\n text: text\n ? {\n fileId: text.fileId,\n fileName: text.fileName,\n contentLength: text.content ? text.content.length : 0\n }\n : null,\n splitPointsCount: splitPoints.length\n });\n\n if (!text) {\n setError(t('textSplit.missingRequiredData') + ': text 为空');\n return;\n }\n\n if (!text.fileId) {\n setError(t('textSplit.missingRequiredData') + ': fileId 不存在');\n return;\n }\n\n if (!text.fileName) {\n setError(t('textSplit.missingRequiredData') + ': fileName 不存在');\n return;\n }\n\n if (!text.content) {\n setError(t('textSplit.missingRequiredData') + ': content 不存在');\n return;\n }\n\n if (!projectId) {\n setError(t('textSplit.missingRequiredData') + ': projectId 不存在');\n return;\n }\n\n setConfirmDialogOpen(false);\n setSaving(true);\n setError('');\n\n try {\n // 准备要发送的数据\n const customSplitData = {\n fileId: text.fileId,\n fileName: text.fileName,\n content: text.content,\n splitPoints: splitPoints.map(point => ({\n position: point.position,\n preview: point.preview\n }))\n };\n\n // 发送请求到待创建的API接口\n const response = await fetch(`/api/projects/${projectId}/custom-split`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(customSplitData)\n });\n\n if (!response.ok) {\n const errorData = await response.json();\n throw new Error(errorData.error || t('textSplit.customSplitFailed'));\n }\n\n // 保存成功\n setSavedMessage(t('textSplit.customSplitSuccess'));\n\n // 短暂显示成功消息后关闭对话框并刷新列表\n setTimeout(() => {\n setSavedMessage('');\n\n // 关闭对话框\n onClose();\n\n // 调用父组件的刷新方法(如果提供了)\n if (typeof onSaveSuccess === 'function') {\n onSaveSuccess();\n }\n }, 1500);\n } catch (err) {\n console.error('保存自定义分块出错:', err);\n setError(err.message || t('textSplit.customSplitFailed'));\n } finally {\n setSaving(false);\n }\n };\n\n return (\n \n \n {text ? text.fileName : ''}\n setCustomSplitMode(e.target.checked)} color=\"primary\" />\n }\n label={t('textSplit.customSplitMode')}\n sx={{ ml: 2 }}\n />\n \n\n {customSplitMode && (\n \n \n {t('textSplit.customSplitInstructions')}\n \n\n {/* 分割点列表 */}\n {splitPoints.length > 0 && (\n \n \n {t('textSplit.splitPointsList')} ({splitPoints.length}):\n \n \n {splitPoints.map((point, index) => (\n handleDeletePoint(point.id)}\n deleteIcon={}\n color=\"primary\"\n variant=\"outlined\"\n />\n ))}\n \n\n {/* 文本块字数预览 */}\n {chunksPreview.length > 0 && (\n \n \n {t('textSplit.chunksPreview')}\n \n \n {chunksPreview.map(chunk => (\n \n ))}\n \n \n )}\n \n )}\n\n {/* 保存按钮 */}\n \n }\n disabled={splitPoints.length === 0 || saving}\n onClick={handleConfirmSave}\n size=\"small\"\n >\n {saving ? t('common.saving') : t('textSplit.saveSplitPoints')}\n \n \n\n {/* 提示消息 */}\n {savedMessage && (\n \n {savedMessage}\n \n )}\n\n {error && (\n \n {error}\n \n )}\n \n )}\n\n \n\n \n {text ? (\n \n {/* 渲染带有分割点标记的内容 */}\n {customSplitMode && splitPoints.length > 0 ? (\n \n
\n                  {text.content.split('').map((char, index) => {\n                    const isSplitPoint = splitPoints.some(point => point.position === index);\n                    const splitPointIndex = splitPoints.findIndex(point => point.position === index);\n\n                    if (isSplitPoint) {\n                      return (\n                        \n                          \n                            \n                              {splitPointIndex + 1}\n                            \n                          \n                          {char}\n                        \n                      );\n                    }\n                    return char;\n                  })}\n                
\n
\n ) : (\n \n {text.content}\n \n )}\n \n ) : (\n \n \n \n )}\n
\n\n \n \n \n\n {/* 确认对话框 */}\n \n {t('textSplit.confirmCustomSplitTitle')}\n \n \n {t('textSplit.confirmCustomSplitMessage')}\n \n \n \n \n \n \n
\n \n );\n}\n"], ["/easy-dataset/components/text-split/ChunkDeleteDialog.js", "'use client';\n\nimport { Dialog, DialogTitle, DialogContent, DialogContentText, DialogActions, Button } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\n\nexport default function ChunkDeleteDialog({ open, onClose, onConfirm }) {\n const { t } = useTranslation();\n return (\n \n {t('common.confirmDelete')}?\n \n {t('common.confirmDelete')}?\n \n \n \n \n \n \n );\n}\n"], ["/easy-dataset/components/text-split/components/DeleteConfirmDialog.js", "'use client';\n\nimport {\n Dialog,\n DialogTitle,\n DialogContent,\n DialogContentText,\n DialogActions,\n Button,\n Typography,\n Box,\n Alert\n} from '@mui/material';\nimport { useTranslation } from 'react-i18next';\n\nexport default function DeleteConfirmDialog({ open, fileName, onClose, onConfirm }) {\n const { t } = useTranslation();\n return (\n \n \n {t('common.confirmDelete')}「{fileName}」?\n \n \n {t('common.confirmDeleteDescription')}\n\n \n \n {t('textSplit.deleteFileWarning')}\n \n \n \n • {t('textSplit.deleteFileWarningChunks')}\n \n \n • {t('textSplit.deleteFileWarningQuestions')}\n \n \n • {t('textSplit.deleteFileWarningDatasets')}\n \n \n \n \n \n \n \n \n \n );\n}\n"], ["/easy-dataset/components/home/ProjectList.js", "'use client';\n\nimport {\n Grid,\n Paper,\n Button,\n Dialog,\n DialogTitle,\n DialogContent,\n DialogContentText,\n DialogActions,\n Typography\n} from '@mui/material';\nimport AddCircleOutlineIcon from '@mui/icons-material/AddCircleOutline';\nimport { useTranslation } from 'react-i18next';\nimport { useState } from 'react';\nimport ProjectCard from './ProjectCard';\n\nexport default function ProjectList({ projects, onCreateProject }) {\n const { t } = useTranslation();\n const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);\n const [projectToDelete, setProjectToDelete] = useState(null);\n const [loading, setLoading] = useState(false);\n // 打开删除确认对话框\n const handleOpenDeleteDialog = (event, project) => {\n setProjectToDelete(project);\n setDeleteDialogOpen(true);\n };\n\n // 关闭删除确认对话框\n const handleCloseDeleteDialog = () => {\n setDeleteDialogOpen(false);\n setProjectToDelete(null);\n };\n\n // 删除项目\n const handleDeleteProject = async () => {\n if (!projectToDelete) return;\n\n try {\n setLoading(true);\n const response = await fetch(`/api/projects/${projectToDelete.id}`, {\n method: 'DELETE'\n });\n\n if (!response.ok) {\n const errorData = await response.json();\n throw new Error(errorData.error || t('projects.deleteFailed'));\n }\n\n // 刷新页面以更新项目列表\n window.location.reload();\n } catch (error) {\n console.error('删除项目失败:', error);\n alert(error.message || t('projects.deleteFailed'));\n } finally {\n setLoading(false);\n handleCloseDeleteDialog();\n }\n };\n\n return (\n <>\n \n {projects.length === 0 ? (\n \n \n \n {t('projects.noProjects')}\n \n \n \n \n ) : (\n projects.map(project => (\n \n \n \n ))\n )}\n \n\n {/* 删除确认对话框 */}\n \n {t('projects.deleteConfirmTitle')}\n \n \n {projectToDelete && (\n <>\n {t('projects.deleteConfirm')}\n
\n \n {projectToDelete.name}\n \n \n )}\n
\n
\n \n \n \n \n \n \n );\n}\n"], ["/easy-dataset/components/distill/AutoDistillProgress.js", "'use client';\n\nimport { useState, useEffect, useRef } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport {\n Dialog,\n DialogTitle,\n DialogContent,\n Box,\n Typography,\n LinearProgress,\n Paper,\n Divider,\n IconButton,\n Button\n} from '@mui/material';\nimport CloseIcon from '@mui/icons-material/Close';\n\n/**\n * 全自动蒸馏进度组件\n * @param {Object} props\n * @param {boolean} props.open - 对话框是否打开\n * @param {Function} props.onClose - 关闭对话框的回调\n * @param {Object} props.progress - 进度信息\n */\nexport default function AutoDistillProgress({ open, onClose, progress = {} }) {\n const { t } = useTranslation();\n const logContainerRef = useRef(null);\n\n // 自动滚动到底部\n useEffect(() => {\n if (logContainerRef.current) {\n logContainerRef.current.scrollTop = logContainerRef.current.scrollHeight;\n }\n }, [progress.logs]);\n\n const getStageText = () => {\n const { stage } = progress;\n switch (stage) {\n case 'level1':\n return t('distill.stageBuildingLevel1');\n case 'level2':\n return t('distill.stageBuildingLevel2');\n case 'level3':\n return t('distill.stageBuildingLevel3');\n case 'level4':\n return t('distill.stageBuildingLevel4');\n case 'level5':\n return t('distill.stageBuildingLevel5');\n case 'questions':\n return t('distill.stageBuildingQuestions');\n case 'datasets':\n return t('distill.stageBuildingDatasets');\n case 'completed':\n return t('distill.stageCompleted');\n default:\n return t('distill.stageInitializing');\n }\n };\n\n const getOverallProgress = () => {\n const { tagsBuilt, tagsTotal, questionsBuilt, questionsTotal, datasetsBuilt, datasetsTotal } = progress;\n\n // 整体进度按比例计算:标签构建占30%,问题生成占35%,数据集生成占35%\n let tagProgress = tagsTotal ? (tagsBuilt / tagsTotal) * 30 : 0;\n let questionProgress = questionsTotal ? (questionsBuilt / questionsTotal) * 35 : 0;\n let datasetProgress = datasetsTotal ? (datasetsBuilt / datasetsTotal) * 35 : 0;\n\n return Math.min(100, Math.round(tagProgress + questionProgress + datasetProgress));\n };\n\n return (\n \n \n \n {t('distill.autoDistillProgress')}\n {(progress.stage === 'completed' || !progress.stage) && (\n \n \n \n )}\n \n \n \n \n {/* 整体进度 */}\n \n \n {t('distill.overallProgress')}\n \n\n \n \n \n \n {getOverallProgress()}%\n \n \n \n\n \n \n \n {t('distill.tagsProgress')}\n \n \n {progress.tagsBuilt || 0} / {progress.tagsTotal || 0}\n \n \n\n \n \n {t('distill.questionsProgress')}\n \n \n {progress.questionsBuilt || 0} / {progress.questionsTotal || 0}\n \n \n\n \n \n {t('distill.datasetsProgress')}\n \n \n {progress.datasetsBuilt || 0} / {progress.datasetsTotal || 0}\n \n \n \n \n\n {/* 当前阶段 */}\n \n \n {t('distill.currentStage')}\n \n\n \n {getStageText()}\n \n \n\n {/* 实时日志 */}\n \n \n {t('distill.realTimeLogs')}\n \n\n \n {progress.logs?.length > 0 ? (\n progress.logs.map((log, index) => {\n // 检测成功日志,显示为绿色 Successfully\n let color = 'inherit';\n if (log.includes('成功') || log.includes('完成') || log.includes('Successfully')) {\n color = '#4caf50';\n }\n if (log.includes('失败') || log.toLowerCase().includes('error')) {\n color = '#f44336';\n }\n return (\n \n {log}\n \n );\n })\n ) : (\n \n {t('distill.waitingForLogs')}\n \n )}\n \n \n \n \n \n );\n}\n"], ["/easy-dataset/components/text-split/ChunkList.js", "'use client';\n\nimport { useState } from 'react';\nimport { Box, Paper, Typography, CircularProgress, Pagination, Grid } from '@mui/material';\nimport ChunkListHeader from './ChunkListHeader';\nimport ChunkCard from './ChunkCard';\nimport ChunkViewDialog from './ChunkViewDialog';\nimport ChunkDeleteDialog from './ChunkDeleteDialog';\nimport BatchEditChunksDialog from './BatchEditChunkDialog';\nimport { useTheme } from '@mui/material/styles';\nimport { useTranslation } from 'react-i18next';\n\n/**\n * Chunk list component\n * @param {Object} props\n * @param {string} props.projectId - Project ID\n * @param {Array} props.chunks - Chunk array\n * @param {Function} props.onDelete - Delete callback\n * @param {Function} props.onEdit - Edit callback\n * @param {Function} props.onGenerateQuestions - Generate questions callback\n * @param {string} props.questionFilter - Question filter\n * @param {Function} props.onQuestionFilterChange - Question filter change callback\n * @param {Object} props.selectedModel - 选中的模型信息\n */\nexport default function ChunkList({\n projectId,\n chunks = [],\n onDelete,\n onEdit,\n onGenerateQuestions,\n loading = false,\n questionFilter,\n setQuestionFilter,\n selectedModel,\n onChunksUpdate\n}) {\n const theme = useTheme();\n const [page, setPage] = useState(1);\n const [selectedChunks, setSelectedChunks] = useState([]);\n const [viewChunk, setViewChunk] = useState(null);\n const [viewDialogOpen, setViewDialogOpen] = useState(false);\n const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);\n const [chunkToDelete, setChunkToDelete] = useState(null);\n const [batchEditDialogOpen, setBatchEditDialogOpen] = useState(false);\n const [batchEditLoading, setBatchEditLoading] = useState(false);\n\n // 对文本块进行排序,先按文件ID排序,再按part-后面的数字排序\n const sortedChunks = [...chunks].sort((a, b) => {\n // 先按fileId排序\n if (a.fileId !== b.fileId) {\n return a.fileId.localeCompare(b.fileId);\n }\n\n // 同一文件内,再按part-后面的数字排序\n const getPartNumber = name => {\n const match = name.match(/part-(\\d+)/);\n return match ? parseInt(match[1], 10) : 0;\n };\n\n const numA = getPartNumber(a.name);\n const numB = getPartNumber(b.name);\n\n return numA - numB;\n });\n\n const itemsPerPage = 5;\n const startIndex = (page - 1) * itemsPerPage;\n const endIndex = startIndex + itemsPerPage;\n const displayedChunks = sortedChunks.slice(startIndex, endIndex);\n const totalPages = Math.ceil(sortedChunks.length / itemsPerPage);\n const { t } = useTranslation();\n\n const handlePageChange = (event, value) => {\n setPage(value);\n };\n\n const handleViewChunk = async chunkId => {\n try {\n const response = await fetch(`/api/projects/${projectId}/chunks/${chunkId}`);\n if (!response.ok) {\n throw new Error(t('textSplit.fetchChunksFailed'));\n }\n\n const data = await response.json();\n setViewChunk(data);\n setViewDialogOpen(true);\n } catch (error) {\n console.error(t('textSplit.fetchChunksError'), error);\n }\n };\n\n const handleCloseViewDialog = () => {\n setViewDialogOpen(false);\n };\n\n const handleOpenDeleteDialog = chunkId => {\n setChunkToDelete(chunkId);\n setDeleteDialogOpen(true);\n };\n\n const handleCloseDeleteDialog = () => {\n setDeleteDialogOpen(false);\n setChunkToDelete(null);\n };\n\n const handleConfirmDelete = () => {\n if (chunkToDelete && onDelete) {\n onDelete(chunkToDelete);\n }\n handleCloseDeleteDialog();\n };\n\n // 处理编辑文本块\n const handleEditChunk = async (chunkId, newContent) => {\n if (onEdit) {\n onEdit(chunkId, newContent);\n onChunksUpdate();\n }\n };\n\n // 处理选择文本块\n const handleSelectChunk = chunkId => {\n setSelectedChunks(prev => {\n if (prev.includes(chunkId)) {\n return prev.filter(id => id !== chunkId);\n } else {\n return [...prev, chunkId];\n }\n });\n };\n\n const handleSelectAll = () => {\n if (selectedChunks.length === chunks.length) {\n setSelectedChunks([]);\n } else {\n setSelectedChunks(chunks.map(chunk => chunk.id));\n }\n };\n\n const handleBatchGenerateQuestions = () => {\n if (onGenerateQuestions && selectedChunks.length > 0) {\n onGenerateQuestions(selectedChunks);\n }\n };\n\n const handleBatchEdit = async editData => {\n try {\n setBatchEditLoading(true);\n\n // 调用批量编辑API\n const response = await fetch(`/api/projects/${projectId}/chunks/batch-edit`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n position: editData.position,\n content: editData.content,\n chunkIds: editData.chunkIds\n })\n });\n\n if (!response.ok) {\n throw new Error('批量编辑失败');\n }\n\n const result = await response.json();\n\n if (result.success) {\n // 编辑成功后,刷新文本块数据\n if (onChunksUpdate) {\n onChunksUpdate();\n }\n\n // 清空选中状态\n setSelectedChunks([]);\n\n // 关闭对话框\n setBatchEditDialogOpen(false);\n\n // 显示成功消息\n console.log(`成功更新了 ${result.updatedCount} 个文本块`);\n } else {\n throw new Error(result.message || '批量编辑失败');\n }\n } catch (error) {\n console.error('批量编辑失败:', error);\n // 这里可以添加错误提示\n } finally {\n setBatchEditLoading(false);\n }\n };\n\n // 打开批量编辑对话框\n const handleOpenBatchEdit = () => {\n setBatchEditDialogOpen(true);\n };\n\n // 关闭批量编辑对话框\n const handleCloseBatchEdit = () => {\n setBatchEditDialogOpen(false);\n };\n\n if (loading) {\n return (\n \n \n \n );\n }\n\n return (\n \n setQuestionFilter(event.target.value)}\n chunks={chunks}\n selectedModel={selectedModel}\n />\n\n \n {displayedChunks.map(chunk => (\n \n handleSelectChunk(chunk.id)}\n onView={() => handleViewChunk(chunk.id)}\n onDelete={() => handleOpenDeleteDialog(chunk.id)}\n onEdit={handleEditChunk}\n onGenerateQuestions={() => onGenerateQuestions && onGenerateQuestions([chunk.id])}\n projectId={projectId}\n selectedModel={selectedModel}\n />\n \n ))}\n \n\n {chunks.length === 0 && (\n \n \n {t('textSplit.noChunks')}\n \n \n )}\n\n {totalPages > 1 && (\n \n \n \n )}\n\n {/* 文本块详情对话框 */}\n \n\n {/* 删除确认对话框 */}\n \n\n {/* 批量编辑对话框 */}\n \n \n );\n}\n"], ["/easy-dataset/components/distill/TagMenu.js", "'use client';\n\nimport { Menu, MenuItem, ListItemIcon, ListItemText } from '@mui/material';\nimport DeleteIcon from '@mui/icons-material/Delete';\nimport { useTranslation } from 'react-i18next';\n\n/**\n * 标签操作菜单组件\n * @param {Object} props\n * @param {HTMLElement} props.anchorEl - 菜单锚点元素\n * @param {boolean} props.open - 菜单是否打开\n * @param {Function} props.onClose - 关闭菜单的回调\n * @param {Function} props.onDelete - 删除操作的回调\n */\nexport default function TagMenu({ anchorEl, open, onClose, onDelete }) {\n const { t } = useTranslation();\n\n return (\n \n \n \n \n \n {t('common.delete')}\n \n \n );\n}\n"], ["/easy-dataset/components/text-split/components/DomainTreeActionDialog.js", "'use client';\n\nimport { useState } from 'react';\nimport {\n Dialog,\n DialogTitle,\n DialogContent,\n DialogActions,\n Button,\n Radio,\n RadioGroup,\n FormControlLabel,\n FormControl,\n Typography\n} from '@mui/material';\nimport { useTranslation } from 'react-i18next';\n\n/**\n * 领域树操作选择对话框\n * 提供三种选项:修订领域树、重建领域树、不更改领域树\n */\nexport default function DomainTreeActionDialog({ open, onClose, onConfirm, isFirstUpload, action }) {\n const { t } = useTranslation();\n const [value, setValue] = useState(isFirstUpload ? 'rebuild' : 'revise');\n\n // 处理选项变更\n const handleChange = event => {\n setValue(event.target.value);\n };\n\n // 确认选择\n const handleConfirm = () => {\n onConfirm(value);\n };\n\n // 获取对话框标题\n const getDialogTitle = () => {\n if (isFirstUpload) {\n return t('textSplit.domainTree.firstUploadTitle');\n }\n return action === 'upload' ? t('textSplit.domainTree.uploadTitle') : t('textSplit.domainTree.deleteTitle');\n };\n\n return (\n \n {getDialogTitle()}\n \n \n \n {!isFirstUpload && (\n }\n label={\n <>\n {t('textSplit.domainTree.reviseOption')}\n \n {t('textSplit.domainTree.reviseDesc')}\n \n \n }\n />\n )}\n }\n label={\n <>\n {t('textSplit.domainTree.rebuildOption')}\n \n {t('textSplit.domainTree.rebuildDesc')}\n \n \n }\n />\n {!isFirstUpload && (\n }\n label={\n <>\n {t('textSplit.domainTree.keepOption')}\n \n {t('textSplit.domainTree.keepDesc')}\n \n \n }\n />\n )}\n \n \n \n \n \n \n \n \n );\n}\n"], ["/easy-dataset/components/distill/DistillTreeView.js", "'use client';\n\nimport { useState, useEffect, useCallback, useMemo, forwardRef, useImperativeHandle } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { Box, Typography, List } from '@mui/material';\nimport axios from 'axios';\nimport { useGenerateDataset } from '@/hooks/useGenerateDataset';\n\n// 导入子组件\nimport TagTreeItem from './TagTreeItem';\nimport TagMenu from './TagMenu';\nimport ConfirmDialog from './ConfirmDialog';\nimport { sortTagsByNumber } from './utils';\n\n/**\n * 蒸馏树形视图组件\n * @param {Object} props\n * @param {string} props.projectId - 项目ID\n * @param {Array} props.tags - 标签列表\n * @param {Function} props.onGenerateSubTags - 生成子标签的回调函数\n * @param {Function} props.onGenerateQuestions - 生成问题的回调函数\n */\nconst DistillTreeView = forwardRef(function DistillTreeView(\n { projectId, tags = [], onGenerateSubTags, onGenerateQuestions },\n ref\n) {\n const { t } = useTranslation();\n const [expandedTags, setExpandedTags] = useState({});\n const [tagQuestions, setTagQuestions] = useState({});\n const [loadingTags, setLoadingTags] = useState({});\n const [loadingQuestions, setLoadingQuestions] = useState({});\n const [menuAnchorEl, setMenuAnchorEl] = useState(null);\n const [selectedTagForMenu, setSelectedTagForMenu] = useState(null);\n const [allQuestions, setAllQuestions] = useState([]);\n const [loading, setLoading] = useState(false);\n const [processingQuestions, setProcessingQuestions] = useState({});\n const [deleteQuestionConfirmOpen, setDeleteQuestionConfirmOpen] = useState(false);\n const [questionToDelete, setQuestionToDelete] = useState(null);\n const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);\n const [tagToDelete, setTagToDelete] = useState(null);\n const [project, setProject] = useState(null);\n const [projectName, setProjectName] = useState('');\n\n // 使用生成数据集的hook\n const { generateSingleDataset } = useGenerateDataset();\n\n // 获取问题统计信息\n const fetchQuestionsStats = useCallback(async () => {\n try {\n setLoading(true);\n const response = await axios.get(`/api/projects/${projectId}/questions/tree?isDistill=true`);\n setAllQuestions(response.data);\n console.log('获取问题统计信息成功:', { totalQuestions: response.data.length });\n } catch (error) {\n console.error('获取问题统计信息失败:', error);\n } finally {\n setLoading(false);\n }\n }, [projectId]);\n\n // 暴露方法给父组件\n useImperativeHandle(ref, () => ({\n fetchQuestionsStats\n }));\n\n // 获取标签下的问题\n const fetchQuestionsByTag = useCallback(\n async tagId => {\n try {\n setLoadingQuestions(prev => ({ ...prev, [tagId]: true }));\n const response = await axios.get(`/api/projects/${projectId}/distill/questions/by-tag?tagId=${tagId}`);\n setTagQuestions(prev => ({\n ...prev,\n [tagId]: response.data\n }));\n } catch (error) {\n console.error('获取标签问题失败:', error);\n } finally {\n setLoadingQuestions(prev => ({ ...prev, [tagId]: false }));\n }\n },\n [projectId]\n );\n\n // 获取项目信息,获取项目名称\n useEffect(() => {\n if (projectId) {\n axios\n .get(`/api/projects/${projectId}`)\n .then(response => {\n setProject(response.data);\n setProjectName(response.data.name || '');\n })\n .catch(error => {\n console.error('获取项目信息失败:', error);\n });\n }\n }, [projectId]);\n\n // 初始化时获取问题统计信息\n useEffect(() => {\n fetchQuestionsStats();\n }, [fetchQuestionsStats]);\n\n // 构建标签树\n const tagTree = useMemo(() => {\n const rootTags = [];\n const tagMap = {};\n\n // 创建标签映射\n tags.forEach(tag => {\n tagMap[tag.id] = { ...tag, children: [] };\n });\n\n // 构建树结构\n tags.forEach(tag => {\n if (tag.parentId && tagMap[tag.parentId]) {\n tagMap[tag.parentId].children.push(tagMap[tag.id]);\n } else {\n rootTags.push(tagMap[tag.id]);\n }\n });\n\n return rootTags;\n }, [tags]);\n\n // 切换标签展开/折叠状态\n const toggleTag = useCallback(\n tagId => {\n setExpandedTags(prev => ({\n ...prev,\n [tagId]: !prev[tagId]\n }));\n\n // 如果展开且还没有加载过问题,则加载问题\n if (!expandedTags[tagId] && !tagQuestions[tagId]) {\n fetchQuestionsByTag(tagId);\n }\n },\n [expandedTags, tagQuestions, fetchQuestionsByTag]\n );\n\n // 处理菜单打开\n const handleMenuOpen = (event, tag) => {\n event.stopPropagation();\n setMenuAnchorEl(event.currentTarget);\n setSelectedTagForMenu(tag);\n };\n\n // 处理菜单关闭\n const handleMenuClose = () => {\n setMenuAnchorEl(null);\n setSelectedTagForMenu(null);\n };\n\n // 打开删除确认对话框\n const openDeleteConfirm = () => {\n console.log('打开删除确认对话框', selectedTagForMenu);\n // 保存要删除的标签\n setTagToDelete(selectedTagForMenu);\n setDeleteConfirmOpen(true);\n handleMenuClose();\n };\n\n // 关闭删除确认对话框\n const closeDeleteConfirm = () => {\n setDeleteConfirmOpen(false);\n };\n\n // 处理删除标签\n const handleDeleteTag = () => {\n if (!tagToDelete) {\n console.log('没有要删除的标签信息');\n return;\n }\n\n console.log('开始删除标签:', tagToDelete.id, tagToDelete.label);\n\n // 先关闭确认对话框\n closeDeleteConfirm();\n\n // 执行删除操作\n const deleteTagAction = async () => {\n try {\n console.log('发送删除请求:', `/api/projects/${projectId}/tags?id=${tagToDelete.id}`);\n\n // 发送删除请求\n const response = await axios.delete(`/api/projects/${projectId}/tags?id=${tagToDelete.id}`);\n\n console.log('删除标签成功:', response.data);\n\n // 刷新页面\n window.location.reload();\n } catch (error) {\n console.error('删除标签失败:', error);\n console.error('错误详情:', error.response ? error.response.data : '无响应数据');\n alert(`删除标签失败: ${error.message}`);\n }\n };\n\n // 立即执行删除操作\n deleteTagAction();\n };\n\n // 打开删除问题确认对话框\n const openDeleteQuestionConfirm = (questionId, event) => {\n event.stopPropagation();\n setQuestionToDelete(questionId);\n setDeleteQuestionConfirmOpen(true);\n };\n\n // 关闭删除问题确认对话框\n const closeDeleteQuestionConfirm = () => {\n setDeleteQuestionConfirmOpen(false);\n setQuestionToDelete(null);\n };\n\n // 处理删除问题\n const handleDeleteQuestion = async () => {\n if (!questionToDelete) return;\n\n try {\n await axios.delete(`/api/projects/${projectId}/questions/${questionToDelete}`);\n // 更新问题列表\n setTagQuestions(prev => {\n const newQuestions = { ...prev };\n Object.keys(newQuestions).forEach(tagId => {\n newQuestions[tagId] = newQuestions[tagId].filter(q => q.id !== questionToDelete);\n });\n return newQuestions;\n });\n // 关闭确认对话框\n closeDeleteQuestionConfirm();\n } catch (error) {\n console.error('删除问题失败:', error);\n }\n };\n\n // 处理生成数据集\n const handleGenerateDataset = async (questionId, questionInfo, event) => {\n event.stopPropagation();\n // 设置处理状态\n setProcessingQuestions(prev => ({\n ...prev,\n [questionId]: true\n }));\n await generateSingleDataset({ projectId, questionId, questionInfo });\n // 重置处理状态\n setProcessingQuestions(prev => ({\n ...prev,\n [questionId]: false\n }));\n };\n\n // 获取标签路径\n const getTagPath = useCallback(\n tag => {\n if (!tag) return '';\n\n const findPath = (currentTag, path = []) => {\n const newPath = [currentTag.label, ...path];\n\n if (!currentTag.parentId) {\n // 如果是顶级标签,确保路径以项目名称开始\n if (projectName && !newPath.includes(projectName)) {\n return [projectName, ...newPath];\n }\n return newPath;\n }\n\n const parentTag = tags.find(t => t.id === currentTag.parentId);\n if (!parentTag) {\n // 如果没有找到父标签,确保路径以项目名称开始\n if (projectName && !newPath.includes(projectName)) {\n return [projectName, ...newPath];\n }\n return newPath;\n }\n\n return findPath(parentTag, newPath);\n };\n\n const path = findPath(tag);\n\n // 最终检查,确保路径以项目名称开始\n if (projectName && path.length > 0 && path[0] !== projectName) {\n path.unshift(projectName);\n }\n\n return path.join(' > ');\n },\n [tags, projectName]\n );\n\n // 渲染标签树\n const renderTagTree = (tagList, level = 0) => {\n // 对同级标签进行排序\n const sortedTagList = sortTagsByNumber(tagList);\n\n return (\n \n {sortedTagList.map(tag => (\n {\n // 包装函数,处理问题生成后的刷新\n const handleGenerateQuestionsWithRefresh = async () => {\n // 调用父组件传入的函数生成问题\n await onGenerateQuestions(tag, getTagPath(tag));\n\n // 生成问题后刷新数据\n await fetchQuestionsStats();\n\n // 如果标签已展开,刷新该标签的问题详情\n if (expandedTags[tag.id]) {\n await fetchQuestionsByTag(tag.id);\n }\n };\n\n handleGenerateQuestionsWithRefresh();\n }}\n onGenerateSubTags={tag => onGenerateSubTags(tag, getTagPath(tag))}\n questions={tagQuestions[tag.id] || []}\n loadingQuestions={loadingQuestions[tag.id]}\n processingQuestions={processingQuestions}\n onDeleteQuestion={openDeleteQuestionConfirm}\n onGenerateDataset={handleGenerateDataset}\n allQuestions={allQuestions}\n tagQuestions={tagQuestions}\n >\n {/* 递归渲染子标签 */}\n {tag.children && tag.children.length > 0 && expandedTags[tag.id] && renderTagTree(tag.children, level + 1)}\n \n ))}\n \n );\n };\n\n return (\n \n {tagTree.length > 0 ? (\n renderTagTree(tagTree)\n ) : (\n \n \n {t('distill.noTags')}\n \n \n )}\n\n {/* 标签操作菜单 */}\n \n\n {/* 删除标签确认对话框 */}\n \n\n {/* 删除问题确认对话框 */}\n \n \n );\n});\n\nexport default DistillTreeView;\n"], ["/easy-dataset/components/mga/GaPairsIndicator.js", "'use client';\n\nimport { useState, useEffect, useCallback, useRef } from 'react';\nimport {\n Box,\n Chip,\n Typography,\n IconButton,\n Tooltip,\n CircularProgress,\n Dialog,\n DialogTitle,\n DialogContent,\n DialogActions,\n Button\n} from '@mui/material';\nimport { Psychology as PsychologyIcon, AutoAwesome as AutoFixIcon } from '@mui/icons-material';\nimport { useTranslation } from 'react-i18next';\nimport GaPairsManager from './GaPairsManager';\n\n/**\n * GA Pairs Indicator Component - Shows GA pairs status for a file\n * @param {Object} props\n * @param {string} props.projectId - Project ID\n * @param {string} props.fileId - File ID\n * @param {string} props.fileName - File name for display\n */\nexport default function GaPairsIndicator({ projectId, fileId, fileName = '未命名文件' }) {\n const { t } = useTranslation();\n const [gaPairs, setGaPairs] = useState([]);\n const [loading, setLoading] = useState(false);\n const [detailsOpen, setDetailsOpen] = useState(false);\n\n // 获取GA对状态的函数\n const fetchGaPairsStatus = useCallback(async () => {\n try {\n setLoading(true);\n\n const response = await fetch(`/api/projects/${projectId}/files/${fileId}/ga-pairs`);\n\n if (!response.ok) {\n if (response.status === 404) {\n setGaPairs([]);\n return;\n }\n throw new Error(`HTTP ${response.status}: Failed to load GA pairs`);\n }\n\n const result = await response.json();\n\n // 处理响应格式\n let newGaPairs = [];\n if (Array.isArray(result)) {\n newGaPairs = result;\n } else if (result?.data) {\n newGaPairs = result.data;\n }\n\n setGaPairs(newGaPairs);\n } catch (error) {\n console.error('获取GA对状态失败:', error);\n setGaPairs([]);\n } finally {\n setLoading(false);\n }\n }, [projectId, fileId]);\n\n // 初始加载\n useEffect(() => {\n if (projectId && fileId) {\n fetchGaPairsStatus();\n }\n }, [projectId, fileId, fetchGaPairsStatus]);\n\n //监听外部事件\n useEffect(() => {\n const handleRefresh = event => {\n const { projectId: eventProjectId, fileIds } = event.detail || {};\n\n if (eventProjectId === projectId && fileIds?.includes(String(fileId))) {\n fetchGaPairsStatus();\n }\n };\n\n window.addEventListener('refreshGaPairsIndicators', handleRefresh);\n return () => window.removeEventListener('refreshGaPairsIndicators', handleRefresh);\n }, [projectId, fileId, fetchGaPairsStatus]);\n\n // 计算激活的GA对数量\n const activePairs = gaPairs.filter(pair => pair.isActive);\n const hasGaPairs = gaPairs.length > 0;\n\n //GA对变化回调处理\n const handleGaPairsChange = useCallback(newGaPairs => {\n setGaPairs(newGaPairs || []);\n }, []);\n\n const handleOpenDialog = useCallback(() => {\n setDetailsOpen(true);\n }, []);\n\n const handleCloseDialog = useCallback(() => {\n setDetailsOpen(false);\n }, []);\n\n //加载状态显示\n if (loading) {\n return (\n \n \n \n Loading...\n \n \n );\n }\n\n return (\n \n {hasGaPairs ? (\n }\n label={`${activePairs.length}/${gaPairs.length} GA Pairs`}\n size=\"small\"\n color={activePairs.length > 0 ? 'primary' : 'default'}\n variant={activePairs.length > 0 ? 'filled' : 'outlined'}\n onClick={handleOpenDialog}\n />\n ) : (\n \n \n \n \n \n )}\n\n {/* Details Dialog */}\n \n GA Pairs for {fileName}\n \n {detailsOpen && (\n \n )}\n \n \n \n \n \n \n );\n}\n"], ["/easy-dataset/app/projects/[projectId]/questions/page.js", "'use client';\n\nimport { useState, useEffect } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport {\n Container,\n Typography,\n Box,\n Button,\n Paper,\n Tabs,\n Tab,\n CircularProgress,\n Divider,\n Checkbox,\n TextField,\n InputAdornment,\n Stack,\n Dialog,\n DialogActions,\n DialogContent,\n DialogContentText,\n DialogTitle,\n LinearProgress,\n Select,\n MenuItem,\n useTheme,\n Tooltip\n} from '@mui/material';\nimport AutoFixHighIcon from '@mui/icons-material/AutoFixHigh';\nimport DeleteIcon from '@mui/icons-material/Delete';\nimport i18n from '@/lib/i18n';\nimport SearchIcon from '@mui/icons-material/Search';\nimport AddIcon from '@mui/icons-material/Add';\nimport QuestionListView from '@/components/questions/QuestionListView';\nimport QuestionTreeView from '@/components/questions/QuestionTreeView';\nimport TabPanel from '@/components/text-split/components/TabPanel';\nimport useTaskSettings from '@/hooks/useTaskSettings';\nimport QuestionEditDialog from './components/QuestionEditDialog';\nimport { useQuestionEdit } from './hooks/useQuestionEdit';\nimport axios from 'axios';\nimport { toast } from 'sonner';\nimport { useDebounce } from '@/hooks/useDebounce';\nimport { useAtomValue } from 'jotai/index';\nimport { selectedModelInfoAtom } from '@/lib/store';\nimport { useGenerateDataset } from '@/hooks/useGenerateDataset';\nimport request from '@/lib/util/request';\n\nexport default function QuestionsPage({ params }) {\n const { t } = useTranslation();\n const theme = useTheme();\n const { projectId } = params;\n const [loading, setLoading] = useState(true);\n const [questions, setQuestions] = useState({});\n const [currentPage, setCurrentPage] = useState(1);\n const [pageSize, setPageSize] = useState(10);\n const [answerFilter, setAnswerFilter] = useState('all'); // 'all', 'answered', 'unanswered'\n const [searchTerm, setSearchTerm] = useState('');\n const debouncedSearchTerm = useDebounce(searchTerm);\n const [tags, setTags] = useState([]);\n const model = useAtomValue(selectedModelInfoAtom);\n const { generateMultipleDataset } = useGenerateDataset();\n const [activeTab, setActiveTab] = useState(0);\n const [selectedQuestions, setSelectedQuestions] = useState([]);\n\n const getQuestionList = async () => {\n try {\n // 获取问题列表\n const questionsResponse = await axios.get(\n `/api/projects/${projectId}/questions?page=${currentPage}&size=10&status=${answerFilter}&input=${searchTerm}`\n );\n if (questionsResponse.status !== 200) {\n throw new Error(t('common.fetchError'));\n }\n setQuestions(questionsResponse.data || {});\n\n // 获取标签树\n const tagsResponse = await axios.get(`/api/projects/${projectId}/tags`);\n if (tagsResponse.status !== 200) {\n throw new Error(t('common.fetchError'));\n }\n setTags(tagsResponse.data.tags || []);\n\n setLoading(false);\n } catch (error) {\n console.error(t('common.fetchError'), error);\n toast.error(error.message);\n }\n };\n\n useEffect(() => {\n getQuestionList();\n }, [currentPage, answerFilter, debouncedSearchTerm]);\n\n const [processing, setProcessing] = useState(false);\n\n const { taskSettings } = useTaskSettings(projectId);\n\n // 进度状态\n const [progress, setProgress] = useState({\n total: 0, // 总共选择的问题数量\n completed: 0, // 已处理完成的数量\n percentage: 0, // 进度百分比\n datasetCount: 0 // 已生成的数据集数量\n });\n\n const {\n editDialogOpen,\n editMode,\n editingQuestion,\n handleOpenCreateDialog,\n handleOpenEditDialog,\n handleCloseDialog,\n handleSubmitQuestion\n } = useQuestionEdit(projectId, updatedQuestion => {\n getQuestionList();\n toast.success(t('questions.operationSuccess'));\n });\n\n const [confirmDialog, setConfirmDialog] = useState({\n open: false,\n title: '',\n content: '',\n confirmAction: null\n });\n\n // 获取所有数据\n useEffect(() => {\n getQuestionList();\n }, [projectId]);\n\n // 处理标签页切换\n const handleTabChange = (event, newValue) => {\n setActiveTab(newValue);\n };\n\n // 处理问题选择\n const handleSelectQuestion = (questionKey, newSelected) => {\n if (newSelected) {\n // 处理批量选择的情况\n setSelectedQuestions(newSelected);\n } else {\n // 处理单个问题选择的情况\n setSelectedQuestions(prev => {\n if (prev.includes(questionKey)) {\n return prev.filter(id => id !== questionKey);\n } else {\n return [...prev, questionKey];\n }\n });\n }\n };\n\n // 全选/取消全选\n const handleSelectAll = async () => {\n if (selectedQuestions.length > 0) {\n setSelectedQuestions([]);\n } else {\n const response = await axios.get(\n `/api/projects/${projectId}/questions?status=${answerFilter}&input=${searchTerm}&selectedAll=1`\n );\n setSelectedQuestions(response.data.map(dataset => dataset.id));\n }\n };\n\n const handleBatchGenerateAnswers_backup = async () => {\n if (selectedQuestions.length === 0) {\n toast.warning(t('questions.noQuestionsSelected'));\n return;\n }\n let data = questions.data.filter(question => selectedQuestions.includes(question.id));\n await generateMultipleDataset(projectId, data);\n await getQuestionList();\n };\n\n // 并行处理数组的辅助函数,限制并发数\n const processInParallel = async (items, processFunction, concurrencyLimit) => {\n const results = [];\n const inProgress = new Set();\n const queue = [...items];\n\n while (queue.length > 0 || inProgress.size > 0) {\n // 如果有空闲槽位且队列中还有任务,启动新任务\n while (inProgress.size < concurrencyLimit && queue.length > 0) {\n const item = queue.shift();\n const promise = processFunction(item).then(result => {\n inProgress.delete(promise);\n return result;\n });\n inProgress.add(promise);\n results.push(promise);\n }\n\n // 等待其中一个任务完成\n if (inProgress.size > 0) {\n await Promise.race(inProgress);\n }\n }\n\n return Promise.all(results);\n };\n\n const handleBatchGenerateAnswers = async () => {\n if (selectedQuestions.length === 0) {\n toast.warning(t('questions.noQuestionsSelected'));\n return;\n }\n\n if (!model) {\n toast.warning(t('models.configNotFound'));\n return;\n }\n\n try {\n setProgress({\n total: selectedQuestions.length,\n completed: 0,\n percentage: 0,\n datasetCount: 0\n });\n\n // 然后设置处理状态为真,确保进度条显示\n setProcessing(true);\n\n toast.info(t('questions.batchGenerateStart', { count: selectedQuestions.length }));\n\n // 单个问题处理函数\n const processQuestion = async questionId => {\n try {\n console.log('开始生成数据集:', { questionId });\n const language = i18n.language === 'zh-CN' ? '中文' : 'en';\n // 调用API生成数据集\n const response = await request(`/api/projects/${projectId}/datasets`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n questionId,\n model,\n language\n })\n });\n\n if (!response.ok) {\n const errorData = await response.json();\n console.error(t('datasets.generateError'), errorData.error || t('datasets.generateFailed'));\n\n // 更新进度状态(即使失败也计入已处理)\n setProgress(prev => {\n const completed = prev.completed + 1;\n const percentage = Math.round((completed / prev.total) * 100);\n\n return {\n ...prev,\n completed,\n percentage\n };\n });\n\n return { success: false, questionId, error: errorData.error || t('datasets.generateFailed') };\n }\n\n const data = await response.json();\n\n // 更新进度状态\n setProgress(prev => {\n const completed = prev.completed + 1;\n const percentage = Math.round((completed / prev.total) * 100);\n const datasetCount = prev.datasetCount + 1;\n\n return {\n ...prev,\n completed,\n percentage,\n datasetCount\n };\n });\n\n console.log(`数据集生成成功: ${questionId}`);\n return { success: true, questionId, data: data.dataset };\n } catch (error) {\n console.error('生成数据集失败:', error);\n\n // 更新进度状态(即使失败也计入已处理)\n setProgress(prev => {\n const completed = prev.completed + 1;\n const percentage = Math.round((completed / prev.total) * 100);\n\n return {\n ...prev,\n completed,\n percentage\n };\n });\n\n return { success: false, questionId, error: error.message };\n }\n };\n\n // 并行处理所有问题,最多同时处理2个\n const results = await processInParallel(selectedQuestions, processQuestion, taskSettings.concurrencyLimit);\n\n // 刷新数据\n getQuestionList();\n\n // 处理完成后设置结果消息\n const successCount = results.filter(r => r.success).length;\n const failCount = results.filter(r => !r.success).length;\n\n if (failCount > 0) {\n toast.warning(\n t('datasets.partialSuccess', {\n successCount,\n total: selectedQuestions.length,\n failCount\n })\n );\n } else {\n toast.success(t('common.success', { successCount }));\n }\n } catch (error) {\n console.error('生成数据集出错:', error);\n toast.error(error.message || '生成数据集失败');\n } finally {\n // 延迟关闭处理状态,确保用户可以看到完成的进度\n setTimeout(() => {\n setProcessing(false);\n // 再次延迟重置进度状态\n setTimeout(() => {\n setProgress({\n total: 0,\n completed: 0,\n percentage: 0,\n datasetCount: 0\n });\n }, 500);\n }, 2000); // 延迟关闭处理状态,让用户看到完成的进度\n }\n };\n\n // 处理删除问题\n const confirmDeleteQuestion = questionId => {\n // 显示确认对话框\n setConfirmDialog({\n open: true,\n title: t('common.confirmDelete'),\n content: t('common.confirmDeleteQuestion'),\n confirmAction: () => executeDeleteQuestion(questionId)\n });\n };\n\n // 执行删除问题的操作\n const executeDeleteQuestion = async questionId => {\n toast.promise(axios.delete(`/api/projects/${projectId}/questions/${questionId}`), {\n loading: '数据删除中',\n success: data => {\n setSelectedQuestions(prev =>\n prev.includes(questionId) ? prev.filter(id => id !== questionId) : [...prev, questionId]\n );\n getQuestionList();\n return t('common.deleteSuccess');\n },\n error: error => {\n return error.response?.data?.message || '删除失败';\n }\n });\n };\n\n // 处理删除问题的入口函数\n const handleDeleteQuestion = questionId => {\n confirmDeleteQuestion(questionId);\n };\n\n // 处理自动生成数据集\n const handleAutoGenerateDatasets = async () => {\n try {\n if (!model) {\n toast.error(t('questions.selectModelFirst', { defaultValue: '请先选择模型' }));\n return;\n }\n\n // 调用创建任务接口\n const response = await axios.post(`/api/projects/${projectId}/tasks`, {\n taskType: 'answer-generation',\n modelInfo: model,\n language: i18n.language\n });\n\n if (response.data?.code === 0) {\n toast.success(t('tasks.createSuccess', { defaultValue: '后台任务已创建,系统将自动处理未生成答案的问题' }));\n } else {\n toast.error(t('tasks.createFailed', { defaultValue: '创建后台任务失败' }));\n }\n } catch (error) {\n console.error('创建任务失败:', error);\n toast.error(t('tasks.createFailed', { defaultValue: '创建任务失败' }) + ': ' + error.message);\n }\n };\n\n // 确认批量删除问题\n const confirmBatchDeleteQuestions = () => {\n if (selectedQuestions.length === 0) {\n toast.warning('请先选择问题');\n return;\n }\n // 显示确认对话框\n setConfirmDialog({\n open: true,\n title: '确认批量删除问题',\n content: `您确定要删除选中的 ${selectedQuestions.length} 个问题吗?此操作不可恢复。`,\n confirmAction: executeBatchDeleteQuestions\n });\n };\n\n // 执行批量删除问题\n const executeBatchDeleteQuestions = async () => {\n toast.promise(\n axios.delete(`/api/projects/${projectId}/questions/batch-delete`, { data: { questionIds: selectedQuestions } }),\n {\n loading: `正在删除 ${selectedQuestions.length} 个问题...`,\n success: data => {\n getQuestionList();\n setSelectedQuestions([]);\n return `成功删除 ${selectedQuestions.length} 个问题`;\n },\n error: error => {\n return error.response?.data?.message || '批量删除问题失败';\n }\n }\n );\n };\n\n // 处理批量删除问题的入口函数\n const handleBatchDeleteQuestions = () => {\n confirmBatchDeleteQuestions();\n };\n\n if (loading) {\n return (\n \n \n \n \n \n );\n }\n\n return (\n \n {/* 处理中的进度显示 - 全局蒙版样式 */}\n {processing && (\n \n \n \n {t('datasets.generatingDataset')}\n \n\n \n \n \n {progress.percentage}%\n \n \n \n \n \n\n \n \n {t('questions.generatingProgress', {\n completed: progress.completed,\n total: progress.total\n })}\n \n \n {t('questions.generatedCount', { count: progress.datasetCount })}\n \n \n \n\n \n\n \n {t('questions.pleaseWait')}\n \n \n \n )}\n\n \n \n {t('questions.title')} ({questions.total})\n \n \n 0 ? 'error' : 'primary'}\n startIcon={}\n onClick={handleBatchDeleteQuestions}\n disabled={selectedQuestions.length === 0}\n >\n {t('questions.deleteSelected')}\n \n\n \n }\n onClick={handleBatchGenerateAnswers}\n disabled={selectedQuestions.length === 0}\n >\n {t('questions.batchGenerate')}\n \n\n \n }\n onClick={handleAutoGenerateDatasets}\n >\n {t('questions.autoGenerateDataset', { defaultValue: '自动生成数据集' })}\n \n \n \n \n\n \n \n \n \n \n\n \n \n \n 0 && selectedQuestions.length === questions?.total}\n indeterminate={selectedQuestions.length > 0 && selectedQuestions.length < questions?.total}\n onChange={handleSelectAll}\n />\n \n {selectedQuestions.length > 0\n ? t('questions.selectedCount', { count: selectedQuestions.length })\n : t('questions.selectAll')}\n (\n {t('questions.totalCount', {\n count: questions.total\n })}\n )\n \n \n\n \n setSearchTerm(e.target.value)}\n InputProps={{\n startAdornment: (\n \n \n \n )\n }}\n />\n setAnswerFilter(e.target.value)}\n size=\"small\"\n sx={{\n width: { xs: '100%', sm: 200 },\n bgcolor: theme.palette.mode === 'dark' ? 'rgba(255, 255, 255, 0.05)' : 'white',\n borderRadius: '8px',\n '& .MuiOutlinedInput-notchedOutline': {\n borderColor: theme.palette.mode === 'dark' ? 'transparent' : 'rgba(0, 0, 0, 0.23)'\n },\n '&:hover .MuiOutlinedInput-notchedOutline': {\n borderColor: theme.palette.mode === 'dark' ? 'transparent' : 'rgba(0, 0, 0, 0.87)'\n },\n '&.Mui-focused .MuiOutlinedInput-notchedOutline': {\n borderColor: 'primary.main'\n }\n }}\n MenuProps={{\n PaperProps: {\n elevation: 2,\n sx: { mt: 1, borderRadius: 2 }\n }\n }}\n >\n {t('questions.filterAll')}\n {t('questions.filterAnswered')}\n {t('questions.filterUnanswered')}\n \n \n \n \n\n \n\n \n setCurrentPage(newPage)}\n selectedQuestions={selectedQuestions}\n onSelectQuestion={handleSelectQuestion}\n onDeleteQuestion={handleDeleteQuestion}\n onEditQuestion={handleOpenEditDialog}\n refreshQuestions={getQuestionList}\n projectId={projectId}\n />\n \n\n \n \n \n \n\n {/* 确认对话框 */}\n setConfirmDialog({ ...confirmDialog, open: false })}\n aria-labelledby=\"alert-dialog-title\"\n aria-describedby=\"alert-dialog-description\"\n >\n {confirmDialog.title}\n \n {confirmDialog.content}\n \n \n \n {\n setConfirmDialog({ ...confirmDialog, open: false });\n if (confirmDialog.confirmAction) {\n confirmDialog.confirmAction();\n }\n }}\n color=\"error\"\n variant=\"contained\"\n autoFocus\n >\n {t('common.confirmDelete')}\n \n \n \n\n \n \n );\n}\n"], ["/easy-dataset/components/datasets/OptimizeDialog.js", "'use client';\n\nimport { Dialog, DialogTitle, DialogContent, DialogActions, Button, TextField, CircularProgress } from '@mui/material';\nimport { useState } from 'react';\nimport { useTranslation } from 'react-i18next';\n\n/**\n * AI优化对话框组件\n */\nexport default function OptimizeDialog({ open, onClose, onConfirm, loading }) {\n const [advice, setAdvice] = useState('');\n const { t } = useTranslation();\n\n const handleConfirm = () => {\n onConfirm(advice);\n setAdvice('');\n };\n\n const handleClose = () => {\n if (!loading) {\n onClose();\n setAdvice('');\n }\n };\n\n return (\n \n {t('datasets.optimizeTitle')}\n \n setAdvice(e.target.value)}\n disabled={loading}\n placeholder={t('datasets.optimizePlaceholder')}\n />\n \n \n \n \n \n \n );\n}\n"], ["/easy-dataset/components/distill/TagTreeItem.js", "'use client';\n\nimport { useState } from 'react';\nimport {\n Box,\n Typography,\n ListItem,\n ListItemButton,\n ListItemIcon,\n ListItemText,\n IconButton,\n Collapse,\n Chip,\n Tooltip,\n List,\n CircularProgress\n} from '@mui/material';\nimport FolderIcon from '@mui/icons-material/Folder';\nimport ExpandMoreIcon from '@mui/icons-material/ExpandMore';\nimport ExpandLessIcon from '@mui/icons-material/ExpandLess';\nimport AddIcon from '@mui/icons-material/Add';\nimport QuestionMarkIcon from '@mui/icons-material/QuestionMark';\nimport MoreVertIcon from '@mui/icons-material/MoreVert';\nimport { useTranslation } from 'react-i18next';\nimport QuestionListItem from './QuestionListItem';\n\n/**\n * 标签树项组件\n * @param {Object} props\n * @param {Object} props.tag - 标签对象\n * @param {number} props.level - 缩进级别\n * @param {boolean} props.expanded - 是否展开\n * @param {Function} props.onToggle - 切换展开/折叠的回调\n * @param {Function} props.onMenuOpen - 打开菜单的回调\n * @param {Function} props.onGenerateQuestions - 生成问题的回调\n * @param {Function} props.onGenerateSubTags - 生成子标签的回调\n * @param {Array} props.questions - 标签下的问题列表\n * @param {boolean} props.loadingQuestions - 是否正在加载问题\n * @param {Object} props.processingQuestions - 正在处理的问题ID映射\n * @param {Function} props.onDeleteQuestion - 删除问题的回调\n * @param {Function} props.onGenerateDataset - 生成数据集的回调\n * @param {Array} props.allQuestions - 所有问题列表(用于计算问题数量)\n * @param {Object} props.tagQuestions - 标签问题映射\n * @param {React.ReactNode} props.children - 子标签内容\n */\nexport default function TagTreeItem({\n tag,\n level = 0,\n expanded = false,\n onToggle,\n onMenuOpen,\n onGenerateQuestions,\n onGenerateSubTags,\n questions = [],\n loadingQuestions = false,\n processingQuestions = {},\n onDeleteQuestion,\n onGenerateDataset,\n allQuestions = [],\n tagQuestions = {},\n children\n}) {\n const { t } = useTranslation();\n\n // 递归计算所有层级的子标签数量\n const getTotalSubTagsCount = childrenTags => {\n let count = childrenTags.length;\n childrenTags.forEach(childTag => {\n if (childTag.children && childTag.children.length > 0) {\n count += getTotalSubTagsCount(childTag.children);\n }\n });\n return count;\n };\n\n // 递归获取所有子标签的问题数量\n const getChildrenQuestionsCount = childrenTags => {\n let count = 0;\n childrenTags.forEach(childTag => {\n // 子标签的问题\n if (tagQuestions[childTag.id] && tagQuestions[childTag.id].length > 0) {\n count += tagQuestions[childTag.id].length;\n } else {\n count += allQuestions.filter(q => q.label === childTag.label).length;\n }\n\n // 子标签的子标签的问题\n if (childTag.children && childTag.children.length > 0) {\n count += getChildrenQuestionsCount(childTag.children);\n }\n });\n return count;\n };\n\n // 计算当前标签的问题数量\n const getCurrentTagQuestionsCount = () => {\n let currentTagQuestions = 0;\n if (tagQuestions[tag.id] && tagQuestions[tag.id].length > 0) {\n currentTagQuestions = tagQuestions[tag.id].length;\n } else {\n currentTagQuestions = allQuestions.filter(q => q.label === tag.label).length;\n }\n return currentTagQuestions;\n };\n\n // 总问题数量 = 当前标签的问题 + 所有子标签的问题\n const totalQuestions =\n getCurrentTagQuestionsCount() + (tag.children ? getChildrenQuestionsCount(tag.children || []) : 0);\n\n return (\n \n 0 ? '1px dashed rgba(0, 0, 0, 0.1)' : 'none',\n ml: level > 0 ? 2 : 0\n }}\n >\n onToggle(tag.id)} sx={{ borderRadius: 1, py: 0.5 }}>\n \n \n \n \n {tag.label}\n {tag.children && tag.children.length > 0 && (\n \n )}\n {totalQuestions > 0 && (\n \n )}\n \n }\n primaryTypographyProps={{ component: 'div' }}\n />\n\n \n \n {\n e.stopPropagation();\n onGenerateQuestions(tag);\n }}\n >\n \n \n \n\n \n {\n e.stopPropagation();\n onGenerateSubTags(tag);\n }}\n >\n \n \n \n\n onMenuOpen(e, tag)}>\n \n \n\n {tag.children && tag.children.length > 0 ? (\n expanded ? (\n \n ) : (\n \n )\n ) : null}\n \n \n \n\n {/* 子标签 */}\n {tag.children && tag.children.length > 0 && (\n \n {children}\n \n )}\n\n {/* 标签下的问题 */}\n {expanded && (\n \n \n {loadingQuestions ? (\n \n \n \n {t('common.loading')}\n \n \n ) : questions && questions.length > 0 ? (\n questions.map(question => (\n onDeleteQuestion(question.id, e)}\n onGenerateDataset={e => onGenerateDataset(question.id, question.question, e)}\n />\n ))\n ) : (\n \n \n {t('distill.noQuestions')}\n \n \n )}\n \n \n )}\n \n );\n}\n"], ["/easy-dataset/components/distill/QuestionListItem.js", "'use client';\n\nimport { useState } from 'react';\nimport {\n ListItem,\n ListItemIcon,\n ListItemText,\n Box,\n Typography,\n Chip,\n IconButton,\n Tooltip,\n CircularProgress\n} from '@mui/material';\nimport HelpOutlineIcon from '@mui/icons-material/HelpOutline';\nimport DeleteIcon from '@mui/icons-material/Delete';\nimport AutoFixHighIcon from '@mui/icons-material/AutoFixHigh';\nimport { useTranslation } from 'react-i18next';\n\n/**\n * 问题列表项组件\n * @param {Object} props\n * @param {Object} props.question - 问题对象\n * @param {number} props.level - 缩进级别\n * @param {Function} props.onDelete - 删除问题的回调\n * @param {Function} props.onGenerateDataset - 生成数据集的回调\n * @param {boolean} props.processing - 是否正在处理\n */\nexport default function QuestionListItem({ question, level, onDelete, onGenerateDataset, processing = false }) {\n const { t } = useTranslation();\n\n return (\n \n \n onGenerateDataset(e)} disabled={processing}>\n {processing ? : }\n \n \n \n onDelete(e)} disabled={processing}>\n \n \n \n \n }\n >\n \n \n \n \n \n {question.question}\n \n {question.answered && (\n \n )}\n \n }\n />\n \n );\n}\n"], ["/easy-dataset/app/projects/[projectId]/datasets/page.js", "'use client';\n\nimport { useState, useEffect } from 'react';\nimport {\n Container,\n Box,\n Typography,\n Button,\n IconButton,\n Paper,\n CircularProgress,\n Dialog,\n DialogTitle,\n DialogContent,\n DialogActions,\n Card,\n useTheme,\n alpha,\n InputBase,\n LinearProgress,\n Select,\n MenuItem\n} from '@mui/material';\nimport DeleteIcon from '@mui/icons-material/Delete';\nimport SearchIcon from '@mui/icons-material/Search';\nimport FileDownloadIcon from '@mui/icons-material/FileDownload';\nimport FilterListIcon from '@mui/icons-material/FilterList';\nimport { useRouter } from 'next/navigation';\nimport ExportDatasetDialog from '@/components/ExportDatasetDialog';\nimport { useTranslation } from 'react-i18next';\nimport DatasetList from './components/DatasetList';\nimport useDatasetExport from './hooks/useDatasetExport';\nimport { processInParallel } from '@/lib/util/async';\nimport axios from 'axios';\nimport { useDebounce } from '@/hooks/useDebounce';\nimport { toast } from 'sonner';\n\n// 删除确认对话框\nconst DeleteConfirmDialog = ({ open, datasets, onClose, onConfirm, batch, progress, deleting }) => {\n const theme = useTheme();\n const { t } = useTranslation();\n const dataset = datasets?.[0];\n return (\n \n \n \n {t('common.confirmDelete')}\n \n \n \n \n {batch\n ? t('datasets.batchconfirmDeleteMessage', {\n count: datasets.length\n })\n : t('common.confirmDeleteDataSet')}\n \n {batch ? (\n ''\n ) : (\n \n \n {t('datasets.question')}:\n \n {dataset?.question}\n \n )}\n {deleting && progress ? (\n \n \n \n {progress.percentage}%\n \n \n \n \n \n \n \n {t('datasets.batchDeleteProgress', {\n completed: progress.completed,\n total: progress.total\n })}\n \n \n {t('datasets.batchDeleteCount', { count: progress.datasetCount })}\n \n \n \n ) : (\n ''\n )}\n \n \n \n \n \n \n );\n};\n\n// 主页面组件\nexport default function DatasetsPage({ params }) {\n const { projectId } = params;\n const router = useRouter();\n const theme = useTheme();\n const [datasets, setDatasets] = useState([]);\n const [loading, setLoading] = useState(true);\n const [deleteDialog, setDeleteDialog] = useState({\n open: false,\n datasets: null,\n batch: false,\n deleting: false\n });\n const [page, setPage] = useState(1);\n const [rowsPerPage, setRowsPerPage] = useState(10);\n const [searchQuery, setSearchQuery] = useState('');\n const debouncedSearchQuery = useDebounce(searchQuery);\n const [searchField, setSearchField] = useState('question'); // 新增:筛选字段,默认为问题\n const [exportDialog, setExportDialog] = useState({ open: false });\n const [selectedIds, setselectedIds] = useState([]);\n const [filterConfirmed, setFilterConfirmed] = useState('all');\n const [filterHasCot, setFilterHasCot] = useState('all');\n const [filterDialogOpen, setFilterDialogOpen] = useState(false);\n const { t } = useTranslation();\n // 删除进度状态\n const [deleteProgress, setDeteleProgress] = useState({\n total: 0, // 总删除问题数量\n completed: 0, // 已删除完成的数量\n percentage: 0 // 进度百分比\n });\n\n // 3. 添加打开导出对话框的处理函数\n const handleOpenExportDialog = () => {\n setExportDialog({ open: true });\n };\n\n // 4. 添加关闭导出对话框的处理函数\n const handleCloseExportDialog = () => {\n setExportDialog({ open: false });\n };\n\n // 获取数据集列表\n const getDatasetsList = async () => {\n try {\n setLoading(true);\n const response = await axios.get(\n `/api/projects/${projectId}/datasets?page=${page}&size=${rowsPerPage}&status=${filterConfirmed}&input=${searchQuery}&field=${searchField}&hasCot=${filterHasCot}`\n );\n setDatasets(response.data);\n } catch (error) {\n toast.error(error.message);\n } finally {\n setLoading(false);\n }\n };\n\n useEffect(() => {\n getDatasetsList();\n }, [projectId, page, rowsPerPage, filterConfirmed, debouncedSearchQuery, searchField, filterHasCot]);\n\n // 处理页码变化\n const handlePageChange = (event, newPage) => {\n // MUI TablePagination 的页码从 0 开始,而我们的 API 从 1 开始\n setPage(newPage + 1);\n };\n\n // 处理每页行数变化\n const handleRowsPerPageChange = event => {\n setPage(1);\n setRowsPerPage(parseInt(event.target.value, 10));\n };\n\n // 打开删除确认框\n const handleOpenDeleteDialog = dataset => {\n setDeleteDialog({\n open: true,\n datasets: [dataset]\n });\n };\n\n // 关闭删除确认框\n const handleCloseDeleteDialog = () => {\n setDeleteDialog({\n open: false,\n dataset: null\n });\n };\n\n const handleBatchDeleteDataset = async () => {\n const datasetsArray = selectedIds.map(id => ({ id }));\n setDeleteDialog({\n open: true,\n datasets: datasetsArray,\n batch: true,\n count: selectedIds.length\n });\n };\n\n const resetProgress = () => {\n setDeteleProgress({\n total: deleteDialog.count,\n completed: 0,\n percentage: 0\n });\n };\n\n const handleDeleteConfirm = async () => {\n if (deleteDialog.batch) {\n setDeleteDialog({\n ...deleteDialog,\n deleting: true\n });\n await handleBatchDelete();\n resetProgress();\n } else {\n const [dataset] = deleteDialog.datasets;\n if (!dataset) return;\n await handleDelete(dataset);\n }\n setselectedIds([]);\n // 刷新数据\n getDatasetsList();\n // 关闭确认框\n handleCloseDeleteDialog();\n };\n\n // 批量删除数据集\n const handleBatchDelete = async () => {\n try {\n await processInParallel(\n selectedIds,\n async datasetId => {\n await fetch(`/api/projects/${projectId}/datasets?id=${datasetId}`, {\n method: 'DELETE'\n });\n },\n 3,\n (cur, total) => {\n setDeteleProgress({\n total,\n completed: cur,\n percentage: Math.floor((cur / total) * 100)\n });\n }\n );\n\n toast.success(t('common.deleteSuccess'));\n } catch (error) {\n console.error('批量删除失败:', error);\n toast.error(error.message || t('common.deleteFailed'));\n }\n };\n\n // 删除数据集\n const handleDelete = async dataset => {\n try {\n const response = await fetch(`/api/projects/${projectId}/datasets?id=${dataset.id}`, {\n method: 'DELETE'\n });\n if (!response.ok) throw new Error(t('datasets.deleteFailed'));\n\n toast.success(t('datasets.deleteSuccess'));\n } catch (error) {\n toast.error(error.message || t('datasets.deleteFailed'));\n }\n };\n\n // 使用自定义 Hook 处理数据集导出逻辑\n const { exportDatasets } = useDatasetExport(projectId);\n\n // 处理导出数据集\n const handleExportDatasets = async exportOptions => {\n const success = await exportDatasets(exportOptions);\n if (success) {\n // 关闭导出对话框\n handleCloseExportDialog();\n }\n };\n\n // 查看详情\n const handleViewDetails = id => {\n router.push(`/projects/${projectId}/datasets/${id}`);\n };\n\n // 处理全选/取消全选\n const handleSelectAll = async event => {\n if (event.target.checked) {\n // 获取所有符合当前筛选条件的数据,不受分页限制\n const response = await axios.get(\n `/api/projects/${projectId}/datasets?status=${filterConfirmed}&input=${searchQuery}&selectedAll=1`\n );\n setselectedIds(response.data.map(dataset => dataset.id));\n } else {\n setselectedIds([]);\n }\n };\n\n // 处理单个选择\n const handleSelectItem = id => {\n setselectedIds(prev => {\n if (prev.includes(id)) {\n return prev.filter(item => item !== id);\n } else {\n return [...prev, id];\n }\n });\n };\n\n if (loading) {\n return (\n \n \n \n \n {t('datasets.loading')}\n \n \n \n );\n }\n\n return (\n \n \n \n \n \n {t('datasets.management')}\n \n \n {t('datasets.stats', {\n total: datasets.total,\n confirmed: datasets.confirmedCount,\n percentage: datasets.total > 0 ? ((datasets.confirmedCount / datasets.total) * 100).toFixed(2) : 0\n })}\n \n \n \n \n \n \n \n {\n setSearchQuery(e.target.value);\n setPage(1);\n }}\n endAdornment={\n {\n setSearchField(e.target.value);\n setPage(1);\n }}\n variant=\"standard\"\n sx={{\n minWidth: 90,\n '& .MuiInput-underline:before': { borderBottom: 'none' },\n '& .MuiInput-underline:after': { borderBottom: 'none' },\n '& .MuiInput-underline:hover:not(.Mui-disabled):before': { borderBottom: 'none' }\n }}\n disableUnderline\n >\n {t('datasets.fieldQuestion')}\n {t('datasets.fieldAnswer')}\n {t('datasets.fieldCOT')}\n {t('datasets.fieldLabel')}\n \n }\n />\n \n setFilterDialogOpen(true)}\n startIcon={}\n sx={{ borderRadius: 2 }}\n >\n {t('datasets.moreFilters')}\n \n }\n sx={{ borderRadius: 2 }}\n onClick={handleOpenExportDialog}\n >\n {t('export.title')}\n \n \n \n \n {selectedIds.length ? (\n \n \n {t('datasets.selected', {\n count: selectedIds.length\n })}\n \n }\n sx={{ borderRadius: 2 }}\n onClick={handleBatchDeleteDataset}\n >\n {t('datasets.batchDelete')}\n \n \n ) : (\n ''\n )}\n\n \n\n \n\n {/* 更多筛选对话框 */}\n setFilterDialogOpen(false)} maxWidth=\"xs\" fullWidth>\n {t('datasets.filtersTitle')}\n \n \n \n {t('datasets.filterConfirmationStatus')}\n \n setFilterConfirmed(e.target.value)}\n fullWidth\n size=\"small\"\n sx={{ mt: 1 }}\n >\n {t('datasets.filterAll')}\n {t('datasets.filterConfirmed')}\n {t('datasets.filterUnconfirmed')}\n \n \n\n \n \n {t('datasets.filterCotStatus')}\n \n setFilterHasCot(e.target.value)}\n fullWidth\n size=\"small\"\n sx={{ mt: 1 }}\n >\n {t('datasets.filterAll')}\n {t('datasets.filterHasCot')}\n {t('datasets.filterNoCot')}\n \n \n \n \n {\n setFilterConfirmed('all');\n setFilterHasCot('all');\n getDatasetsList();\n }}\n >\n {t('datasets.resetFilters')}\n \n {\n setFilterDialogOpen(false);\n setPage(1); // 重置到第一页\n getDatasetsList();\n }}\n variant=\"contained\"\n >\n {t('datasets.applyFilters')}\n \n \n \n\n \n \n );\n}\n"], ["/easy-dataset/components/text-split/components/DirectoryView.js", "'use client';\n\nimport { Box, List, ListItem, ListItemIcon, ListItemText, Collapse, IconButton } from '@mui/material';\nimport FolderIcon from '@mui/icons-material/Folder';\nimport ArticleIcon from '@mui/icons-material/Article';\nimport ExpandLess from '@mui/icons-material/ExpandLess';\nimport ExpandMore from '@mui/icons-material/ExpandMore';\nimport { useTheme } from '@mui/material/styles';\n\n/**\n * 目录结构组件\n * @param {Object} props\n * @param {Array} props.items - 目录项数组\n * @param {Object} props.expandedItems - 展开状态对象\n * @param {Function} props.onToggleItem - 展开/折叠回调\n * @param {number} props.level - 当前层级\n * @param {string} props.parentId - 父级ID\n */\nexport default function DirectoryView({ items, expandedItems, onToggleItem, level = 0, parentId = '' }) {\n const theme = useTheme();\n\n if (!items || items.length === 0) return null;\n\n return (\n 0 ? 2 : 0 }}>\n {items.map((item, index) => {\n const itemId = `${parentId}-${index}`;\n const hasChildren = item.children && item.children.length > 0;\n const isExpanded = expandedItems[itemId] || false;\n\n return (\n \n 0 ? `1px solid ${theme.palette.divider}` : 'none',\n ml: level > 0 ? 1 : 0\n }}\n >\n \n {hasChildren ? : }\n \n \n {hasChildren && (\n onToggleItem(itemId)}>\n {isExpanded ? : }\n \n )}\n \n\n {hasChildren && (\n \n \n \n )}\n \n );\n })}\n \n );\n}\n"], ["/easy-dataset/components/mga/GaPairsManager.js", "'use client';\n\nimport { useState, useEffect } from 'react';\nimport {\n Box,\n Typography,\n Button,\n Card,\n CardContent,\n Switch,\n FormControlLabel,\n TextField,\n IconButton,\n Tooltip,\n Divider,\n Alert,\n CircularProgress,\n Dialog,\n DialogTitle,\n DialogContent,\n DialogActions,\n Grid\n} from '@mui/material';\nimport {\n Add as AddIcon,\n Delete as DeleteIcon,\n AutoFixHigh as AutoFixHighIcon,\n Save as SaveIcon\n} from '@mui/icons-material';\nimport { useTranslation } from 'react-i18next';\nimport i18n from '@/lib/i18n';\n\n/**\n * GA Pairs Manager Component\n * @param {Object} props\n * @param {string} props.projectId - Project ID\n * @param {string} props.fileId - File ID\n * @param {Function} props.onGaPairsChange - Callback when GA pairs change\n */\nexport default function GaPairsManager({ projectId, fileId, onGaPairsChange }) {\n const { t } = useTranslation();\n const [gaPairs, setGaPairs] = useState([]);\n const [backupGaPairs, setBackupGaPairs] = useState([]); // 备份状态\n const [loading, setLoading] = useState(false);\n const [generating, setGenerating] = useState(false);\n const [saving, setSaving] = useState(false);\n const [error, setError] = useState(null);\n const [success, setSuccess] = useState(null);\n const [addDialogOpen, setAddDialogOpen] = useState(false);\n const [newGaPair, setNewGaPair] = useState({\n genreTitle: '',\n genreDesc: '',\n audienceTitle: '',\n audienceDesc: '',\n isActive: true\n });\n\n useEffect(() => {\n loadGaPairs();\n }, [projectId, fileId]);\n\n const loadGaPairs = async () => {\n try {\n setLoading(true);\n setError(null);\n\n const response = await fetch(`/api/projects/${projectId}/files/${fileId}/ga-pairs`);\n\n // 检查响应状态\n if (!response.ok) {\n if (response.status === 404) {\n console.warn('GA Pairs API not found, using empty data');\n setGaPairs([]);\n setBackupGaPairs([]);\n return;\n }\n throw new Error(`HTTP ${response.status}: Failed to load GA pairs`);\n }\n\n const result = await response.json();\n console.log('Load GA pairs result:', result);\n\n if (result.success) {\n const loadedData = result.data || [];\n setGaPairs(loadedData);\n setBackupGaPairs([...loadedData]); // 创建备份\n onGaPairsChange?.(loadedData);\n } else {\n throw new Error(result.error || 'Failed to load GA pairs');\n }\n } catch (error) {\n console.error('Load GA pairs error:', error);\n setError(t('gaPairs.loadError', { error: error.message }));\n } finally {\n setLoading(false);\n }\n };\n\n const generateGaPairs = async () => {\n try {\n setGenerating(true);\n setError(null);\n\n console.log('Starting GA pairs generation...');\n\n // Get current language from i18n\n const currentLanguage = i18n.language === 'en' ? 'en' : '中文';\n\n const response = await fetch(`/api/projects/${projectId}/files/${fileId}/ga-pairs`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n regenerate: false,\n appendMode: true, // 新增:启用追加模式\n language: currentLanguage\n })\n });\n\n if (!response.ok) {\n let errorMessage = t('gaPairs.generateError');\n\n if (response.status === 404) {\n errorMessage = t('gaPairs.serviceNotAvailable');\n } else if (response.status === 400) {\n try {\n const errorResult = await response.json();\n if (errorResult.error?.includes('No active AI model')) {\n errorMessage = t('gaPairs.noActiveModel');\n } else if (errorResult.error?.includes('content might be too short')) {\n errorMessage = t('gaPairs.contentTooShort');\n } else {\n errorMessage = errorResult.error || errorMessage;\n }\n } catch (parseError) {\n errorMessage = t('gaPairs.requestFailed', { status: response.status });\n }\n } else if (response.status === 500) {\n try {\n const errorResult = await response.json();\n if (errorResult.error?.includes('model configuration') || errorResult.error?.includes('Module not found')) {\n errorMessage = t('gaPairs.configError');\n } else {\n errorMessage = errorResult.error || 'Internal server error occurred.';\n }\n } catch (parseError) {\n console.error('Failed to parse error response:', parseError);\n errorMessage = errorResult.error || t('gaPairs.internalServerError');\n }\n }\n\n throw new Error(errorMessage);\n }\n\n // 处理成功响应\n const responseText = await response.text();\n if (!responseText || responseText.trim() === '') {\n throw new Error(t('gaPairs.emptyResponse'));\n }\n\n const result = JSON.parse(responseText);\n console.log('Generate GA pairs result:', result);\n\n if (result.success) {\n // 在追加模式下,后端只返回新生成的GA对\n const newGaPairs = result.data || [];\n\n // 将新生成的GA对追加到现有的GA对\n const updatedGaPairs = [...gaPairs, ...newGaPairs];\n\n setGaPairs(updatedGaPairs);\n setBackupGaPairs([...updatedGaPairs]); // 更新备份\n onGaPairsChange?.(updatedGaPairs);\n setSuccess(\n t('gaPairs.additionalPairsGenerated', {\n count: newGaPairs.length,\n total: updatedGaPairs.length\n })\n );\n } else {\n throw new Error(result.error || t('gaPairs.generationFailed'));\n }\n } catch (error) {\n console.error('Generate GA pairs error:', error);\n setError(error.message);\n } finally {\n setGenerating(false);\n }\n };\n\n const saveGaPairs = async () => {\n try {\n setSaving(true);\n setError(null);\n\n // 验证GA对数据\n const validatedGaPairs = gaPairs.map((pair, index) => {\n // 处理不同的数据格式\n let genreTitle, genreDesc, audienceTitle, audienceDesc;\n\n if (pair.genre && typeof pair.genre === 'object') {\n genreTitle = pair.genre.title;\n genreDesc = pair.genre.description;\n } else {\n genreTitle = pair.genreTitle || pair.genre;\n genreDesc = pair.genreDesc || '';\n }\n\n if (pair.audience && typeof pair.audience === 'object') {\n audienceTitle = pair.audience.title;\n audienceDesc = pair.audience.description;\n } else {\n audienceTitle = pair.audienceTitle || pair.audience;\n audienceDesc = pair.audienceDesc || '';\n }\n\n // 验证必填字段\n if (!genreTitle || !audienceTitle) {\n throw new Error(t('gaPairs.validationError', { number: index + 1 }));\n }\n\n return {\n id: pair.id,\n genreTitle: genreTitle.trim(),\n genreDesc: genreDesc.trim(),\n audienceTitle: audienceTitle.trim(),\n audienceDesc: audienceDesc.trim(),\n isActive: pair.isActive !== undefined ? pair.isActive : true\n };\n });\n\n console.log('Saving validated GA pairs:', validatedGaPairs);\n\n const response = await fetch(`/api/projects/${projectId}/files/${fileId}/ga-pairs`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n updates: validatedGaPairs\n })\n });\n\n if (!response.ok) {\n let errorMessage = t('gaPairs.saveError');\n\n if (response.status === 404) {\n errorMessage = 'GA Pairs save service is not available.';\n } else {\n try {\n const errorResult = await response.json();\n errorMessage = errorResult.error || errorMessage;\n } catch (parseError) {\n errorMessage = t('gaPairs.serverError', { status: response.status });\n }\n }\n\n throw new Error(errorMessage);\n }\n\n const responseText = await response.text();\n const result = responseText ? JSON.parse(responseText) : { success: true };\n\n if (result.success) {\n // 更新本地状态为服务器返回的数据\n const savedData = result.data || validatedGaPairs;\n setGaPairs(savedData);\n\n // 根据保存的GA对数量显示不同的成功消息\n if (savedData.length === 0) {\n setSuccess(t('gaPairs.allPairsDeleted'));\n } else {\n setSuccess(t('gaPairs.pairsSaved', { count: savedData.length }));\n }\n\n onGaPairsChange?.(savedData);\n } else {\n throw new Error(result.error || t('gaPairs.saveOperationFailed'));\n }\n } catch (error) {\n console.error('Save GA pairs error:', error);\n setError(error.message);\n } finally {\n setSaving(false);\n }\n };\n\n const handleGaPairChange = (index, field, value) => {\n const updatedGaPairs = [...gaPairs];\n\n // 确保对象存在\n if (!updatedGaPairs[index]) {\n console.error(`GA pair at index ${index} does not exist`);\n return;\n }\n\n updatedGaPairs[index] = {\n ...updatedGaPairs[index],\n [field]: value\n };\n\n setGaPairs(updatedGaPairs);\n // 不立即调用 onGaPairsChange,等用户点击保存时再调用\n };\n\n const handleDeleteGaPair = index => {\n const updatedGaPairs = gaPairs.filter((_, i) => i !== index);\n setGaPairs(updatedGaPairs);\n onGaPairsChange?.(updatedGaPairs);\n };\n\n const handleAddGaPair = () => {\n // 验证输入\n if (!newGaPair.genreTitle?.trim() || !newGaPair.audienceTitle?.trim()) {\n setError(t('gaPairs.requiredFields'));\n return;\n }\n\n // 创建新的GA对对象\n const newPair = {\n id: `temp_${Date.now()}`, // 临时ID\n genreTitle: newGaPair.genreTitle.trim(),\n genreDesc: newGaPair.genreDesc?.trim() || '',\n audienceTitle: newGaPair.audienceTitle.trim(),\n audienceDesc: newGaPair.audienceDesc?.trim() || '',\n isActive: true\n };\n\n const updatedGaPairs = [...gaPairs, newPair];\n setGaPairs(updatedGaPairs);\n onGaPairsChange?.(updatedGaPairs);\n\n // 重置表单并关闭对话框\n setNewGaPair({\n genreTitle: '',\n genreDesc: '',\n audienceTitle: '',\n audienceDesc: '',\n isActive: true\n });\n setAddDialogOpen(false);\n setError(null);\n };\n\n const resetMessages = () => {\n setError(null);\n setSuccess(null);\n };\n\n const recoverFromBackup = () => {\n setGaPairs([...backupGaPairs]);\n setError(null);\n setSuccess(t('gaPairs.restoredFromBackup'));\n };\n\n useEffect(() => {\n if (error || success) {\n const timer = setTimeout(resetMessages, 5000);\n return () => clearTimeout(timer);\n }\n }, [error, success]);\n\n if (loading) {\n return (\n \n \n {t('gaPairs.loading')}\n \n );\n }\n\n return (\n \n {/* Header with action buttons */}\n \n {t('gaPairs.title')}\n \n {/* 右上角按钮为手动添加GA对 */}\n }\n onClick={() => setAddDialogOpen(true)}\n disabled={generating || saving}\n >\n {t('gaPairs.addPair')}\n \n \n \n \n\n {/* Error/Success Messages */}\n {error && (\n 0 && (\n \n )\n }\n onClose={resetMessages}\n >\n {error}\n \n )}\n {success && (\n \n {success}\n \n )}\n\n {/* Generate GA Pairs Section - 只在没有GA对时显示 */}\n {gaPairs.length === 0 && (\n \n \n \n {t('gaPairs.noGaPairsTitle')}\n \n \n {t('gaPairs.noGaPairsDescription')}\n \n : }\n onClick={generateGaPairs}\n disabled={generating}\n size=\"large\"\n >\n {generating ? t('gaPairs.generating') : t('gaPairs.generateGaPairs')}\n \n \n \n )}\n\n {/* GA Pairs List */}\n {gaPairs.length > 0 && (\n \n \n {t('gaPairs.activePairs', {\n active: gaPairs.filter(pair => pair.isActive).length,\n total: gaPairs.length\n })}\n \n\n \n {gaPairs.map((pair, index) => (\n \n \n \n \n \n {t('gaPairs.pairNumber', { number: index + 1 })}\n \n \n handleGaPairChange(index, 'isActive', e.target.checked)}\n size=\"small\"\n />\n }\n label={t('gaPairs.active')}\n />\n {/* 添加删除按钮 */}\n \n handleDeleteGaPair(index)}>\n \n \n \n \n \n\n \n handleGaPairChange(index, 'genreTitle', e.target.value)}\n multiline\n rows={2}\n fullWidth\n disabled={!pair.isActive}\n />\n handleGaPairChange(index, 'genreDesc', e.target.value)}\n multiline\n rows={2}\n fullWidth\n disabled={!pair.isActive}\n />\n handleGaPairChange(index, 'audienceTitle', e.target.value)}\n multiline\n rows={2}\n fullWidth\n disabled={!pair.isActive}\n />\n handleGaPairChange(index, 'audienceDesc', e.target.value)}\n multiline\n rows={2}\n fullWidth\n disabled={!pair.isActive}\n />\n \n \n \n \n ))}\n \n\n {/* 在GA对列表下方添加生成按钮 */}\n \n : }\n onClick={generateGaPairs}\n disabled={generating}\n >\n {generating ? t('gaPairs.generating') : t('gaPairs.generateMore')}\n \n \n \n )}\n\n {/* Add GA Pair Dialog */}\n setAddDialogOpen(false)} maxWidth=\"md\" fullWidth>\n {t('gaPairs.addDialogTitle')}\n \n \n setNewGaPair({ ...newGaPair, genreTitle: e.target.value })}\n fullWidth\n required\n placeholder={t('gaPairs.genreTitlePlaceholder')}\n />\n setNewGaPair({ ...newGaPair, genreDesc: e.target.value })}\n multiline\n rows={3}\n fullWidth\n placeholder={t('gaPairs.genreDescPlaceholder')}\n />\n setNewGaPair({ ...newGaPair, audienceTitle: e.target.value })}\n fullWidth\n required\n placeholder={t('gaPairs.audienceTitlePlaceholder')}\n />\n setNewGaPair({ ...newGaPair, audienceDesc: e.target.value })}\n multiline\n rows={3}\n fullWidth\n placeholder={t('gaPairs.audienceDescPlaceholder')}\n />\n setNewGaPair({ ...newGaPair, isActive: e.target.checked })}\n />\n }\n label={t('gaPairs.active')}\n />\n \n \n \n {\n setAddDialogOpen(false);\n // 重置表单\n setNewGaPair({\n genreTitle: '',\n genreDesc: '',\n audienceTitle: '',\n audienceDesc: '',\n isActive: true\n });\n }}\n >\n {t('gaPairs.cancel')}\n \n \n {t('gaPairs.addPairButton')}\n \n \n \n \n );\n}\n"], ["/easy-dataset/app/projects/[projectId]/text-split/page.js", "'use client';\n\nimport axios from 'axios';\nimport { useState, useEffect } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport {\n Container,\n Box,\n Tabs,\n Tab,\n IconButton,\n Collapse,\n Dialog,\n DialogContent,\n DialogTitle,\n Typography\n} from '@mui/material';\nimport { useTheme } from '@mui/material/styles';\nimport ExpandMoreIcon from '@mui/icons-material/ExpandMore';\nimport ExpandLessIcon from '@mui/icons-material/ExpandLess';\nimport FullscreenIcon from '@mui/icons-material/Fullscreen';\nimport CloseIcon from '@mui/icons-material/Close';\nimport FileUploader from '@/components/text-split/FileUploader';\nimport FileList from '@/components/text-split/components/FileList';\nimport DeleteConfirmDialog from '@/components/text-split/components/DeleteConfirmDialog';\nimport LoadingBackdrop from '@/components/text-split/LoadingBackdrop';\nimport PdfSettings from '@/components/text-split/PdfSettings';\nimport ChunkList from '@/components/text-split/ChunkList';\nimport DomainAnalysis from '@/components/text-split/DomainAnalysis';\nimport useTaskSettings from '@/hooks/useTaskSettings';\nimport { useAtomValue } from 'jotai/index';\nimport { selectedModelInfoAtom } from '@/lib/store';\nimport useChunks from './useChunks';\nimport useQuestionGeneration from './useQuestionGeneration';\nimport useFileProcessing from './useFileProcessing';\nimport useFileProcessingStatus from '@/hooks/useFileProcessingStatus';\nimport { toast } from 'sonner';\n\nexport default function TextSplitPage({ params }) {\n const { t } = useTranslation();\n const theme = useTheme();\n const { projectId } = params;\n const [activeTab, setActiveTab] = useState(0);\n const { taskSettings } = useTaskSettings(projectId);\n const [pdfStrategy, setPdfStrategy] = useState('default');\n const [questionFilter, setQuestionFilter] = useState('all'); // 'all', 'generated', 'ungenerated'\n const [selectedViosnModel, setSelectedViosnModel] = useState('');\n const selectedModelInfo = useAtomValue(selectedModelInfoAtom);\n const { taskFileProcessing, task } = useFileProcessingStatus();\n const [currentPage, setCurrentPage] = useState(1);\n const [uploadedFiles, setUploadedFiles] = useState({ data: [], total: 0 });\n const [searchFileName, setSearchFileName] = useState('');\n\n // 上传区域的展开/折叠状态\n const [uploaderExpanded, setUploaderExpanded] = useState(true);\n\n // 文献列表(FileList)展示对话框状态\n const [fileListDialogOpen, setFileListDialogOpen] = useState(false);\n\n // 使用自定义hooks\n const { chunks, tocData, loading, fetchChunks, handleDeleteChunk, handleEditChunk, updateChunks, setLoading } =\n useChunks(projectId, questionFilter);\n\n // 获取文件列表\n const fetchUploadedFiles = async (page = currentPage, fileName = searchFileName) => {\n try {\n setLoading(true);\n const params = new URLSearchParams({\n page: page.toString(),\n size: '10'\n });\n\n if (fileName && fileName.trim()) {\n params.append('fileName', fileName.trim());\n }\n\n const response = await axios.get(`/api/projects/${projectId}/files?${params}`);\n setUploadedFiles(response.data);\n } catch (error) {\n console.error('Error fetching files:', error);\n toast.error(error.message || '获取文件列表失败');\n } finally {\n setLoading(false);\n }\n };\n\n // 删除文件确认对话框状态\n const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);\n const [fileToDelete, setFileToDelete] = useState(null);\n\n // 打开删除确认对话框\n const openDeleteConfirm = (fileId, fileName) => {\n setFileToDelete({ fileId, fileName });\n setDeleteConfirmOpen(true);\n };\n\n // 关闭删除确认对话框\n const closeDeleteConfirm = () => {\n setDeleteConfirmOpen(false);\n setFileToDelete(null);\n };\n\n // 确认删除文件\n const confirmDeleteFile = async () => {\n if (!fileToDelete) return;\n\n try {\n setLoading(true);\n closeDeleteConfirm();\n\n await axios.delete(`/api/projects/${projectId}/files/${fileToDelete.fileId}`);\n await fetchUploadedFiles();\n fetchChunks();\n\n toast.success(\n t('textSplit.deleteSuccess', { fileName: fileToDelete.fileName }) || `删除 ${fileToDelete.fileName} 成功`\n );\n } catch (error) {\n console.error('删除文件出错:', error);\n toast.error(error.message || '删除文件失败');\n } finally {\n setLoading(false);\n setFileToDelete(null);\n }\n };\n\n const {\n processing,\n progress: questionProgress,\n handleGenerateQuestions\n } = useQuestionGeneration(projectId, taskSettings);\n\n const { fileProcessing, progress: pdfProgress, handleFileProcessing } = useFileProcessing(projectId);\n\n // 当前页面使用的进度状态\n const progress = processing ? questionProgress : pdfProgress;\n\n // 加载文本块数据和文件列表\n useEffect(() => {\n fetchChunks('all');\n fetchUploadedFiles();\n }, [fetchChunks, taskFileProcessing, currentPage, searchFileName]);\n\n /**\n * 对上传后的文件进行处理\n */\n const handleUploadSuccess = async (fileNames, pdfFiles, domainTreeAction) => {\n try {\n await handleFileProcessing(fileNames, pdfStrategy, selectedViosnModel, domainTreeAction);\n location.reload();\n } catch (error) {\n toast.error('File upload failed' + error.message || '');\n }\n };\n\n // 包装生成问题的处理函数\n const onGenerateQuestions = async chunkIds => {\n await handleGenerateQuestions(chunkIds, selectedModelInfo, fetchChunks);\n };\n\n useEffect(() => {\n const url = new URL(window.location.href);\n if (questionFilter !== 'all') {\n url.searchParams.set('filter', questionFilter);\n } else {\n url.searchParams.delete('filter');\n }\n window.history.replaceState({}, '', url);\n fetchChunks(questionFilter);\n }, [questionFilter]);\n\n const handleSelected = array => {\n if (array.length > 0) {\n axios.post(`/api/projects/${projectId}/chunks`, { array }).then(response => {\n updateChunks(response.data);\n });\n } else {\n fetchChunks();\n }\n };\n\n return (\n \n {/* 文件上传组件 */}\n\n \n setUploaderExpanded(!uploaderExpanded)}\n sx={{\n bgcolor: 'background.paper',\n boxShadow: 1,\n mr: uploaderExpanded ? 1 : 0 // 展开时按钮之间留点间距\n }}\n size=\"small\"\n >\n {uploaderExpanded ? : }\n \n\n {/* 文献列表扩展按钮,仅在上部区域展开时显示 */}\n {uploaderExpanded && (\n setFileListDialogOpen(true)}\n sx={{ bgcolor: 'background.paper', boxShadow: 1 }}\n size=\"small\"\n title={t('textSplit.expandFileList') || '扩展文献列表'}\n >\n \n \n )}\n \n\n \n \n \n \n \n\n {/* 标签页 */}\n \n \n {\n setActiveTab(newValue);\n }}\n variant=\"fullWidth\"\n sx={{ borderBottom: 1, borderColor: 'divider', flexGrow: 1 }}\n >\n \n \n \n \n\n {/* 智能分割标签内容 */}\n {activeTab === 0 && (\n \n )}\n\n {/* 领域分析标签内容 */}\n {activeTab === 1 && }\n \n\n {/* 加载中蒙版 */}\n \n\n {/* 处理中蒙版 */}\n \n\n {/* 文件处理进度蒙版 */}\n \n\n {/* 文件删除确认对话框 */}\n \n\n {/* 文献列表对话框 */}\n setFileListDialogOpen(false)}\n maxWidth=\"lg\"\n fullWidth\n sx={{ '& .MuiDialog-paper': { bgcolor: 'background.default' } }}\n >\n \n {t('textSplit.fileList')}\n setFileListDialogOpen(false)} aria-label=\"close\">\n \n \n \n \n {/* 此处复用 FileUploader 组件中的 FileList 部分 */}\n \n {/* 文件列表内容 */}\n handleSelected(array)}\n onDeleteFile={(fileId, fileName) => openDeleteConfirm(fileId, fileName)}\n projectId={projectId}\n currentPage={currentPage}\n onPageChange={(page, fileName) => {\n if (fileName !== undefined) {\n // 搜索时更新搜索关键词和页码\n setSearchFileName(fileName);\n setCurrentPage(page);\n } else {\n // 翻页时只更新页码\n setCurrentPage(page);\n }\n }}\n isFullscreen={true} // 在对话框中移除高度限制\n />\n \n \n \n \n );\n}\n"], ["/easy-dataset/components/text-split/ChunkCard.js", "'use client';\n\nimport { useState, useEffect } from 'react';\nimport {\n Box,\n Typography,\n IconButton,\n Chip,\n Checkbox,\n Tooltip,\n Card,\n CardContent,\n CardActions,\n Dialog,\n DialogTitle,\n DialogContent,\n DialogActions,\n Button,\n TextField\n} from '@mui/material';\nimport DeleteIcon from '@mui/icons-material/Delete';\nimport VisibilityIcon from '@mui/icons-material/Visibility';\nimport QuizIcon from '@mui/icons-material/Quiz';\nimport EditIcon from '@mui/icons-material/Edit';\nimport { useTheme } from '@mui/material/styles';\nimport { useTranslation } from 'react-i18next';\n\n// 编辑文本块对话框组件\nconst EditChunkDialog = ({ open, chunk, onClose, onSave }) => {\n const [content, setContent] = useState(chunk?.content || '');\n const { t } = useTranslation();\n\n // 当文本块变化时更新内容\n useEffect(() => {\n if (chunk?.content) {\n setContent(chunk.content);\n }\n }, [chunk]);\n\n const handleSave = () => {\n onSave(content);\n onClose();\n };\n\n return (\n \n {t('textSplit.editChunk', { chunkId: chunk?.name })}\n \n setContent(e.target.value)}\n variant=\"outlined\"\n sx={{ mt: 1 }}\n />\n \n \n \n \n \n \n );\n};\n\nexport default function ChunkCard({\n chunk,\n selected,\n onSelect,\n onView,\n onDelete,\n onGenerateQuestions,\n onEdit,\n projectId,\n selectedModel // 添加selectedModel参数\n}) {\n const theme = useTheme();\n const { t } = useTranslation();\n const [editDialogOpen, setEditDialogOpen] = useState(false);\n const [chunkForEdit, setChunkForEdit] = useState(null);\n\n // 获取文本预览\n const getTextPreview = (content, maxLength = 150) => {\n if (!content) return '';\n return content.length > maxLength ? `${content.substring(0, maxLength)}...` : content;\n };\n\n // 检查是否有已生成的问题\n const hasQuestions = chunk.questions && chunk.questions.length > 0;\n\n // 处理编辑按钮点击\n const handleEditClick = async () => {\n try {\n // 显示加载状态\n console.log('正在获取文本块完整内容...');\n console.log('projectId:', projectId, 'chunkId:', chunk.id);\n\n // 先获取完整的文本块内容,使用从外部传入的 projectId\n const response = await fetch(`/api/projects/${projectId}/chunks/${encodeURIComponent(chunk.id)}`);\n\n if (!response.ok) {\n throw new Error(t('textSplit.fetchChunkFailed'));\n }\n\n const data = await response.json();\n console.log('获取文本块完整内容成功:', data);\n\n // 先设置完整数据,再打开对话框(与 ChunkList.js 中的实现一致)\n setChunkForEdit(data);\n setEditDialogOpen(true);\n } catch (error) {\n console.error(t('textSplit.fetchChunkError'), error);\n // 如果出错,使用原始预览数据\n alert(t('textSplit.fetchChunkError'));\n }\n };\n\n // 处理保存编辑内容\n const handleSaveEdit = newContent => {\n if (onEdit) {\n onEdit(chunk.id, newContent);\n }\n };\n\n return (\n <>\n \n \n \n \n \n \n \n {chunk.name}\n \n \n \n \n {chunk.Questions.length > 0 && (\n \n {chunk.Questions.map((q, index) => (\n \n {index + 1}. {q.question}\n \n ))}\n \n }\n arrow\n placement=\"top\"\n >\n \n \n )}\n \n \n\n \n {getTextPreview(chunk.content)}\n \n \n \n \n\n \n \n \n \n \n \n\n \n \n \n \n \n \n \n\n \n \n \n \n \n\n \n \n \n \n \n \n \n\n {/* 编辑文本块对话框 */}\n {\n setEditDialogOpen(false);\n setChunkForEdit(null);\n }}\n onSave={handleSaveEdit}\n />\n \n );\n}\n"], ["/easy-dataset/components/text-split/components/FileList.js", "'use client';\n\nimport {\n Box,\n Typography,\n List,\n ListItem,\n ListItemText,\n IconButton,\n Tooltip,\n Divider,\n CircularProgress,\n Checkbox,\n Button,\n Dialog,\n DialogTitle,\n DialogContent,\n DialogContentText,\n DialogActions,\n FormControlLabel,\n Switch,\n Pagination,\n TextField,\n InputAdornment\n} from '@mui/material';\nimport {\n Visibility as VisibilityIcon,\n Download,\n Delete as DeleteIcon,\n FilePresent as FileIcon,\n Psychology as PsychologyIcon,\n CheckBox as SelectAllIcon,\n CheckBoxOutlineBlank as DeselectAllIcon,\n Search as SearchIcon,\n Clear as ClearIcon\n} from '@mui/icons-material';\nimport { useState, useEffect } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { useAtomValue } from 'jotai';\nimport { selectedModelInfoAtom } from '@/lib/store';\nimport MarkdownViewDialog from '../MarkdownViewDialog';\nimport GaPairsIndicator from '../../mga/GaPairsIndicator';\nimport i18n from '@/lib/i18n';\n\nexport default function FileList({\n theme,\n files = {},\n loading = false,\n onDeleteFile,\n sendToFileUploader,\n projectId,\n setPageLoading,\n currentPage = 1,\n onPageChange,\n isFullscreen = false // 新增参数,用于控制是否处于全屏状态\n}) {\n const { t } = useTranslation();\n\n // 现有的状态\n const [array, setArray] = useState([]);\n const [viewDialogOpen, setViewDialogOpen] = useState(false);\n const [viewContent, setViewContent] = useState('');\n\n // 新增的批量生成GA对相关状态\n const [batchGenDialogOpen, setBatchGenDialogOpen] = useState(false);\n const [generating, setGenerating] = useState(false);\n const [genError, setGenError] = useState(null);\n const [genResult, setGenResult] = useState(null);\n const [projectModel, setProjectModel] = useState(null);\n const [loadingModel, setLoadingModel] = useState(false);\n const [appendMode, setAppendMode] = useState(false);\n\n // 搜索相关状态\n const [searchTerm, setSearchTerm] = useState('');\n const [searchLoading, setSearchLoading] = useState(false);\n\n // 获取当前选中的模型信息\n const selectedModelInfo = useAtomValue(selectedModelInfoAtom);\n\n // 后端搜索功能\n const handleSearch = async searchValue => {\n if (typeof onPageChange === 'function') {\n setSearchLoading(true);\n try {\n // 调用父组件的页面变更函数,传递搜索参数\n await onPageChange(1, searchValue); // 搜索时重置到第一页\n } catch (error) {\n console.error('搜索失败:', error);\n } finally {\n setSearchLoading(false);\n }\n }\n };\n\n // 防抖搜索\n useEffect(() => {\n const timer = setTimeout(() => {\n handleSearch(searchTerm);\n }, 500); // 500ms 防抖\n\n return () => clearTimeout(timer);\n }, [searchTerm]);\n\n // 清空搜索\n const handleClearSearch = () => {\n setSearchTerm('');\n // 清空搜索时立即触发搜索\n handleSearch('');\n };\n\n const handleCheckboxChange = (fileId, isChecked) => {\n setArray(prevArray => {\n let newArray;\n const stringFileId = String(fileId);\n\n if (isChecked) {\n newArray = prevArray.includes(stringFileId) ? prevArray : [...prevArray, stringFileId];\n } else {\n newArray = prevArray.filter(item => item !== stringFileId);\n }\n\n if (typeof sendToFileUploader === 'function') {\n sendToFileUploader(newArray);\n }\n return newArray;\n });\n };\n\n // 全选文件(包括所有页面的文件)\n const handleSelectAll = async () => {\n try {\n // 获取项目中所有文件的ID\n const response = await fetch(`/api/projects/${projectId}/files?getAllIds=true`);\n if (!response.ok) {\n throw new Error('获取文件列表失败');\n }\n\n const data = await response.json();\n const allFileIds = data.allFileIds || [];\n\n setArray(allFileIds);\n if (typeof sendToFileUploader === 'function') {\n sendToFileUploader(allFileIds);\n }\n } catch (error) {\n console.error('全选文件失败:', error);\n // 如果API调用失败,回退到选择当前页面的文件\n if (files?.data?.length > 0) {\n const currentPageFileIds = files.data.map(file => String(file.id));\n setArray(currentPageFileIds);\n if (typeof sendToFileUploader === 'function') {\n sendToFileUploader(currentPageFileIds);\n }\n }\n }\n };\n // 取消全选\n const handleDeselectAll = () => {\n setArray([]);\n if (typeof sendToFileUploader === 'function') {\n sendToFileUploader([]);\n }\n };\n\n const handleCloseViewDialog = () => {\n setViewDialogOpen(false);\n };\n\n // 刷新文本块列表\n const refreshTextChunks = () => {\n if (typeof setPageLoading === 'function') {\n setPageLoading(true);\n setTimeout(() => {\n // 可能需要调用父组件的刷新方法\n sendToFileUploader(array);\n setPageLoading(false);\n }, 500);\n }\n };\n\n const handleViewContent = async fileId => {\n getFileContent(fileId);\n setViewDialogOpen(true);\n };\n\n const handleDownload = async (fileId, fileName) => {\n setPageLoading(true);\n const text = await getFileContent(fileId);\n\n // Modify the filename if it ends with .pdf\n let downloadName = fileName || 'download.txt';\n if (downloadName.toLowerCase().endsWith('.pdf')) {\n downloadName = downloadName.slice(0, -4) + '.md';\n }\n\n const blob = new Blob([text.content], { type: 'text/plain' });\n const url = URL.createObjectURL(blob);\n\n const a = document.createElement('a');\n a.href = url;\n a.download = downloadName;\n\n document.body.appendChild(a);\n a.click();\n\n document.body.removeChild(a);\n URL.revokeObjectURL(url);\n\n setPageLoading(false);\n };\n\n const getFileContent = async fileId => {\n try {\n const response = await fetch(`/api/projects/${projectId}/preview/${fileId}`);\n if (!response.ok) {\n throw new Error(t('textSplit.fetchChunksFailed'));\n }\n const data = await response.json();\n setViewContent(data);\n return data;\n } catch (error) {\n console.error(t('textSplit.fetchChunksError'), error);\n }\n };\n\n const formatFileSize = size => {\n if (size < 1024) {\n return size + 'B';\n } else if (size < 1024 * 1024) {\n return (size / 1024).toFixed(2) + 'KB';\n } else if (size < 1024 * 1024 * 1024) {\n return (size / 1024 / 1024).toFixed(2) + 'MB';\n } else {\n return (size / 1024 / 1024 / 1024).toFixed(2) + 'GB';\n }\n };\n\n // 新增:获取项目特定的默认模型信息\n const fetchProjectModel = async () => {\n try {\n setLoadingModel(true);\n\n // 首先获取项目信息\n const response = await fetch(`/api/projects/${projectId}`);\n if (!response.ok) {\n throw new Error(t('gaPairs.fetchProjectInfoFailed', { status: response.status }));\n }\n\n const projectData = await response.json();\n\n // 获取模型配置\n const modelResponse = await fetch(`/api/projects/${projectId}/model-config`);\n if (!modelResponse.ok) {\n throw new Error(t('gaPairs.fetchModelConfigFailed', { status: modelResponse.status }));\n }\n\n const modelConfigData = await modelResponse.json();\n\n if (modelConfigData.data && Array.isArray(modelConfigData.data)) {\n // 优先使用项目默认模型\n let targetModel = null;\n\n if (projectData.defaultModelConfigId) {\n targetModel = modelConfigData.data.find(model => model.id === projectData.defaultModelConfigId);\n }\n\n // 如果没有默认模型,使用第一个可用的模型\n if (!targetModel) {\n targetModel = modelConfigData.data.find(\n m => m.modelName && m.endpoint && (m.providerId === 'ollama' || m.apiKey)\n );\n }\n\n if (targetModel) {\n setProjectModel(targetModel);\n }\n }\n } catch (error) {\n console.error(t('gaPairs.fetchProjectModelError'), error);\n } finally {\n setLoadingModel(false);\n }\n };\n\n // 新增:批量生成GA对的处理函数\n const handleBatchGenerateGAPairs = async () => {\n if (array.length === 0) {\n setGenError(t('gaPairs.selectAtLeastOneFile'));\n return;\n }\n\n const modelToUse = projectModel || selectedModelInfo;\n\n if (!modelToUse || !modelToUse.id) {\n setGenError(t('gaPairs.noDefaultModel'));\n return;\n }\n\n // 检查模型配置是否完整\n if (!modelToUse.modelName || !modelToUse.endpoint) {\n setGenError('模型配置不完整,请检查模型设置');\n return;\n }\n\n // 检查API密钥(除了ollama模型)\n if (modelToUse.providerId !== 'ollama' && !modelToUse.apiKey) {\n setGenError(t('gaPairs.missingApiKey'));\n return;\n }\n\n try {\n setGenerating(true);\n setGenError(null);\n setGenResult(null);\n\n const stringFileIds = array.map(id => String(id));\n\n // 获取当前语言环境\n const currentLanguage = i18n.language === 'en' ? 'en' : '中文';\n\n const requestData = {\n fileIds: stringFileIds,\n modelConfigId: modelToUse.id,\n language: currentLanguage,\n appendMode: appendMode\n };\n\n const response = await fetch(`/api/projects/${projectId}/batch-generateGA`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(requestData)\n });\n\n const responseText = await response.text();\n\n if (!response.ok) {\n const errorData = await response\n .json()\n .catch(() => ({ error: t('gaPairs.requestFailed', { status: response.status }) }));\n throw new Error(errorData.error || t('gaPairs.requestFailed', { status: response.status }));\n }\n\n const result = JSON.parse(responseText);\n\n if (result.success) {\n setGenResult({\n total: result.data?.length || 0,\n success: result.data?.filter(r => r.success).length || 0\n });\n\n // 成功后清空选择状态\n setArray([]);\n if (typeof sendToFileUploader === 'function') {\n sendToFileUploader([]);\n }\n\n console.log(t('gaPairs.batchGenerationSuccess', { count: result.summary?.success || 0 }));\n\n //发送全局刷新事件\n const successfulFileIds = result.data?.filter(item => item.success)?.map(item => String(item.fileId)) || [];\n\n if (successfulFileIds.length > 0) {\n window.dispatchEvent(\n new CustomEvent('refreshGaPairsIndicators', {\n detail: {\n projectId,\n fileIds: successfulFileIds\n }\n })\n );\n }\n } else {\n setGenError(result.error || t('gaPairs.generationFailed'));\n }\n } catch (error) {\n console.error(t('gaPairs.batchGenerationFailed'), error);\n setGenError(t('gaPairs.generationError', { error: error.message || t('common.unknownError') }));\n } finally {\n setGenerating(false);\n }\n };\n\n // 新增:打开批量生成对话框\n const openBatchGenDialog = () => {\n // 如果没有选中文件,自动选中所有文件\n if (array.length === 0 && files?.data?.length > 0) {\n const allFileIds = files.data.map(file => String(file.id));\n setArray(allFileIds);\n if (typeof sendToFileUploader === 'function') {\n sendToFileUploader(allFileIds);\n }\n }\n\n // 获取项目模型配置\n fetchProjectModel();\n setBatchGenDialogOpen(true);\n };\n\n // 新增:关闭批量生成对话框\n const closeBatchGenDialog = () => {\n setBatchGenDialogOpen(false);\n setGenError(null);\n setGenResult(null);\n setAppendMode(false); // 重置追加模式\n };\n\n return (\n \n {/* 标题和按钮区域 */}\n \n {/* 第一行:标题和按钮 */}\n 0 ? 2 : 0\n }}\n >\n {t('textSplit.uploadedDocuments', { count: files.total })}\n\n {/* 批量生成GA对按钮 */}\n {files.total > 0 && (\n \n {/* 全选/取消全选按钮 */}\n {array.length === files.total ? (\n }\n onClick={handleDeselectAll}\n disabled={loading}\n >\n {t('gaPairs.deselectAllFiles')}\n \n ) : (\n }\n onClick={handleSelectAll}\n disabled={loading}\n >\n {t('gaPairs.selectAllFiles')}\n \n )}\n\n {/* 批量生成GA对按钮 */}\n }\n onClick={openBatchGenDialog}\n disabled={loading}\n >\n {t('gaPairs.batchGenerate')}\n \n \n )}\n \n\n {/* 第二行:搜索框 - 在全屏展示时显示,或者有搜索内容时显示 */}\n {isFullscreen && (files.total > 0 || searchTerm) && (\n \n setSearchTerm(e.target.value)}\n InputProps={{\n startAdornment: (\n \n \n \n ),\n endAdornment: searchTerm && (\n \n \n \n \n \n )\n }}\n sx={{ width: '100%', maxWidth: 400 }}\n />\n {(searchTerm || searchLoading) && (\n \n {searchLoading\n ? '搜索中...'\n : searchTerm\n ? t('textSplit.searchResults', {\n count: files?.data?.length || 0,\n total: files.total,\n defaultValue: `找到 ${files?.data?.length || 0} 个文件(共 ${files.total} 个)`\n })\n : null}\n \n )}\n \n )}\n \n\n {loading ? (\n \n \n \n ) : files.total === 0 ? (\n \n \n {searchTerm\n ? // 搜索无结果\n t('textSplit.noSearchResults', {\n searchTerm,\n defaultValue: `未找到包含 \"${searchTerm}\" 的文件`\n })\n : // 真的没有上传文件\n t('textSplit.noFilesUploaded', {\n defaultValue: '暂未上传文件'\n })}\n \n \n ) : !files?.data || files.data.length === 0 ? (\n \n \n {searchTerm\n ? // 搜索有结果但当前页没数据\n t('textSplit.noResultsOnCurrentPage', {\n defaultValue: '当前页面没有搜索结果,请返回第一页查看'\n })\n : // 当前页没数据但总数不为0\n t('textSplit.noDataOnCurrentPage', {\n defaultValue: '当前页面没有数据'\n })}\n \n \n ) : (\n <>\n \n {files?.data?.map((file, index) => (\n \n \n {/* 文件信息区域 */}\n \n \n \n handleViewContent(file.id)}\n primary={\n \n {file.fileName}\n \n }\n secondary={\n \n {`${formatFileSize(file.size)} · ${new Date(file.createAt).toLocaleString()}`}\n \n }\n />\n \n \n\n {/* 操作按钮区域 */}\n \n handleCheckboxChange(file.id, e.target.checked)}\n />\n \n \n handleDownload(file.id, file.fileName)}>\n \n \n \n \n onDeleteFile(file.id, file.fileName)}>\n \n \n \n \n \n {index < files.data.length - 1 && }\n \n ))}\n \n\n {/* 分页控件 */}\n {files.total > 10 && (\n \n onPageChange && onPageChange(page)}\n color=\"primary\"\n showFirstButton\n showLastButton\n />\n \n )}\n \n )}\n\n {/* 现有的文本块详情对话框 */}\n \n\n {/* 新增:批量生成GA对对话框 */}\n \n 批量生成GA对\n \n {!genResult && (\n \n {t('gaPairs.batchGenerateDescription', { count: array.length })}\n\n {/* 追加模式选择 */}\n \n setAppendMode(e.target.checked)} color=\"primary\" />\n }\n label={`${t('gaPairs.appendMode')}(${t('gaPairs.appendModeDescription')})`}\n />\n \n\n {loadingModel ? (\n \n \n {t('gaPairs.loadingProjectModel')}\n \n ) : projectModel ? (\n \n \n {t('gaPairs.usingModel')}:{' '}\n \n {projectModel.providerName}: {projectModel.modelName}\n \n \n \n ) : (\n \n \n {t('gaPairs.noDefaultModel')}\n \n \n )}\n \n )}\n\n {genError && (\n \n \n {genError}\n \n \n )}\n\n {genResult && (\n \n \n {t('gaPairs.batchGenCompleted', { success: genResult.success, total: genResult.total })}\n \n \n )}\n \n \n \n {!genResult && (\n : }\n >\n {generating ? t('gaPairs.generating') : t('gaPairs.startGeneration')}\n \n )}\n \n \n \n );\n}\n"], ["/easy-dataset/components/playground/ModelSelector.js", "import React from 'react';\nimport {\n FormControl,\n InputLabel,\n Select,\n MenuItem,\n OutlinedInput,\n Box,\n Chip,\n Checkbox,\n ListItemText\n} from '@mui/material';\nimport { useTranslation } from 'react-i18next';\n\nconst ITEM_HEIGHT = 48;\nconst ITEM_PADDING_TOP = 8;\nconst MenuProps = {\n PaperProps: {\n style: {\n maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,\n width: 250\n }\n }\n};\n\n/**\n * 模型选择组件\n * @param {Object} props\n * @param {Array} props.models - 可用模型列表\n * @param {Array} props.selectedModels - 已选择的模型ID列表\n * @param {Function} props.onChange - 选择改变时的回调函数\n */\nexport default function ModelSelector({ models, selectedModels, onChange }) {\n // 获取模型名称\n const getModelName = modelId => {\n const model = models.find(m => m.id === modelId);\n return model ? `${model.providerName}: ${model.modelName}` : modelId;\n };\n const { t } = useTranslation();\n\n return (\n \n {t('playground.selectModelMax3')}\n }\n renderValue={selected => (\n \n {selected.map(modelId => (\n \n ))}\n \n )}\n MenuProps={MenuProps}\n >\n {models\n .filter(m => {\n if (m.providerId.toLowerCase() === 'ollama') {\n return m.modelName && m.endpoint;\n } else {\n return m.modelName && m.endpoint && m.apiKey;\n }\n })\n .map(model => (\n = 3 && !selectedModels.includes(model.id)}\n >\n -1} />\n \n \n ))}\n \n \n );\n}\n"], ["/easy-dataset/components/home/ProjectCard.js", "'use client';\n\nimport {\n Card,\n Box,\n CardActionArea,\n CardContent,\n Typography,\n Avatar,\n Chip,\n Divider,\n IconButton,\n Tooltip\n} from '@mui/material';\nimport Link from 'next/link';\nimport { styles } from '@/styles/home';\nimport DataObjectIcon from '@mui/icons-material/DataObject';\nimport DeleteIcon from '@mui/icons-material/Delete';\nimport FolderOpenIcon from '@mui/icons-material/FolderOpen';\nimport VisibilityIcon from '@mui/icons-material/Visibility';\nimport { useTranslation } from 'react-i18next';\nimport { useState } from 'react';\n\n/**\n * 项目卡片组件\n * @param {Object} props - 组件属性\n * @param {Object} props.project - 项目数据\n * @param {Function} props.onDeleteClick - 删除按钮点击事件处理函数\n */\nexport default function ProjectCard({ project, onDeleteClick }) {\n const { t } = useTranslation();\n const [processingId, setProcessingId] = useState(false);\n\n // 打开项目目录\n const handleOpenDirectory = async event => {\n event.stopPropagation();\n event.preventDefault();\n\n if (processingId) return;\n\n try {\n setProcessingId(true);\n\n const response = await fetch('/api/projects/open-directory', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({ projectId: project.id })\n });\n\n if (!response.ok) {\n const data = await response.json();\n throw new Error(data.error || t('migration.openDirectoryFailed'));\n }\n\n // 成功打开目录,不需要特别处理\n } catch (error) {\n console.error('打开目录错误:', error);\n alert(error.message);\n } finally {\n setProcessingId(false);\n }\n };\n\n // 处理删除按钮点击\n const handleDeleteClick = event => {\n event.stopPropagation();\n event.preventDefault();\n onDeleteClick(event, project);\n };\n\n return (\n \n \n \n \n \n \n {project.name}\n \n \n \n \n \n \n\n \n {project.description}\n \n\n \n\n \n \n {t('projects.lastUpdated')}: {new Date(project.updateAt).toLocaleDateString('zh-CN')}\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n );\n}\n"], ["/easy-dataset/components/text-split/ChunkViewDialog.js", "'use client';\n\nimport { Box, Button, Dialog, DialogTitle, DialogContent, DialogActions, CircularProgress } from '@mui/material';\nimport ReactMarkdown from 'react-markdown';\nimport { useTranslation } from 'react-i18next';\n\nexport default function ChunkViewDialog({ open, chunk, onClose }) {\n const { t } = useTranslation();\n return (\n \n {t('textSplit.chunkDetails', { chunkId: chunk?.name })}\n \n {chunk ? (\n \n {chunk.content}\n \n ) : (\n \n \n \n )}\n \n \n \n \n \n );\n}\n"], ["/easy-dataset/components/home/CreateProjectDialog.js", "'use client';\n\nimport { useState, useEffect } from 'react';\nimport {\n Dialog,\n DialogTitle,\n DialogContent,\n DialogActions,\n Button,\n TextField,\n Box,\n Typography,\n useTheme,\n CircularProgress,\n FormControl,\n InputLabel,\n Select,\n MenuItem\n} from '@mui/material';\nimport { useRouter } from 'next/navigation';\nimport { useTranslation } from 'react-i18next';\n\nexport default function CreateProjectDialog({ open, onClose }) {\n const { t } = useTranslation();\n const theme = useTheme();\n const router = useRouter();\n const [loading, setLoading] = useState(false);\n const [projects, setProjects] = useState([]);\n const [formData, setFormData] = useState({\n name: '',\n description: '',\n reuseConfigFrom: ''\n });\n const [error, setError] = useState(null);\n\n // 获取项目列表\n useEffect(() => {\n const fetchProjects = async () => {\n try {\n const response = await fetch('/api/projects');\n if (response.ok) {\n const data = await response.json();\n setProjects(data);\n }\n } catch (error) {\n console.error('获取项目列表失败:', error);\n }\n };\n\n fetchProjects();\n }, []);\n\n const handleChange = e => {\n const { name, value } = e.target;\n setFormData(prev => ({\n ...prev,\n [name]: value\n }));\n };\n\n const handleSubmit = async e => {\n e.preventDefault();\n setLoading(true);\n setError(null);\n\n try {\n const response = await fetch('/api/projects', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(formData)\n });\n\n if (!response.ok) {\n throw new Error(t('projects.createFailed'));\n }\n\n const data = await response.json();\n\n router.push(`/projects/${data.id}/settings?tab=model`);\n } catch (err) {\n console.error(t('projects.createError'), err);\n setError(err.message);\n } finally {\n setLoading(false);\n }\n };\n\n return (\n \n \n \n {t('projects.createNew')}\n \n \n
\n \n \n \n \n \n {t('projects.reuseConfig')}\n \n {t('projects.noReuse')}\n {projects.map(project => (\n \n {project.name}\n \n ))}\n \n \n \n {error && (\n \n {error}\n \n )}\n \n \n \n \n {loading ? : t('home.createProject')}\n \n \n
\n \n );\n}\n"], ["/easy-dataset/components/playground/ChatMessage.js", "import React, { useState } from 'react';\nimport { Box, Paper, Typography, Alert, useTheme, IconButton, Collapse } from '@mui/material';\nimport ExpandMoreIcon from '@mui/icons-material/ExpandMore';\nimport ExpandLessIcon from '@mui/icons-material/ExpandLess';\nimport PsychologyIcon from '@mui/icons-material/Psychology';\nimport AutoFixHighIcon from '@mui/icons-material/AutoFixHigh';\nimport { useTranslation } from 'react-i18next';\n\n/**\n * 聊天消息组件\n * @param {Object} props\n * @param {Object} props.message - 消息对象\n * @param {string} props.message.role - 消息角色:'user'、'assistant' 或 'error'\n * @param {string} props.message.content - 消息内容\n * @param {string} props.modelName - 模型名称(仅在 assistant 或 error 类型消息中显示)\n */\nexport default function ChatMessage({ message, modelName }) {\n const theme = useTheme();\n const { t } = useTranslation();\n\n // 用户消息\n if (message.role === 'user') {\n return (\n \n \n {typeof message.content === 'string' ? (\n {message.content}\n ) : (\n // 如果是数组类型(用于视觉模型的用户输入)\n <>\n {Array.isArray(message.content) &&\n message.content.map((item, i) => {\n if (item.type === 'text') {\n return (\n \n {item.text}\n \n );\n } else if (item.type === 'image_url') {\n return (\n \n \n \n );\n }\n return null;\n })}\n \n )}\n \n \n );\n }\n\n // 助手消息\n if (message.role === 'assistant') {\n // 处理推理过程的展示状态\n const [showThinking, setShowThinking] = useState(message.showThinking || false);\n const hasThinking = message.thinking && message.thinking.trim().length > 0;\n\n return (\n \n \n {modelName && (\n \n {modelName}\n \n )}\n\n {/* 推理过程显示区域 */}\n {hasThinking && (\n \n \n \n {message.isStreaming ? (\n \n ) : (\n \n )}\n \n {t('playground.reasoningProcess', '推理过程')}\n \n \n setShowThinking(!showThinking)} sx={{ p: 0 }}>\n {showThinking ? : }\n \n \n\n \n \n \n {message.thinking}\n \n \n \n \n )}\n\n {/* 回答内容 */}\n \n {typeof message.content === 'string' ? (\n <>\n {message.content}\n {message.isStreaming && |}\n \n ) : (\n // 如果是数组类型(用于视觉模型的响应)\n <>\n {Array.isArray(message.content) &&\n message.content.map((item, i) => {\n if (item.type === 'text') {\n return {item.text};\n } else if (item.type === 'image_url') {\n return (\n \n \"图片\"\n \n );\n }\n return null;\n })}\n {message.isStreaming && |}\n \n )}\n \n \n \n );\n }\n\n // 错误消息\n if (message.role === 'error') {\n return (\n \n \n {modelName && (\n \n {modelName}\n \n )}\n {message.content}\n \n \n );\n }\n\n return null;\n}\n"], ["/easy-dataset/components/text-split/FileUploader.js", "'use client';\n\nimport { useState, useEffect } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { Paper, Grid } from '@mui/material';\nimport { useTheme } from '@mui/material/styles';\nimport { useAtomValue } from 'jotai/index';\nimport { selectedModelInfoAtom } from '@/lib/store';\nimport UploadArea from './components/UploadArea';\nimport FileList from './components/FileList';\nimport DeleteConfirmDialog from './components/DeleteConfirmDialog';\nimport PdfProcessingDialog from './components/PdfProcessingDialog';\nimport DomainTreeActionDialog from './components/DomainTreeActionDialog';\nimport FileLoadingProgress from './components/FileLoadingProgress';\nimport { fileApi, taskApi } from '@/lib/api';\nimport { getContent, checkMaxSize, checkInvalidFiles, getvalidFiles } from '@/lib/file/file-process';\nimport { toast } from 'sonner';\n\nexport default function FileUploader({\n projectId,\n onUploadSuccess,\n onFileDeleted,\n sendToPages,\n setPdfStrategy,\n pdfStrategy,\n selectedViosnModel,\n setSelectedViosnModel,\n setPageLoading,\n taskFileProcessing,\n fileTask\n}) {\n const theme = useTheme();\n const { t } = useTranslation();\n const [files, setFiles] = useState([]);\n const [pdfFiles, setPdfFiles] = useState([]);\n const [uploadedFiles, setUploadedFiles] = useState({});\n const selectedModelInfo = useAtomValue(selectedModelInfoAtom);\n const [uploading, setUploading] = useState(false);\n const [loading, setLoading] = useState(false);\n const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);\n const [pdfProcessConfirmOpen, setpdfProcessConfirmOpen] = useState(false);\n const [fileToDelete, setFileToDelete] = useState({});\n const [domainTreeActionOpen, setDomainTreeActionOpen] = useState(false);\n const [domainTreeAction, setDomainTreeAction] = useState('');\n const [isFirstUpload, setIsFirstUpload] = useState(false);\n const [pendingAction, setPendingAction] = useState(null);\n const [taskSettings, setTaskSettings] = useState(null);\n const [visionModels, setVisionModels] = useState([]);\n const [currentPage, setCurrentPage] = useState(1);\n const [pageSize] = useState(10);\n const [searchFileName, setSearchFileName] = useState('');\n\n useEffect(() => {\n fetchUploadedFiles();\n }, [currentPage, searchFileName]);\n\n /**\n * 处理 PDF 处理方式选择\n */\n const handleRadioChange = event => {\n const modelId = event.target.selectedVision;\n setPdfStrategy(event.target.value);\n\n if (event.target.value === 'mineru') {\n toast.success(t('textSplit.mineruSelected'));\n } else if (event.target.value === 'vision') {\n const model = visionModels.find(item => item.id === modelId);\n toast.success(\n t('textSplit.customVisionModelSelected', {\n name: model.modelName,\n provider: model.projectName\n })\n );\n } else {\n toast.success(t('textSplit.defaultSelected'));\n }\n };\n\n /**\n * 获取上传的文件列表\n * @param {*} page\n * @param {*} size\n * @param {*} fileName\n */\n const fetchUploadedFiles = async (page = currentPage, size = pageSize, fileName = searchFileName) => {\n try {\n setLoading(true);\n const data = await fileApi.getFiles({ projectId, page, size, fileName, t });\n setUploadedFiles(data);\n\n setIsFirstUpload(data.total === 0);\n\n const taskData = await taskApi.getProjectTasks(projectId);\n setTaskSettings(taskData);\n\n //使用Jotai会出现数据获取的延迟,导致这里模型获取不到,改用localStorage获取模型信息\n const model = JSON.parse(localStorage.getItem('modelConfigList'));\n\n //过滤出视觉模型\n const visionItems = model.filter(item => item.type === 'vision' && item.apiKey);\n\n //先默认选择第一个配置的视觉模型\n if (visionItems.length > 0) {\n setSelectedViosnModel(visionItems[0].id);\n }\n\n setVisionModels(visionItems);\n } catch (error) {\n toast.error(error.message);\n } finally {\n setLoading(false);\n }\n };\n\n /**\n * 处理文件选择\n */\n const handleFileSelect = event => {\n const selectedFiles = Array.from(event.target.files);\n\n checkMaxSize(selectedFiles);\n checkInvalidFiles(selectedFiles);\n\n const validFiles = getvalidFiles(selectedFiles);\n\n if (validFiles.length > 0) {\n setFiles(prev => [...prev, ...validFiles]);\n }\n const hasPdfFiles = selectedFiles.filter(file => file.name.endsWith('.pdf'));\n if (hasPdfFiles.length > 0) {\n setpdfProcessConfirmOpen(true);\n setPdfFiles(hasPdfFiles);\n }\n };\n\n /**\n * 从待上传文件列表中移除文件\n */\n const removeFile = index => {\n const fileToRemove = files[index];\n setFiles(prev => prev.filter((_, i) => i !== index));\n if (fileToRemove && fileToRemove.name.toLowerCase().endsWith('.pdf')) {\n setPdfFiles(prevPdfFiles => prevPdfFiles.filter(pdfFile => pdfFile.name !== fileToRemove.name));\n }\n };\n\n /**\n * 上传文件\n */\n const uploadFiles = async () => {\n if (files.length === 0) return;\n\n // 如果是第一次上传,直接走默认逻辑\n if (isFirstUpload) {\n handleStartUpload('rebuild');\n return;\n }\n\n // 否则打开领域树操作选择对话框\n setDomainTreeAction('upload');\n setPendingAction({ type: 'upload' });\n setDomainTreeActionOpen(true);\n };\n\n /**\n * 处理领域树操作选择\n */\n const handleDomainTreeAction = action => {\n setDomainTreeActionOpen(false);\n\n // 执行挂起的操作\n if (pendingAction && pendingAction.type === 'upload') {\n handleStartUpload(action);\n } else if (pendingAction && pendingAction.type === 'delete') {\n handleDeleteFile(action);\n }\n\n // 清除挂起的操作\n setPendingAction(null);\n };\n\n /**\n * 开始上传文件\n */\n const handleStartUpload = async domainTreeActionType => {\n setUploading(true);\n try {\n const uploadedFileInfos = [];\n for (const file of files) {\n const { fileContent, fileName } = await getContent(file);\n const data = await fileApi.uploadFile({ file, projectId, fileContent, fileName, t });\n uploadedFileInfos.push({ fileName: data.fileName, fileId: data.fileId });\n }\n toast.success(t('textSplit.uploadSuccess', { count: files.length }));\n setFiles([]);\n setCurrentPage(1);\n await fetchUploadedFiles();\n if (onUploadSuccess) {\n await onUploadSuccess(uploadedFileInfos, pdfFiles, domainTreeActionType);\n }\n } catch (err) {\n toast.error(err.message || t('textSplit.uploadFailed'));\n } finally {\n setUploading(false);\n }\n };\n\n // 打开删除确认对话框\n const openDeleteConfirm = (fileId, fileName) => {\n setFileToDelete({ fileId, fileName });\n setDeleteConfirmOpen(true);\n };\n\n // 关闭删除确认对话框\n const closeDeleteConfirm = () => {\n setDeleteConfirmOpen(false);\n setFileToDelete(null);\n };\n\n // 删除文件前确认领域树操作\n const confirmDeleteFile = () => {\n setDeleteConfirmOpen(false);\n\n // 如果没有其他文件了(删除后会变为空),直接删除\n if (uploadedFiles.total <= 1) {\n handleDeleteFile('keep');\n return;\n }\n\n // 否则打开领域树操作选择对话框\n setDomainTreeAction('delete');\n setPendingAction({ type: 'delete' });\n setDomainTreeActionOpen(true);\n };\n\n // 处理删除文件\n const handleDeleteFile = async domainTreeActionType => {\n if (!fileToDelete) return;\n\n try {\n setLoading(true);\n closeDeleteConfirm();\n\n await fileApi.deleteFile({\n fileToDelete,\n projectId,\n domainTreeActionType,\n modelInfo: selectedModelInfo || {},\n t\n });\n await fetchUploadedFiles();\n\n if (onFileDeleted) {\n const filesLength = uploadedFiles.total;\n onFileDeleted(fileToDelete, filesLength);\n }\n\n if (uploadedFiles.data && uploadedFiles.data.length <= 1 && currentPage > 1) {\n setCurrentPage(1);\n }\n\n toast.success(t('textSplit.deleteSuccess', { fileName: fileToDelete.fileName }));\n } catch (error) {\n console.error('删除文件出错:', error);\n toast.error(error.message);\n } finally {\n setLoading(false);\n setFileToDelete(null);\n }\n };\n\n return (\n \n {taskFileProcessing ? (\n \n ) : (\n <>\n \n {/* 左侧:上传文件区域 */}\n \n \n \n\n {/* 右侧:已上传文件列表 */}\n \n sendToPages(array)}\n onDeleteFile={openDeleteConfirm}\n projectId={projectId}\n currentPage={currentPage}\n onPageChange={(page, fileName) => {\n if (fileName !== undefined) {\n // 搜索时更新搜索关键词和页码\n setSearchFileName(fileName);\n setCurrentPage(page);\n } else {\n // 翻页时只更新页码\n setCurrentPage(page);\n }\n }}\n />\n \n \n\n \n\n {/* 领域树操作选择对话框 */}\n setDomainTreeActionOpen(false)}\n onConfirm={handleDomainTreeAction}\n isFirstUpload={isFirstUpload}\n action={domainTreeAction}\n />\n {/* 检测到pdf的处理框 */}\n setpdfProcessConfirmOpen(false)}\n onRadioChange={handleRadioChange}\n value={pdfStrategy}\n projectId={projectId}\n taskSettings={taskSettings}\n visionModels={visionModels}\n selectedViosnModel={selectedViosnModel}\n setSelectedViosnModel={setSelectedViosnModel}\n />\n \n )}\n \n );\n}\n"], ["/easy-dataset/components/datasets/DatasetHeader.js", "'use client';\n\nimport { Box, Button, Divider, Typography, IconButton, CircularProgress, Paper, Tooltip } from '@mui/material';\nimport NavigateBeforeIcon from '@mui/icons-material/NavigateBefore';\nimport NavigateNextIcon from '@mui/icons-material/NavigateNext';\nimport DeleteIcon from '@mui/icons-material/Delete';\nimport { useTranslation } from 'react-i18next';\nimport { useRouter } from 'next/navigation';\n\n/**\n * 数据集详情页面的头部导航组件\n */\nexport default function DatasetHeader({\n projectId,\n datasetsAllCount,\n datasetsConfirmCount,\n confirming,\n currentDataset,\n shortcutsEnabled,\n setShortcutsEnabled,\n onNavigate,\n onConfirm,\n onDelete\n}) {\n const router = useRouter();\n const { t } = useTranslation();\n\n return (\n \n \n \n \n \n {t('datasets.datasetDetail')}\n \n {t('datasets.stats', {\n total: datasetsAllCount,\n confirmed: datasetsConfirmCount,\n percentage: ((datasetsConfirmCount / datasetsAllCount) * 100).toFixed(2)\n })}\n \n \n {/* 快捷键启用选项 - 已注释掉,保持原代码结构 */}\n {/* \n {t('datasets.enableShortcuts')}\n \n \n ?\n \n \n setShortcutsEnabled((prev) => !prev)}\n >\n {shortcutsEnabled ? t('common.enabled') : t('common.disabled')}\n \n */}\n \n onNavigate('prev')}>\n \n \n onNavigate('next')}>\n \n \n \n \n {confirming ? (\n \n ) : currentDataset.confirmed ? (\n t('datasets.confirmed')\n ) : (\n t('datasets.confirmSave')\n )}\n \n \n \n \n \n );\n}\n"], ["/easy-dataset/app/projects/[projectId]/questions/components/QuestionEditDialog.js", "'use client';\n\nimport { useState, useEffect, useMemo } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport {\n Dialog,\n DialogTitle,\n DialogContent,\n DialogActions,\n TextField,\n Button,\n Box,\n Autocomplete,\n TextField as MuiTextField\n} from '@mui/material';\nimport axios from 'axios';\n\nexport default function QuestionEditDialog({\n open,\n onClose,\n onSubmit,\n initialData,\n projectId,\n tags,\n mode = 'create' // 'create' or 'edit'\n}) {\n const [chunks, setChunks] = useState([]);\n const { t } = useTranslation();\n // 获取文本块的标题\n const getChunkTitle = chunkId => {\n const chunk = chunks.find(c => c.id === chunkId);\n return chunk?.name || chunkId; // 直接使用文件名\n };\n\n const [formData, setFormData] = useState({\n id: '',\n question: '',\n chunkId: '',\n label: '' // 默认不选中任何标签\n });\n\n const getChunks = async projectId => {\n // 获取文本块列表\n const response = await axios.get(`/api/projects/${projectId}/split`);\n if (response.status !== 200) {\n throw new Error(t('common.fetchError'));\n }\n setChunks(response.data.chunks || []);\n };\n\n useEffect(() => {\n getChunks(projectId);\n if (initialData) {\n console.log('初始数据:', initialData); // 查看传入的初始数据\n setFormData({\n id: initialData.id,\n question: initialData.question || '',\n chunkId: initialData.chunkId || '',\n label: initialData.label || 'other' // 改用 label 而不是 label\n });\n } else {\n setFormData({\n id: '',\n question: '',\n chunkId: '',\n label: ''\n });\n }\n }, [initialData]);\n\n const handleSubmit = () => {\n onSubmit(formData);\n onClose();\n };\n\n const flattenTags = (tags, prefix = '') => {\n let flatTags = [];\n const traverse = node => {\n flatTags.push({\n id: node.label, // 使用标签名作为 id\n label: node.label, // 直接使用原始标签名\n originalLabel: node.label\n });\n if (node.child && node.child.length > 0) {\n node.child.forEach(child => traverse(child));\n }\n };\n tags.forEach(tag => traverse(tag));\n flatTags.push({\n id: 'other',\n label: t('datasets.uncategorized'),\n originalLabel: 'other'\n });\n return flatTags;\n };\n\n const flattenedTags = useMemo(() => flattenTags(tags), [tags, t]);\n\n // 修改 return 中的 Autocomplete 组件\n {\n return tag.label;\n }}\n value={(() => {\n const foundTag = flattenedTags.find(tag => tag.id === formData.label);\n const defaultTag = flattenedTags.find(tag => tag.id === 'other');\n return foundTag || defaultTag;\n })()}\n onChange={(e, newValue) => {\n setFormData({ ...formData, label: newValue ? newValue.id : 'other' });\n }}\n renderInput={params => (\n \n )}\n />;\n\n return (\n \n {mode === 'create' ? t('questions.createQuestion') : t('questions.editQuestion')}\n \n \n setFormData({ ...formData, question: e.target.value })}\n />\n\n getChunkTitle(chunk.id)}\n value={chunks.find(chunk => chunk.id === formData.chunkId) || null}\n onChange={(e, newValue) => setFormData({ ...formData, chunkId: newValue ? newValue.id : '' })}\n renderInput={params => (\n \n )}\n />\n\n tag.label}\n value={flattenedTags.find(tag => tag.id === formData.label) || null}\n onChange={(e, newValue) => setFormData({ ...formData, label: newValue ? newValue.id : '' })}\n renderInput={params => (\n \n )}\n />\n \n \n \n \n \n \n \n );\n}\n"], ["/easy-dataset/components/questions/QuestionTreeView.js", "'use client';\n\nimport { useState, useEffect, useCallback, useMemo, memo } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport {\n Box,\n Typography,\n Paper,\n List,\n ListItem,\n ListItemText,\n Checkbox,\n IconButton,\n Collapse,\n Chip,\n Tooltip,\n Divider,\n CircularProgress\n} from '@mui/material';\nimport ExpandMoreIcon from '@mui/icons-material/ExpandMore';\nimport ExpandLessIcon from '@mui/icons-material/ExpandLess';\nimport DeleteIcon from '@mui/icons-material/Delete';\nimport AutoFixHighIcon from '@mui/icons-material/AutoFixHigh';\nimport EditIcon from '@mui/icons-material/Edit';\nimport FolderIcon from '@mui/icons-material/Folder';\nimport QuestionMarkIcon from '@mui/icons-material/QuestionMark';\nimport { useGenerateDataset } from '@/hooks/useGenerateDataset';\nimport axios from 'axios';\n\n/**\n * 问题树视图组件\n * @param {Object} props\n * @param {Array} props.tags - 标签树\n * @param {Array} props.selectedQuestions - 已选择的问题ID列表\n * @param {Function} props.onSelectQuestion - 选择问题的回调函数\n * @param {Function} props.onDeleteQuestion - 删除问题的回调函数\n */\nexport default function QuestionTreeView({\n tags = [],\n selectedQuestions = [],\n onSelectQuestion,\n onDeleteQuestion,\n onEditQuestion,\n projectId,\n searchTerm\n}) {\n const { t } = useTranslation();\n const [expandedTags, setExpandedTags] = useState({});\n const [questionsByTag, setQuestionsByTag] = useState({});\n const [processingQuestions, setProcessingQuestions] = useState({});\n const { generateSingleDataset } = useGenerateDataset();\n const [questions, setQuestions] = useState([]);\n const [loadedTags, setLoadedTags] = useState({});\n // 初始化时,将所有标签设置为收起状态(而不是展开状态)\n useEffect(() => {\n async function fetchTagsInfo() {\n try {\n // 获取标签信息,仅用于标签统计\n const response = await axios.get(`/api/projects/${projectId}/questions/tree?tagsOnly=true&input=${searchTerm}`);\n setQuestions(response.data); // 设置数据仅用于标签统计\n\n // 当搜索条件变化时,重新加载已展开标签的问题数据\n const expandedTagLabels = Object.entries(expandedTags)\n .filter(([_, isExpanded]) => isExpanded)\n .map(([label]) => label);\n\n // 重新加载已展开标签的数据\n for (const label of expandedTagLabels) {\n fetchTagQuestions(label);\n }\n } catch (error) {\n console.error('获取标签信息失败:', error);\n }\n }\n\n if (projectId) {\n fetchTagsInfo();\n }\n\n const initialExpandedState = {};\n const processTag = tag => {\n // 将默认状态改为 false(收起)而不是 true(展开)\n initialExpandedState[tag.label] = false;\n if (tag.child && tag.child.length > 0) {\n tag.child.forEach(processTag);\n }\n };\n\n tags.forEach(processTag);\n // 未分类问题也默认收起\n initialExpandedState['uncategorized'] = false;\n setExpandedTags(initialExpandedState);\n }, [tags]);\n\n // 根据标签对问题进行分类\n useEffect(() => {\n const taggedQuestions = {};\n\n // 初始化标签映射\n const initTagMap = tag => {\n taggedQuestions[tag.label] = [];\n if (tag.child && tag.child.length > 0) {\n tag.child.forEach(initTagMap);\n }\n };\n\n tags.forEach(initTagMap);\n\n // 将问题分配到对应的标签下\n questions.forEach(question => {\n // 如果问题没有标签,添加到\"未分类\"\n if (!question.label) {\n if (!taggedQuestions['uncategorized']) {\n taggedQuestions['uncategorized'] = [];\n }\n taggedQuestions['uncategorized'].push(question);\n return;\n }\n\n // 将问题添加到匹配的标签下\n const questionLabel = question.label;\n\n // 查找最精确匹配的标签\n // 使用一个数组来存储所有匹配的标签路径,以便找到最精确的匹配\n const findAllMatchingTags = (tag, path = []) => {\n const currentPath = [...path, tag.label];\n\n // 存储所有匹配结果\n const matches = [];\n\n // 精确匹配当前标签\n if (tag.label === questionLabel) {\n matches.push({ label: tag.label, depth: currentPath.length });\n }\n\n // 检查子标签\n if (tag.child && tag.child.length > 0) {\n for (const childTag of tag.child) {\n const childMatches = findAllMatchingTags(childTag, currentPath);\n matches.push(...childMatches);\n }\n }\n\n return matches;\n };\n\n // 在所有根标签中查找所有匹配\n let allMatches = [];\n for (const rootTag of tags) {\n const matches = findAllMatchingTags(rootTag);\n allMatches.push(...matches);\n }\n\n // 找到深度最大的匹配(最精确的匹配)\n let matchedTagLabel = null;\n if (allMatches.length > 0) {\n // 按深度排序,深度最大的是最精确的匹配\n allMatches.sort((a, b) => b.depth - a.depth);\n matchedTagLabel = allMatches[0].label;\n }\n\n if (matchedTagLabel) {\n // 如果找到匹配的标签,将问题添加到该标签下\n if (!taggedQuestions[matchedTagLabel]) {\n taggedQuestions[matchedTagLabel] = [];\n }\n taggedQuestions[matchedTagLabel].push(question);\n } else {\n // 如果找不到匹配的标签,添加到\"未分类\"\n if (!taggedQuestions['uncategorized']) {\n taggedQuestions['uncategorized'] = [];\n }\n taggedQuestions['uncategorized'].push(question);\n }\n });\n\n setQuestionsByTag(taggedQuestions);\n }, [questions, tags]);\n\n // 处理展开/折叠标签 - 使用 useCallback 优化\n const handleToggleExpand = useCallback(\n tagLabel => {\n // 检查是否需要加载此标签的问题数据\n const shouldExpand = !expandedTags[tagLabel];\n\n if (shouldExpand && !loadedTags[tagLabel]) {\n // 如果要展开且尚未加载数据,则加载数据\n fetchTagQuestions(tagLabel);\n }\n\n setExpandedTags(prev => ({\n ...prev,\n [tagLabel]: shouldExpand\n }));\n },\n [expandedTags, loadedTags, projectId]\n );\n\n // 获取特定标签的问题数据\n const fetchTagQuestions = useCallback(\n async tagLabel => {\n try {\n const response = await axios.get(\n `/api/projects/${projectId}/questions/tree?tag=${encodeURIComponent(tagLabel)}${searchTerm ? `&input=${searchTerm}` : ''}`\n );\n\n // 更新问题数据,合并新获取的数据\n setQuestions(prev => {\n // 创建一个新数组,包含现有数据\n const updatedQuestions = [...prev];\n\n // 添加新获取的问题数据\n response.data.forEach(newQuestion => {\n // 检查是否已存在相同 ID 的问题\n const existingIndex = updatedQuestions.findIndex(q => q.id === newQuestion.id);\n if (existingIndex === -1) {\n // 如果不存在,添加到数组\n updatedQuestions.push(newQuestion);\n } else {\n // 如果已存在,更新数据\n updatedQuestions[existingIndex] = newQuestion;\n }\n });\n\n return updatedQuestions;\n });\n\n // 标记该标签已加载数据\n setLoadedTags(prev => ({\n ...prev,\n [tagLabel]: true\n }));\n } catch (error) {\n console.error(`获取标签 \"${tagLabel}\" 的问题失败:`, error);\n }\n },\n [projectId, searchTerm, expandedTags]\n );\n\n // 检查问题是否被选中 - 使用 useCallback 优化\n const isQuestionSelected = useCallback(\n questionKey => {\n return selectedQuestions.includes(questionKey);\n },\n [selectedQuestions]\n );\n\n // 处理生成数据集 - 使用 useCallback 优化\n const handleGenerateDataset = async (questionId, questionInfo) => {\n // 设置处理状态\n setProcessingQuestions(prev => ({\n ...prev,\n [questionId]: true\n }));\n await generateSingleDataset({ projectId, questionId, questionInfo });\n // 重置处理状态\n setProcessingQuestions(prev => ({\n ...prev,\n [questionId]: false\n }));\n };\n\n // 渲染单个问题项 - 使用 useCallback 优化\n const renderQuestionItem = useCallback(\n (question, index, total) => {\n const questionKey = question.id;\n return (\n \n );\n },\n [isQuestionSelected, onSelectQuestion, onDeleteQuestion, handleGenerateDataset, processingQuestions, t]\n );\n\n // 计算标签及其子标签下的所有问题数量 - 使用 useMemo 缓存计算结果\n const tagQuestionCounts = useMemo(() => {\n const counts = {};\n\n const countQuestions = tag => {\n const directQuestions = questionsByTag[tag.label] || [];\n let total = directQuestions.length;\n\n if (tag.child && tag.child.length > 0) {\n for (const childTag of tag.child) {\n total += countQuestions(childTag);\n }\n }\n\n counts[tag.label] = total;\n return total;\n };\n\n tags.forEach(countQuestions);\n return counts;\n }, [questionsByTag, tags]);\n\n // 递归渲染标签树 - 使用 useCallback 优化\n const renderTagTree = useCallback(\n (tag, level = 0) => {\n const questions = questionsByTag[tag.label] || [];\n const hasQuestions = questions.length > 0;\n const hasChildren = tag.child && tag.child.length > 0;\n const isExpanded = expandedTags[tag.label];\n const totalQuestions = tagQuestionCounts[tag.label] || 0;\n\n return (\n \n \n\n {/* 只有当标签展开时才渲染子内容,减少不必要的渲染 */}\n {isExpanded && (\n \n {hasChildren && (\n {tag.child.map(childTag => renderTagTree(childTag, level + 1))}\n )}\n\n {hasQuestions && (\n \n {questions.map((question, index) => renderQuestionItem(question, index, questions.length))}\n \n )}\n \n )}\n \n );\n },\n [questionsByTag, expandedTags, tagQuestionCounts, handleToggleExpand, renderQuestionItem, t]\n );\n\n // 渲染未分类问题\n const renderUncategorizedQuestions = () => {\n const uncategorizedQuestions = questionsByTag['uncategorized'] || [];\n if (uncategorizedQuestions.length === 0) return null;\n\n return (\n \n handleToggleExpand('uncategorized')}\n sx={{\n py: 1,\n bgcolor: 'primary.light',\n color: 'primary.contrastText',\n '&:hover': {\n bgcolor: 'primary.main'\n },\n borderRadius: '4px',\n mb: 0.5,\n pr: 1\n }}\n >\n \n \n \n {t('datasets.uncategorized')}\n \n \n \n }\n />\n \n {expandedTags['uncategorized'] ? : }\n \n \n\n \n \n {uncategorizedQuestions.map((question, index) =>\n renderQuestionItem(question, index, uncategorizedQuestions.length)\n )}\n \n \n \n );\n };\n\n // 如果没有标签和问题,显示空状态\n if (tags.length === 0 && Object.keys(questionsByTag).length === 0) {\n return (\n \n \n {t('datasets.noTagsAndQuestions')}\n \n \n );\n }\n\n return (\n \n \n {renderUncategorizedQuestions()}\n {tags.map(tag => renderTagTree(tag))}\n \n \n );\n}\n\n// 使用 memo 优化问题项渲染\nconst QuestionItem = memo(\n ({ question, index, total, isSelected, onSelect, onDelete, onGenerate, onEdit, isProcessing, t }) => {\n const questionKey = question.id;\n return (\n \n \n onSelect(questionKey)} size=\"small\" />\n \n \n {question.question}\n {question.dataSites && question.dataSites.length > 0 && (\n \n )}\n \n }\n secondary={\n \n {t('datasets.source')}: {question.chunk?.name || question.chunkId || t('common.unknown')}\n \n }\n />\n \n \n \n onEdit({\n question: question.question,\n chunkId: question.chunkId,\n label: question.label || 'other'\n })\n }\n disabled={isProcessing}\n >\n \n \n \n \n onGenerate(question.id, question.question)}\n disabled={isProcessing}\n >\n {isProcessing ? : }\n \n \n \n onDelete(question.question, question.chunkId)}>\n \n \n \n \n \n {index < total - 1 && }\n \n );\n }\n);\n\n// 使用 memo 优化标签项渲染\nconst TagItem = memo(({ tag, level, isExpanded, totalQuestions, onToggle, t }) => {\n return (\n onToggle(tag.label)}\n sx={{\n pl: level * 2 + 1,\n py: 1,\n bgcolor: level === 0 ? 'primary.light' : 'background.paper',\n color: level === 0 ? 'primary.contrastText' : 'inherit',\n '&:hover': {\n bgcolor: level === 0 ? 'primary.main' : 'action.hover'\n },\n borderRadius: '4px',\n mb: 0.5,\n pr: 1\n }}\n >\n {/* 内部内容保持不变 */}\n \n \n \n {tag.label}\n \n {totalQuestions > 0 && (\n \n )}\n \n }\n />\n \n {isExpanded ? : }\n \n \n );\n});\n"], ["/easy-dataset/app/projects/[projectId]/datasets/[datasetId]/page.js", "'use client';\n\nimport { Container, Box, Typography, Alert, Snackbar, Paper } from '@mui/material';\nimport ChunkViewDialog from '@/components/text-split/ChunkViewDialog';\nimport DatasetHeader from '@/components/datasets/DatasetHeader';\nimport DatasetMetadata from '@/components/datasets/DatasetMetadata';\nimport EditableField from '@/components/datasets/EditableField';\nimport OptimizeDialog from '@/components/datasets/OptimizeDialog';\nimport useDatasetDetails from '@/app/projects/[projectId]/datasets/[datasetId]/useDatasetDetails';\nimport { useTranslation } from 'react-i18next';\n\n/**\n * 数据集详情页面\n */\nexport default function DatasetDetailsPage({ params }) {\n const { projectId, datasetId } = params;\n\n const { t } = useTranslation();\n // 使用自定义Hook管理状态和逻辑\n const {\n currentDataset,\n loading,\n editingAnswer,\n editingCot,\n answerValue,\n cotValue,\n snackbar,\n confirming,\n optimizeDialog,\n viewDialogOpen,\n viewChunk,\n datasetsAllCount,\n datasetsConfirmCount,\n answerTokens,\n cotTokens,\n shortcutsEnabled,\n setShortcutsEnabled,\n setSnackbar,\n setAnswerValue,\n setCotValue,\n setEditingAnswer,\n setEditingCot,\n handleNavigate,\n handleConfirm,\n handleSave,\n handleDelete,\n handleOpenOptimizeDialog,\n handleCloseOptimizeDialog,\n handleOptimize,\n handleViewChunk,\n handleCloseViewDialog\n } = useDatasetDetails(projectId, datasetId);\n\n // 加载状态\n if (loading) {\n return (\n \n \n {t('datasets.loadingDataset')}\n \n \n );\n }\n\n // 无数据状态\n if (!currentDataset) {\n return (\n \n {t('datasets.datasetNotFound')}\n \n );\n }\n\n return (\n \n {/* 顶部导航栏 */}\n \n\n {/* 主要内容 */}\n \n \n \n {t('datasets.question')}\n \n \n {currentDataset.question}\n \n \n\n setEditingAnswer(true)}\n onChange={e => setAnswerValue(e.target.value)}\n onSave={() => handleSave('answer', answerValue)}\n onCancel={() => {\n setEditingAnswer(false);\n setAnswerValue(currentDataset.answer);\n }}\n onOptimize={handleOpenOptimizeDialog}\n tokenCount={answerTokens}\n />\n\n setEditingCot(true)}\n onChange={e => setCotValue(e.target.value)}\n onSave={() => handleSave('cot', cotValue)}\n onCancel={() => {\n setEditingCot(false);\n setCotValue(currentDataset.cot || '');\n }}\n tokenCount={cotTokens}\n />\n\n \n \n\n {/* 消息提示 */}\n setSnackbar(prev => ({ ...prev, open: false }))}\n anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}\n >\n setSnackbar(prev => ({ ...prev, open: false }))}\n severity={snackbar.severity}\n sx={{ width: '100%' }}\n >\n {snackbar.message}\n \n \n\n {/* AI优化对话框 */}\n \n\n {/* 文本块详情对话框 */}\n \n \n );\n}\n"], ["/easy-dataset/components/settings/ModelSettings.js", "'use client';\n\nimport { useState, useEffect } from 'react';\nimport {\n Typography,\n Box,\n Button,\n TextField,\n Grid,\n Card,\n CardContent,\n Dialog,\n DialogTitle,\n DialogContent,\n DialogActions,\n FormControl,\n Autocomplete,\n Slider,\n InputLabel,\n Select,\n MenuItem,\n Stack,\n Paper,\n Avatar,\n Tooltip,\n IconButton,\n Chip\n} from '@mui/material';\nimport AddIcon from '@mui/icons-material/Add';\nimport CheckCircleIcon from '@mui/icons-material/CheckCircle';\nimport ErrorIcon from '@mui/icons-material/Error';\nimport { DEFAULT_MODEL_SETTINGS, MODEL_PROVIDERS } from '@/constant/model';\nimport { useTranslation } from 'react-i18next';\nimport axios from 'axios';\nimport { ProviderIcon } from '@lobehub/icons';\nimport { toast } from 'sonner';\nimport EditIcon from '@mui/icons-material/Edit';\nimport DeleteIcon from '@mui/icons-material/Delete';\nimport ScienceIcon from '@mui/icons-material/Science';\nimport { useRouter } from 'next/navigation';\nimport { useAtom } from 'jotai';\nimport { modelConfigListAtom, selectedModelInfoAtom } from '@/lib/store';\n\nexport default function ModelSettings({ projectId }) {\n const { t } = useTranslation();\n const router = useRouter();\n // 模型对话框状态\n const [openModelDialog, setOpenModelDialog] = useState(false);\n const [editingModel, setEditingModel] = useState(null);\n const [loading, setLoading] = useState(true);\n const [providerList, setProviderList] = useState([]);\n const [providerOptions, setProviderOptions] = useState([]);\n const [selectedProvider, setSelectedProvider] = useState({});\n const [models, setModels] = useState([]);\n const [modelConfigList, setModelConfigList] = useAtom(modelConfigListAtom);\n const [selectedModelInfo, setSelectedModelInfo] = useAtom(selectedModelInfoAtom);\n const [modelConfigForm, setModelConfigForm] = useState({\n id: '',\n providerId: '',\n providerName: '',\n endpoint: '',\n apiKey: '',\n modelId: '',\n modelName: '',\n type: 'text',\n temperature: 0.0,\n maxTokens: 0,\n topP: 0,\n topK: 0,\n status: 1\n });\n\n useEffect(() => {\n getProvidersList();\n getModelConfigList();\n }, []);\n\n // 获取提供商列表\n const getProvidersList = () => {\n axios.get('/api/llm/providers').then(response => {\n console.log('获取的模型列表:', response.data);\n setProviderList(response.data);\n const providerOptions = response.data.map(provider => ({\n id: provider.id,\n label: provider.name\n }));\n setSelectedProvider(response.data[0]);\n getProviderModels(response.data[0].id);\n setProviderOptions(providerOptions);\n });\n };\n\n // 获取模型配置列表\n const getModelConfigList = () => {\n axios\n .get(`/api/projects/${projectId}/model-config`)\n .then(response => {\n setModelConfigList(response.data.data);\n setLoading(false);\n })\n .catch(error => {\n setLoading(false);\n toast.error('Fetch model list Error', { duration: 3000 });\n });\n };\n\n const onChangeProvider = (event, newValue) => {\n console.log('选择提供商:', newValue, typeof newValue);\n if (typeof newValue === 'string') {\n // 用户手动输入了自定义提供商\n setModelConfigForm(prev => ({\n ...prev,\n providerId: 'custom',\n endpoint: '',\n providerName: ''\n }));\n } else if (newValue && newValue.id) {\n // 用户从下拉列表中选择了一个提供商\n const selectedProvider = providerList.find(p => p.id === newValue.id);\n if (selectedProvider) {\n setSelectedProvider(selectedProvider);\n setModelConfigForm(prev => ({\n ...prev,\n providerId: selectedProvider.id,\n endpoint: selectedProvider.apiUrl,\n providerName: selectedProvider.name,\n modelName: ''\n }));\n getProviderModels(newValue.id);\n }\n }\n };\n\n // 获取提供商的模型列表(DB)\n const getProviderModels = providerId => {\n axios\n .get(`/api/llm/model?providerId=${providerId}`)\n .then(response => {\n setModels(response.data);\n })\n .catch(error => {\n toast.error('Get Models Error', { duration: 3000 });\n });\n };\n\n //同步模型列表\n const refreshProviderModels = async () => {\n let data = await getNewModels();\n if (!data) return;\n if (data.length > 0) {\n setModels(data);\n toast.success('Refresh Success', { duration: 3000 });\n const newModelsData = await axios.post('/api/llm/model', {\n newModels: data,\n providerId: selectedProvider.id\n });\n if (newModelsData.status === 200) {\n toast.success('Get Model Success', { duration: 3000 });\n }\n } else {\n toast.info('No Models Need Refresh', { duration: 3000 });\n }\n };\n\n //获取最新模型列表\n async function getNewModels() {\n try {\n if (!modelConfigForm || !modelConfigForm.endpoint) {\n return null;\n }\n const providerId = modelConfigForm.providerId;\n console.log(providerId, 'getNewModels providerId');\n\n // 使用后端 API 代理请求\n const res = await axios.post('/api/llm/fetch-models', {\n endpoint: modelConfigForm.endpoint,\n providerId: providerId,\n apiKey: modelConfigForm.apiKey\n });\n\n return res.data;\n } catch (err) {\n if (err.response && err.response.status === 401) {\n toast.error('API Key Invalid', { duration: 3000 });\n } else {\n toast.error('Get Model List Error', { duration: 3000 });\n }\n return null;\n }\n }\n\n // 打开模型对话框\n const handleOpenModelDialog = (model = null) => {\n if (model) {\n console.log('handleOpenModelDialog', model);\n setModelConfigForm(model);\n getProviderModels(model.providerId);\n } else {\n setModelConfigForm({\n ...modelConfigForm,\n apiKey: '',\n ...DEFAULT_MODEL_SETTINGS,\n id: ''\n });\n }\n setOpenModelDialog(true);\n };\n\n // 关闭模型对话框\n const handleCloseModelDialog = () => {\n setOpenModelDialog(false);\n };\n\n // 处理模型表单变更\n const handleModelFormChange = e => {\n const { name, value } = e.target;\n console.log('handleModelFormChange', name, value);\n setModelConfigForm(prev => ({\n ...prev,\n [name]: value\n }));\n };\n\n // 保存模型\n const handleSaveModel = () => {\n axios\n .post(`/api/projects/${projectId}/model-config`, modelConfigForm)\n .then(response => {\n if (selectedModelInfo && selectedModelInfo.id === response.data.id) {\n setSelectedModelInfo(response.data);\n }\n toast.success(t('settings.saveSuccess'), { duration: 3000 });\n getModelConfigList();\n handleCloseModelDialog();\n })\n .catch(error => {\n toast.error(t('settings.saveFailed'));\n console.error(error);\n });\n };\n\n // 删除模型\n const handleDeleteModel = id => {\n axios\n .delete(`/api/projects/${projectId}/model-config/${id}`)\n .then(response => {\n toast.success(t('settings.deleteSuccess'), { duration: 3000 });\n getModelConfigList();\n })\n .catch(error => {\n toast.error(t('settings.deleteFailed'), { duration: 3000 });\n });\n };\n\n // 获取模型状态图标和颜色\n const getModelStatusInfo = model => {\n if (model.providerId.toLowerCase() === 'ollama') {\n return {\n icon: ,\n color: 'success',\n text: t('models.localModel')\n };\n } else if (model.apiKey) {\n return {\n icon: ,\n color: 'success',\n text: t('models.apiKeyConfigured')\n };\n } else {\n return {\n icon: ,\n color: 'warning',\n text: t('models.apiKeyNotConfigured')\n };\n }\n };\n\n if (loading) {\n return {t('textSplit.loading')};\n }\n\n return (\n \n \n \n \n \n }\n onClick={() => router.push(`/projects/${projectId}/playground`)}\n size=\"small\"\n sx={{ textTransform: 'none' }}\n >\n {t('playground.title')}\n \n }\n onClick={() => handleOpenModelDialog()}\n size=\"small\"\n sx={{ textTransform: 'none' }}\n >\n {t('models.add')}\n \n \n \n\n \n {modelConfigList.map(model => (\n \n \n \n \n \n \n {model.modelName ? model.modelName : t('models.unselectedModel')}\n \n \n {model.providerName}\n \n \n \n\n \n \n \n \n \n \n \n \n router.push(`/projects/${projectId}/playground?modelId=${model.id}`)}\n color=\"secondary\"\n >\n \n \n \n\n \n handleOpenModelDialog(model)} color=\"primary\">\n \n \n \n\n \n handleDeleteModel(model.id)}\n disabled={modelConfigList.length <= 1}\n color=\"error\"\n >\n \n \n \n \n \n \n ))}\n \n \n\n {/* 模型表单对话框 */}\n \n {editingModel ? t('models.edit') : t('models.add')}\n \n \n {/*ai提供商*/}\n \n \n option.label}\n value={\n providerOptions.find(p => p.id === modelConfigForm.providerId) || {\n id: 'custom',\n label: modelConfigForm.providerName || ''\n }\n }\n onChange={onChangeProvider}\n renderInput={params => (\n {\n // 当用户手动输入时,更新 provider 字段\n setModelConfigForm(prev => ({\n ...prev,\n providerId: 'custom',\n providerName: e.target.value\n }));\n }}\n />\n )}\n renderOption={(props, option) => {\n return (\n
\n
\n \n {option.label}\n
\n
\n );\n }}\n />\n
\n
\n {/*接口地址*/}\n \n \n \n {/*api密钥*/}\n \n \n \n {/*模型列表*/}\n \n \n model && model.modelName)\n .map(model => ({\n label: model.modelName,\n id: model.id,\n modelId: model.modelId,\n providerId: model.providerId\n }))}\n value={modelConfigForm.modelName}\n onChange={(event, newValue) => {\n console.log('newValue', newValue);\n setModelConfigForm(prev => ({\n ...prev,\n modelName: newValue?.label,\n modelId: newValue?.modelId ? newValue?.modelId : newValue?.label\n }));\n }}\n renderInput={params => (\n {\n setModelConfigForm(prev => ({\n ...prev,\n modelName: e.target.value\n }));\n }}\n />\n )}\n />\n \n \n \n {/* 新增:视觉模型选择项 */}\n \n \n {t('models.type')}\n \n {t('models.text')}\n {t('models.vision')}\n \n \n \n \n \n {t('models.temperature')}\n \n\n \n \n \n {modelConfigForm.temperature}\n \n \n \n \n \n {t('models.maxTokens')}\n \n\n \n \n \n {modelConfigForm.maxTokens}\n \n \n \n
\n
\n \n \n \n {t('common.save')}\n \n \n
\n
\n );\n}\n"], ["/easy-dataset/components/text-split/components/TabPanel.js", "'use client';\n\nimport { Box } from '@mui/material';\n\n/**\n * 标签页面板组件\n * @param {Object} props\n * @param {number} props.value - 当前激活的标签索引\n * @param {number} props.index - 当前面板对应的索引\n * @param {ReactNode} props.children - 子组件\n */\nexport default function TabPanel({ value, index, children }) {\n return (\n