{"repo_name": "easy-dataset", "file_name": "/easy-dataset/lib/llm/core/index.js", "inference_info": {"prefix_code": "/**\n * LLM API 统一调用工具类\n * 支持多种模型提供商:OpenAI、Ollama、智谱AI等\n * 支持普通输出和流式输出\n */\nimport { DEFAULT_MODEL_SETTINGS } from '@/constant/model';\nimport { extractThinkChain, extractAnswer } from '@/lib/llm/common/util';\nconst OllamaClient = require('./providers/ollama'); // 导入 OllamaClient\nconst OpenAIClient = require('./providers/openai'); // 导入 OpenAIClient\nconst ZhiPuClient = require('./providers/zhipu'); // 导入 ZhiPuClient\nconst OpenRouterClient = require('./providers/openrouter');\n\n", "suffix_code": "\n\nmodule.exports = LLMClient;\n", "middle_code": "class LLMClient {\n constructor(config = {}) {\n this.config = {\n provider: config.providerId || 'openai',\n endpoint: this._handleEndpoint(config.providerId, config.endpoint) || '',\n apiKey: config.apiKey || '',\n model: config.modelName || '',\n temperature: config.temperature || DEFAULT_MODEL_SETTINGS.temperature,\n maxTokens: config.maxTokens || DEFAULT_MODEL_SETTINGS.maxTokens,\n max_tokens: config.maxTokens || DEFAULT_MODEL_SETTINGS.maxTokens\n };\n if (config.topP !== 0) {\n this.config.topP = config.topP;\n }\n if (config.topK !== 0) {\n this.config.topK = config.topK;\n }\n this.client = this._createClient(this.config.provider, this.config);\n }\n _handleEndpoint(provider, endpoint) {\n if (provider.toLowerCase() === 'ollama') {\n if (endpoint.endsWith('v1/') || endpoint.endsWith('v1')) {\n return endpoint.replace('v1', 'api');\n }\n }\n if (endpoint.includes('/chat/completions')) {\n return endpoint.replace('/chat/completions', '');\n }\n return endpoint;\n }\n _createClient(provider, config) {\n const clientMap = {\n ollama: OllamaClient,\n openai: OpenAIClient,\n siliconflow: OpenAIClient,\n deepseek: OpenAIClient,\n zhipu: ZhiPuClient,\n openrouter: OpenRouterClient\n };\n const ClientClass = clientMap[provider.toLowerCase()] || OpenAIClient;\n return new ClientClass(config);\n }\n async _callClientMethod(method, ...args) {\n try {\n return await this.client[method](...args);\n } catch (error) {\n console.error(`${this.config.provider} API 调用出错:`, error);\n throw error;\n }\n }\n async chat(prompt, options = {}) {\n const messages = Array.isArray(prompt) ? prompt : [{ role: 'user', content: prompt }];\n options = {\n ...options,\n ...this.config\n };\n return this._callClientMethod('chat', messages, options);\n }\n async chatStreamAPI(prompt, options = {}) {\n const messages = Array.isArray(prompt) ? prompt : [{ role: 'user', content: prompt }];\n options = {\n ...options,\n ...this.config\n };\n return this._callClientMethod('chatStreamAPI', messages, options);\n }\n async chatStream(prompt, options = {}) {\n const messages = Array.isArray(prompt) ? prompt : [{ role: 'user', content: prompt }];\n options = {\n ...options,\n ...this.config\n };\n return this._callClientMethod('chatStream', messages, options);\n }\n async getResponse(prompt, options = {}) {\n const llmRes = await this.chat(prompt, options);\n return llmRes.text || llmRes.response.messages || '';\n }\n async getResponseWithCOT(prompt, options = {}) {\n const llmRes = await this.chat(prompt, options);\n let answer = llmRes.text || '';\n let cot = llmRes.reasoning || '';\n if ((answer && answer.startsWith('')) || answer.startsWith('')) {\n cot = extractThinkChain(answer);\n answer = extractAnswer(answer);\n } else if (\n llmRes?.response?.body?.choices?.length > 0 &&\n llmRes.response.body.choices[0].message.reasoning_content\n ) {\n if (llmRes.response.body.choices[0].message.reasoning_content) {\n cot = llmRes.response.body.choices[0].message.reasoning_content;\n }\n if (llmRes.response.body.choices[0].message.content) {\n answer = llmRes.response.body.choices[0].message.content;\n }\n }\n if (answer.startsWith('\\n\\n')) {\n answer = answer.slice(2);\n }\n if (cot.endsWith('\\n\\n')) {\n cot = cot.slice(0, -2);\n }\n return { answer, cot };\n }\n}", "code_description": null, "fill_type": "CLASS_TYPE", "language_type": "javascript", "sub_task_type": null}, "context_code": [["/easy-dataset/lib/llm/core/providers/base.js", "import { generateText, streamText } from 'ai';\n\nclass BaseClient {\n constructor(config) {\n this.endpoint = config.endpoint || '';\n this.apiKey = config.apiKey || '';\n this.model = config.model || '';\n this.modelConfig = {\n temperature: config.temperature || 0.7,\n top_p: config.top_p || 0.9,\n max_tokens: config.max_tokens || 8192\n };\n }\n\n /**\n * chat(普通输出)\n */\n async chat(messages, options) {\n const lastMessage = messages[messages.length - 1];\n const prompt = lastMessage.content;\n const model = this._getModel();\n const result = await generateText({\n model,\n messages: this._convertJson(messages),\n temperature: options.temperature || this.modelConfig.temperature,\n topP: options.top_p || this.modelConfig.top_p,\n maxTokens: options.max_tokens || this.modelConfig.max_tokens\n });\n return result;\n }\n\n /**\n * chat(流式输出)\n */\n async chatStream(messages, options) {\n const lastMessage = messages[messages.length - 1];\n const prompt = lastMessage.content;\n const model = this._getModel();\n const stream = streamText({\n model,\n messages: this._convertJson(messages),\n temperature: options.temperature || this.modelConfig.temperature,\n topP: options.top_p || this.modelConfig.top_p,\n maxTokens: options.max_tokens || this.modelConfig.max_tokens\n });\n return stream.toTextStreamResponse();\n }\n\n // 抽象方法\n _getModel() {\n throw new Error('_getModel 子类方法必须实现');\n }\n\n /**\n * chat(纯API流式输出)\n */\n async chatStreamAPI(messages, options) {\n const model = this._getModel();\n const modelName = typeof model === 'function' ? model.modelName : this.model;\n\n // 构建请求数据\n const payload = {\n model: modelName,\n messages: this._convertJson(messages),\n temperature: options.temperature || this.modelConfig.temperature,\n top_p: options.top_p || this.modelConfig.top_p,\n max_tokens: options.max_tokens || this.modelConfig.max_tokens,\n stream: true // 开启流式输出\n };\n\n // 添加思维链相关参数\n payload.send_reasoning = true;\n payload.reasoning = true;\n\n try {\n // 发起流式请求\n const response = await fetch(\n `${this.endpoint.endsWith('/') ? this.endpoint : `${this.endpoint}/`}chat/completions`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`\n },\n body: JSON.stringify(payload)\n }\n );\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`API请求失败: ${response.status} ${response.statusText}\\n${errorText}`);\n }\n\n if (!response.body) {\n throw new Error('响应中没有可读取的数据流');\n }\n\n // 处理原始数据流,实现思维链的流式输出\n const reader = response.body.getReader();\n const encoder = new TextEncoder();\n const decoder = new TextDecoder();\n\n // 创建一个新的可读流\n const newStream = new ReadableStream({\n async start(controller) {\n let buffer = '';\n let isThinking = false; // 当前是否在输出思维链模式\n let pendingReasoning = null; // 等待输出的思维链\n\n // 输出文本内容\n const sendContent = text => {\n if (!text) return;\n\n // 如果正在输出思维链,需要先关闭思维链标签\n if (isThinking) {\n controller.enqueue(encoder.encode(''));\n isThinking = false;\n }\n\n controller.enqueue(encoder.encode(text));\n };\n\n // 流式输出思维链\n const sendReasoning = text => {\n if (!text) return;\n\n // 如果还没有开始思维链输出,需要先添加思维链标签\n if (!isThinking) {\n controller.enqueue(encoder.encode(''));\n isThinking = true;\n }\n\n controller.enqueue(encoder.encode(text));\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n // 流结束时,如果还在思维链模式,关闭标签\n if (isThinking) {\n controller.enqueue(encoder.encode(''));\n }\n controller.close();\n break;\n }\n\n // 解析数据块\n const chunk = decoder.decode(value, { stream: true });\n buffer += chunk;\n\n // 处理数据行\n let boundary = buffer.indexOf('\\n');\n while (boundary !== -1) {\n const line = buffer.substring(0, boundary).trim();\n buffer = buffer.substring(boundary + 1);\n\n if (line.startsWith('data:') && !line.includes('[DONE]')) {\n try {\n // 解析JSON数据\n const jsonData = JSON.parse(line.substring(5).trim());\n const deltaContent = jsonData.choices?.[0]?.delta?.content;\n const deltaReasoning = jsonData.choices?.[0]?.delta?.reasoning_content;\n\n // 如果有思维链内容,则实时流式输出\n if (deltaReasoning) {\n sendReasoning(deltaReasoning);\n }\n\n // 如果有正文内容也实时输出\n if (deltaContent !== undefined && deltaContent !== null) {\n sendContent(deltaContent);\n }\n } catch (e) {\n // 忽略 JSON 解析错误\n console.error('解析响应数据出错:', e);\n }\n } else if (line.includes('[DONE]')) {\n // 数据流结束,如果还在思维链模式,需要关闭思维链标签\n if (isThinking) {\n controller.enqueue(encoder.encode(''));\n isThinking = false;\n }\n }\n\n boundary = buffer.indexOf('\\n');\n }\n }\n } catch (error) {\n console.error('处理数据流时出错:', error);\n // 如果出错时正在输出思维链,要关闭思维链标签\n if (isThinking) {\n try {\n controller.enqueue(encoder.encode(''));\n } catch (e) {\n console.error('关闭思维链标签出错:', e);\n }\n }\n controller.error(error);\n }\n }\n });\n\n // 最终返回响应流\n return new Response(newStream, {\n headers: {\n 'Content-Type': 'text/plain', // 纯文本格式\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive'\n }\n });\n } catch (error) {\n console.error('流式API调用出错:', error);\n throw error;\n }\n }\n\n _convertJson(data) {\n return data.map(item => {\n // 只处理 role 为 \"user\" 的项\n if (item.role !== 'user') return item;\n\n const newItem = {\n role: 'user',\n content: '',\n experimental_attachments: [],\n parts: []\n };\n\n // 情况1:content 是字符串\n if (typeof item.content === 'string') {\n newItem.content = item.content;\n newItem.parts.push({\n type: 'text',\n text: item.content\n });\n }\n // 情况2:content 是数组\n else if (Array.isArray(item.content)) {\n item.content.forEach(contentItem => {\n if (contentItem.type === 'text') {\n // 文本内容\n newItem.content = contentItem.text;\n newItem.parts.push({\n type: 'text',\n text: contentItem.text\n });\n } else if (contentItem.type === 'image_url') {\n // 图片内容\n const imageUrl = contentItem.image_url.url;\n\n // 提取文件名(如果没有则使用默认名)\n let fileName = 'image.jpg';\n if (imageUrl.startsWith('data:')) {\n // 如果是 base64 数据,尝试从 content type 获取扩展名\n const match = imageUrl.match(/^data:image\\/(\\w+);base64/);\n if (match) {\n fileName = `image.${match[1]}`;\n }\n }\n\n newItem.experimental_attachments.push({\n url: imageUrl,\n name: fileName,\n contentType: imageUrl.startsWith('data:') ? imageUrl.split(';')[0].replace('data:', '') : 'image/jpeg' // 默认为 jpeg\n });\n }\n });\n }\n\n return newItem;\n });\n }\n}\n\nmodule.exports = BaseClient;\n"], ["/easy-dataset/lib/llm/core/providers/ollama.js", "import { createOllama } from 'ollama-ai-provider';\nimport BaseClient from './base.js';\n\nclass OllamaClient extends BaseClient {\n constructor(config) {\n super(config);\n this.ollama = createOllama({\n baseURL: this.endpoint,\n apiKey: this.apiKey\n });\n }\n\n _getModel() {\n return this.ollama(this.model);\n }\n\n /**\n * 获取本地可用的模型列表\n * @returns {Promise} 返回模型列表\n */\n async getModels() {\n try {\n const response = await fetch(this.endpoint + '/tags');\n const data = await response.json();\n // 处理响应,提取模型名称\n if (data && data.models) {\n return data.models.map(model => ({\n name: model.name,\n modified_at: model.modified_at,\n size: model.size\n }));\n }\n return [];\n } catch (error) {\n console.error('Fetch error:', error);\n }\n }\n\n async chatStreamAPI(messages, options) {\n const model = this._getModel();\n const modelName = typeof model === 'function' ? model.modelName : this.model;\n\n // 构建符合 Ollama API 的请求数据\n const payload = {\n model: modelName,\n messages: this._convertJson(messages),\n stream: true, // 开启流式输出\n options: {\n temperature: options.temperature || this.modelConfig.temperature,\n top_p: options.top_p || this.modelConfig.top_p,\n num_predict: options.max_tokens || this.modelConfig.max_tokens\n }\n };\n\n if (this.endpoint.endsWith('/api')) {\n this.endpoint = this.endpoint.slice(0, -4);\n }\n\n try {\n // 发起流式请求\n const response = await fetch(`${this.endpoint.endsWith('/') ? this.endpoint : `${this.endpoint}/`}api/chat`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(payload)\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`API请求失败: ${response.status} ${response.statusText}\\n${errorText}`);\n }\n\n if (!response.body) {\n throw new Error('响应中没有可读取的数据流');\n }\n\n // 处理原始数据流,实现思维链的流式输出\n const reader = response.body.getReader();\n const encoder = new TextEncoder();\n const decoder = new TextDecoder();\n\n // 创建一个新的可读流\n const newStream = new ReadableStream({\n async start(controller) {\n let buffer = '';\n let isThinking = false; // 当前是否在输出思维链模式\n let pendingReasoning = null; // 等待输出的思维链\n\n // 输出文本内容\n const sendContent = text => {\n if (!text) return;\n\n // 如果正在输出思维链,需要先关闭思维链标签\n if (isThinking) {\n controller.enqueue(encoder.encode(''));\n isThinking = false;\n }\n\n controller.enqueue(encoder.encode(text));\n };\n\n // 流式输出思维链\n const sendReasoning = text => {\n if (!text) return;\n\n // 如果还没有开始思维链输出,需要先添加思维链标签\n if (!isThinking) {\n controller.enqueue(encoder.encode(''));\n isThinking = true;\n }\n\n controller.enqueue(encoder.encode(text));\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n // 流结束时,如果还在思维链模式,关闭标签\n if (isThinking) {\n controller.enqueue(encoder.encode(''));\n }\n controller.close();\n break;\n }\n\n // 解析数据块\n const chunk = decoder.decode(value, { stream: true });\n buffer += chunk;\n\n // 处理数据行\n let boundary = buffer.indexOf('\\n');\n while (boundary !== -1) {\n const line = buffer.substring(0, boundary).trim();\n buffer = buffer.substring(boundary + 1);\n\n if (line) {\n try {\n // 解析JSON数据\n const jsonData = JSON.parse(line);\n const deltaContent = jsonData.message?.content;\n const deltaReasoning = jsonData.message?.thinking;\n\n // 如果有思维链内容,则实时流式输出\n if (deltaReasoning) {\n sendReasoning(deltaReasoning);\n }\n\n // 如果有正文内容也实时输出\n if (deltaContent !== undefined && deltaContent !== null) {\n sendContent(deltaContent);\n }\n } catch (e) {\n // 忽略 JSON 解析错误\n console.error('解析响应数据出错:', e);\n }\n }\n\n boundary = buffer.indexOf('\\n');\n }\n }\n } catch (error) {\n console.error('处理数据流时出错:', error);\n // 如果出错时正在输出思维链,要关闭思维链标签\n if (isThinking) {\n try {\n controller.enqueue(encoder.encode(''));\n } catch (e) {\n console.error('关闭思维链标签出错:', e);\n }\n }\n controller.error(error);\n }\n }\n });\n\n // 最终返回响应流\n return new Response(newStream, {\n headers: {\n 'Content-Type': 'text/plain', // 纯文本格式\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive'\n }\n });\n } catch (error) {\n console.error('流式API调用出错:', error);\n throw error;\n }\n }\n}\n\nmodule.exports = OllamaClient;\n"], ["/easy-dataset/lib/services/datasets/index.js", "import { getQuestionById, updateQuestion } from '@/lib/db/questions';\nimport {\n createDataset,\n deleteDataset,\n getDatasetsById,\n getDatasetsByPagination,\n getDatasetsIds,\n updateDataset\n} from '@/lib/db/datasets';\nimport { getProject } from '@/lib/db/projects';\nimport getAnswerPrompt from '@/lib/llm/prompts/answer';\nimport getAnswerEnPrompt from '@/lib/llm/prompts/answerEn';\nimport getEnhancedAnswerPrompt from '@/lib/llm/prompts/enhancedAnswer';\nimport getEnhancedAnswerEnPrompt from '@/lib/llm/prompts/enhancedAnswerEn';\nimport getOptimizeCotPrompt from '@/lib/llm/prompts/optimizeCot';\nimport getOptimizeCotEnPrompt from '@/lib/llm/prompts/optimizeCotEn';\nimport { getChunkById } from '@/lib/db/chunks';\nimport { getActiveGaPairsByFileId } from '@/lib/db/ga-pairs';\nimport { nanoid } from 'nanoid';\nimport LLMClient from '@/lib/llm/core/index';\nimport logger from '@/lib/util/logger';\n\n/**\n * 优化思维链\n * @param {string} originalQuestion - 原始问题\n * @param {string} answer - 答案\n * @param {string} originalCot - 原始思维链\n * @param {string} language - 语言\n * @param {object} llmClient - LLM客户端\n * @param {string} id - 数据集ID\n * @param {string} projectId - 项目ID\n */\nasync function optimizeCot(originalQuestion, answer, originalCot, language, llmClient, id, projectId) {\n try {\n const prompt =\n language === 'en'\n ? getOptimizeCotEnPrompt(originalQuestion, answer, originalCot)\n : getOptimizeCotPrompt(originalQuestion, answer, originalCot);\n const { answer: as, cot } = await llmClient.getResponseWithCOT(prompt);\n const optimizedAnswer = as || cot;\n const result = await updateDataset({ id, cot: optimizedAnswer.replace('优化后的思维链', '') });\n logger.info(`成功优化思维链: ${originalQuestion}, ID: ${id}`);\n return result;\n } catch (error) {\n logger.error(`优化思维链失败: ${error.message}`);\n throw error;\n }\n}\n\n/**\n * 为单个问题生成答案并创建数据集\n * @param {string} projectId - 项目ID\n * @param {string} questionId - 问题ID\n * @param {object} options - 选项\n * @param {string} options.model - 模型名称\n * @param {string} options.language - 语言(中文/en)\n * @returns {Promise} 生成的数据集\n */\nexport async function generateDatasetForQuestion(projectId, questionId, options) {\n try {\n const { model, language = '中文' } = options;\n\n // 验证参数\n if (!projectId || !questionId || !model) {\n throw new Error('缺少必要参数');\n }\n\n // 获取问题\n const question = await getQuestionById(questionId);\n if (!question) {\n throw new Error('问题不存在');\n }\n\n // 获取文本块内容\n const chunk = await getChunkById(question.chunkId);\n if (!chunk) {\n throw new Error('文本块不存在');\n }\n const idDistill = chunk.name === 'Distilled Content';\n\n // 获取项目配置\n const project = await getProject(projectId);\n const { globalPrompt, answerPrompt } = project;\n\n // 创建LLM客户端\n const llmClient = new LLMClient(model);\n let activeGaPairs = [];\n let questionLinkedGaPair = null;\n let useEnhancedPrompt = false;\n\n if (chunk.fileId && !idDistill) {\n try {\n activeGaPairs = await getActiveGaPairsByFileId(chunk.fileId);\n\n // 优先检查问题是否关联了特定的GA pair\n if (question.gaPairId) {\n questionLinkedGaPair = activeGaPairs.find(ga => ga.id === question.gaPairId);\n if (questionLinkedGaPair) {\n useEnhancedPrompt = true;\n logger.info(`问题关联GA pair: ${questionLinkedGaPair.genreTitle}+${questionLinkedGaPair.audienceTitle}`);\n }\n }\n\n logger.info(`检查到激活的GA对,${useEnhancedPrompt ? '使用' : '不使用'}增强提示词`);\n } catch (error) {\n logger.warn(`获取GA pairs失败,使用标准提示词: ${error.message}`);\n useEnhancedPrompt = false;\n }\n }\n\n let prompt;\n\n if (idDistill) {\n // 对于精炼内容,直接使用问题\n prompt = question.question;\n } else if (useEnhancedPrompt) {\n // 使用MGA增强提示词\n const enhancedPromptFunc = language === 'en' ? getEnhancedAnswerEnPrompt : getEnhancedAnswerPrompt;\n\n //使用问题关联的GA pair\n let primaryGaPair;\n\n primaryGaPair = {\n genre: `${questionLinkedGaPair.genreTitle}: ${questionLinkedGaPair.genreDesc}`,\n audience: `${questionLinkedGaPair.audienceTitle}: ${questionLinkedGaPair.audienceDesc}`,\n active: questionLinkedGaPair.isActive\n };\n logger.info(`使用问题关联的GA pair: ${primaryGaPair.genre} | ${primaryGaPair.audience}`);\n\n prompt = enhancedPromptFunc({\n text: chunk.content,\n question: question.question,\n globalPrompt,\n answerPrompt,\n activeGaPair: primaryGaPair\n });\n\n logger.info(`使用MGA增强提示词生成答案`);\n } else {\n // 使用标准提示词\n const promptFunc = language === 'en' ? getAnswerEnPrompt : getAnswerPrompt;\n prompt = promptFunc({\n text: chunk.content,\n question: question.question,\n globalPrompt,\n answerPrompt\n });\n\n logger.info('使用标准提示词生成答案');\n }\n\n // 调用大模型生成答案\n const { answer, cot } = await llmClient.getResponseWithCOT(prompt);\n\n const datasetId = nanoid(12);\n\n // 创建新的数据集项\n const datasets = {\n id: datasetId,\n projectId: projectId,\n question: question.question,\n answer: answer,\n model: model.modelName,\n cot: cot,\n questionLabel: question.label || null\n };\n\n let chunkData = await getChunkById(question.chunkId);\n datasets.chunkName = chunkData.name;\n datasets.chunkContent = ''; // 不再保存原始文本块内容\n datasets.questionId = question.id;\n\n let dataset = await createDataset(datasets);\n if (cot && !idDistill) {\n // 为了性能考虑,这里异步优化\n optimizeCot(question.question, answer, cot, language, llmClient, datasetId, projectId);\n }\n if (dataset) {\n await updateQuestion({ id: questionId, answered: true });\n }\n\n const logMessage = useEnhancedPrompt\n ? `成功生成MGA增强数据集: ${question.question}`\n : `成功生成标准数据集: ${question.question}`;\n logger.info(logMessage);\n\n return {\n success: true,\n dataset,\n mgaEnhanced: useEnhancedPrompt,\n activePairs: activeGaPairs.length\n };\n } catch (error) {\n logger.error(`生成数据集失败: ${error.message}`);\n throw error;\n }\n}\n\nexport default {\n generateDatasetForQuestion,\n optimizeCot\n};\n"], ["/easy-dataset/lib/util/domain-tree.js", "/**\n * 领域树处理模块\n * 用于处理领域树的生成、修订和管理\n */\nconst LLMClient = require('../llm/core/index');\nconst getLabelPrompt = require('../llm/prompts/label');\nconst getLabelEnPrompt = require('../llm/prompts/labelEn');\nconst getLabelRevisePrompt = require('../llm/prompts/labelRevise');\nconst getLabelReviseEnPrompt = require('../llm/prompts/labelReviseEn');\nconst { getProjectTocs } = require('../file/text-splitter');\nconst { getTags, batchSaveTags } = require('../db/tags');\nconst { extractJsonFromLLMOutput } = require('../llm/common/util');\nconst { filterDomainTree } = require('./file');\n\n/**\n * 处理领域树生成或更新\n * @param {Object} options - 配置选项\n * @param {string} options.projectId - 项目ID\n * @param {string} options.action - 操作类型: 'rebuild', 'revise', 'keep'\n * @param {string} options.toc - 所有文档的目录结构\n * @param {Object} options.model - 使用的模型信息\n * @param {string} options.language - 语言: 'en' 或 '中文'\n * @param {string} options.fileName - 文件名(用于新增文件时获取内容)\n * @param {string} options.deletedContent - 被删除的文件内容(用于删除文件时)\n * @param {Object} options.project - 项目信息,包含 globalPrompt 和 domainTreePrompt\n * @returns {Promise} 生成的领域树标签\n */\nasync function handleDomainTree({\n projectId,\n action = 'rebuild',\n allToc,\n newToc,\n model,\n language = '中文',\n deleteToc = null,\n project\n}) {\n // 如果是保持不变,直接返回现有标签\n if (action === 'keep') {\n console.log(`[${projectId}] Using existing domain tree`);\n return await getTags(projectId);\n }\n\n const isEnglish = language === 'en';\n const { globalPrompt, domainTreePrompt } = project || {};\n\n try {\n if (!allToc) {\n allToc = await getProjectTocs(projectId);\n }\n\n const llmClient = new LLMClient(model);\n let tags, prompt, response;\n // 重建领域树\n if (action === 'rebuild') {\n console.log(`[${projectId}] Rebuilding domain tree`);\n const promptFunc = isEnglish ? getLabelEnPrompt : getLabelPrompt;\n prompt = promptFunc({ text: allToc, globalPrompt, domainTreePrompt });\n console.log('rebuild', prompt);\n response = await llmClient.getResponse(prompt);\n tags = extractJsonFromLLMOutput(response);\n console.log('rebuild tags', tags);\n }\n // 修订领域树\n else if (action === 'revise') {\n console.log(`[${projectId}] Revising domain tree`);\n // 获取现有的领域树\n const existingTags = await getTags(projectId);\n\n if (!existingTags || existingTags.length === 0) {\n // 如果没有现有领域树,就像重建一样处理\n const promptFunc = isEnglish ? getLabelEnPrompt : getLabelPrompt;\n prompt = promptFunc({ text: allToc, globalPrompt, domainTreePrompt });\n } else {\n // 增量更新领域树的逻辑\n const promptFunc = isEnglish ? getLabelReviseEnPrompt : getLabelRevisePrompt;\n\n prompt = promptFunc({\n text: allToc,\n existingTags: filterDomainTree(existingTags),\n newContent: newToc,\n deletedContent: deleteToc,\n globalPrompt,\n domainTreePrompt\n });\n }\n\n // console.log('revise', prompt);\n\n response = await llmClient.getResponse(prompt);\n tags = extractJsonFromLLMOutput(response);\n\n // console.log('revise tags', tags);\n }\n\n // 保存领域树标签(如果生成成功)\n if (tags && tags.length > 0 && action !== 'keep') {\n await batchSaveTags(projectId, tags);\n } else if (!tags && action !== 'keep') {\n console.error(`[${projectId}] Failed to generate domain tree tags`);\n }\n\n return tags;\n } catch (error) {\n console.error(`[${projectId}] Error handling domain tree: ${error.message}`);\n throw error;\n }\n}\n\nmodule.exports = {\n handleDomainTree\n};\n"], ["/easy-dataset/lib/services/questions/index.js", "import LLMClient from '@/lib/llm/core/index';\nimport getQuestionPrompt from '@/lib/llm/prompts/question';\nimport getQuestionEnPrompt from '@/lib/llm/prompts/questionEn';\nimport getAddLabelPrompt from '@/lib/llm/prompts/addLabel';\nimport getAddLabelEnPrompt from '@/lib/llm/prompts/addLabelEn';\nimport { extractJsonFromLLMOutput } from '@/lib/llm/common/util';\nimport { getTaskConfig, getProject } from '@/lib/db/projects';\nimport { getTags } from '@/lib/db/tags';\nimport { getChunkById } from '@/lib/db/chunks';\nimport { saveQuestions, saveQuestionsWithGaPair } from '@/lib/db/questions';\nimport { getActiveGaPairsByFileId } from '@/lib/db/ga-pairs';\nimport logger from '@/lib/util/logger';\n\n/**\n * 随机移除问题中的问号\n * @param {Array} questions 问题列表\n * @param {Number} probability 移除概率(0-100)\n * @returns {Array} 处理后的问题列表\n */\nfunction randomRemoveQuestionMark(questions, questionMaskRemovingProbability) {\n for (let i = 0; i < questions.length; i++) {\n // 去除问题结尾的空格\n let question = questions[i].trimEnd();\n\n if (Math.random() * 100 < questionMaskRemovingProbability && (question.endsWith('?') || question.endsWith('?'))) {\n question = question.slice(0, -1);\n }\n questions[i] = question;\n }\n return questions;\n}\n\n/**\n * 为指定文本块生成问题\n * @param {String} projectId 项目ID\n * @param {String} chunkId 文本块ID\n * @param {Object} options 选项\n * @param {String} options.model 模型名称\n * @param {String} options.language 语言(中文/en)\n * @param {Number} options.number 问题数量(可选)\n * @returns {Promise} 生成结果\n */\nexport async function generateQuestionsForChunk(projectId, chunkId, options) {\n try {\n const { model, language = '中文', number } = options;\n\n if (!model) {\n throw new Error('模型名称不能为空');\n }\n\n // 并行获取文本块内容和项目配置\n const [chunk, taskConfig, project] = await Promise.all([\n getChunkById(chunkId),\n getTaskConfig(projectId),\n getProject(projectId)\n ]);\n\n if (!chunk) {\n throw new Error('文本块不存在');\n }\n\n // 获取项目配置信息\n const { questionGenerationLength, questionMaskRemovingProbability = 60 } = taskConfig;\n const { globalPrompt, questionPrompt } = project;\n\n // 创建LLM客户端\n const llmClient = new LLMClient(model);\n // 生成问题的数量,如果未指定,则根据文本长度自动计算\n const questionNumber = number || Math.floor(chunk.content.length / questionGenerationLength);\n\n // 根据语言选择相应的提示词函数\n const promptFunc = language === 'en' ? getQuestionEnPrompt : getQuestionPrompt;\n const prompt = promptFunc({\n text: chunk.content,\n number: questionNumber,\n language,\n globalPrompt,\n questionPrompt\n });\n const response = await llmClient.getResponse(prompt);\n\n // 从LLM输出中提取JSON格式的问题列表\n const originalQuestions = extractJsonFromLLMOutput(response);\n const questions = randomRemoveQuestionMark(originalQuestions, questionMaskRemovingProbability);\n if (!questions || !Array.isArray(questions)) {\n throw new Error('生成问题失败');\n }\n\n // 先获取标签,确保 tags 在后续逻辑中可用\n const tags = await getTags(projectId);\n // 根据语言选择标签提示词函数\n const labelPromptFunc = language === 'en' ? getAddLabelEnPrompt : getAddLabelPrompt;\n const labelPrompt = labelPromptFunc(JSON.stringify(tags), JSON.stringify(questions));\n\n const labelResponse = await llmClient.getResponse(labelPrompt);\n const labelQuestions = extractJsonFromLLMOutput(labelResponse);\n\n // 保存问题到数据库\n await saveQuestions(projectId, labelQuestions, chunkId);\n\n // 返回生成的问题\n return {\n chunkId,\n labelQuestions,\n total: labelQuestions.length\n };\n } catch (error) {\n logger.error('生成问题时出错:', error);\n throw error;\n }\n}\n\nfunction extractLabels(data) {\n if (!Array.isArray(data)) {\n return [];\n }\n\n return data.map(item => {\n const result = {\n label: item.label\n };\n\n if (Array.isArray(item.child) && item.child.length > 0) {\n result.child = extractLabels(item.child);\n }\n\n return result;\n });\n}\n\n/**\n * 为指定文本块生成问题(支持GA增强)\n * @param {String} projectId 项目ID\n * @param {String} chunkId 文本块ID\n * @param {Object} options 选项\n * @param {String} options.model 模型名称\n * @param {String} options.language 语言(中文/en)\n * @param {Number} options.number 问题数量(可选)\n * @param {Boolean} options.enableGaExpansion 是否启用GA扩展生成\n * @returns {Promise} 生成结果\n */\nexport async function generateQuestionsForChunkWithGA(projectId, chunkId, options) {\n try {\n const { model, language = '中文', number } = options;\n\n if (!model) {\n throw new Error('模型名称不能为空');\n }\n\n // 并行获取文本块内容和项目配置\n const [chunk, taskConfig, project] = await Promise.all([\n getChunkById(chunkId),\n getTaskConfig(projectId),\n getProject(projectId)\n ]);\n\n if (!chunk) {\n throw new Error('文本块不存在');\n }\n\n // 获取项目配置信息\n const { questionGenerationLength, questionMaskRemovingProbability = 60 } = taskConfig;\n const { globalPrompt, questionPrompt } = project;\n\n // 检查是否有可用的GA pairs并且启用GA扩展\n let activeGaPairs = [];\n let useGaExpansion = false;\n\n if (chunk.fileId) {\n try {\n activeGaPairs = await getActiveGaPairsByFileId(chunk.fileId);\n useGaExpansion = activeGaPairs.length > 0;\n logger.info(`检查到 ${activeGaPairs.length} 个激活的GA pairs,${useGaExpansion ? '启用' : '不启用'}GA扩展生成`);\n } catch (error) {\n logger.warn(`获取GA pairs失败,使用标准生成: ${error.message}`);\n useGaExpansion = false;\n }\n }\n\n // 创建LLM客户端\n const llmClient = new LLMClient(model);\n\n // 计算基础问题数量\n const baseQuestionNumber = number || Math.floor(chunk.content.length / questionGenerationLength);\n\n let allGeneratedQuestions = [];\n let totalExpectedQuestions = baseQuestionNumber;\n\n if (useGaExpansion) {\n // GA扩展模式:为每个GA pair生成基础数量的问题\n totalExpectedQuestions = baseQuestionNumber * activeGaPairs.length;\n logger.info(\n `GA扩展模式:将生成${baseQuestionNumber} 基础问题 × ${activeGaPairs.length} GA pairs = ${totalExpectedQuestions}个总问题`\n );\n\n // 为每个GA pair生成问题\n for (const gaPair of activeGaPairs) {\n const activeGaPair = {\n genre: `${gaPair.genreTitle}: ${gaPair.genreDesc}`,\n audience: `${gaPair.audienceTitle}: ${gaPair.audienceDesc}`,\n active: gaPair.isActive\n };\n\n // 根据语言选择相应的提示词函数\n const promptFunc = language === 'en' ? getQuestionEnPrompt : getQuestionPrompt;\n const prompt = promptFunc({\n text: chunk.content,\n number: baseQuestionNumber,\n language,\n globalPrompt,\n questionPrompt,\n activeGaPair: activeGaPair\n });\n\n const response = await llmClient.getResponse(prompt);\n const originalQuestions = extractJsonFromLLMOutput(response);\n const questions = randomRemoveQuestionMark(originalQuestions, questionMaskRemovingProbability);\n\n if (!questions || !Array.isArray(questions)) {\n logger.warn(`GA pair ${gaPair.genreTitle}+${gaPair.audienceTitle} 生成问题失败,跳过`);\n continue;\n }\n\n // 为这批问题添加标签\n const tags = await getTags(projectId);\n const labelPromptFunc = language === 'en' ? getAddLabelEnPrompt : getAddLabelPrompt;\n const labelPrompt = labelPromptFunc(JSON.stringify(tags), JSON.stringify(questions));\n const labelResponse = await llmClient.getResponse(labelPrompt);\n const labelQuestions = extractJsonFromLLMOutput(labelResponse);\n\n // 保存问题到数据库(关联GA pair)\n await saveQuestionsWithGaPair(projectId, labelQuestions, chunkId, gaPair.id);\n\n allGeneratedQuestions.push(\n ...labelQuestions.map(q => ({\n ...q,\n gaPairId: gaPair.id,\n gaPairInfo: `${gaPair.genreTitle}+${gaPair.audienceTitle}`\n }))\n );\n\n logger.info(`GA pair ${gaPair.genreTitle}+${gaPair.audienceTitle} 生成了 ${labelQuestions.length} 个问题`);\n }\n } else {\n // 标准模式:使用原有逻辑\n logger.info(`标准模式:生成 ${baseQuestionNumber} 个问题`);\n\n const promptFunc = language === 'en' ? getQuestionEnPrompt : getQuestionPrompt;\n const prompt = promptFunc({\n text: chunk.content,\n number: baseQuestionNumber,\n language,\n globalPrompt,\n questionPrompt\n });\n\n const response = await llmClient.getResponse(prompt);\n const originalQuestions = extractJsonFromLLMOutput(response);\n const questions = randomRemoveQuestionMark(originalQuestions, questionMaskRemovingProbability);\n\n if (!questions || !Array.isArray(questions)) {\n throw new Error('生成问题失败');\n }\n\n // 添加标签\n const tags = extractLabels(await getTags(projectId));\n const labelPromptFunc = language === 'en' ? getAddLabelEnPrompt : getAddLabelPrompt;\n const labelPrompt = labelPromptFunc(JSON.stringify(tags), JSON.stringify(questions));\n const labelResponse = await llmClient.getResponse(labelPrompt);\n const labelQuestions = extractJsonFromLLMOutput(labelResponse);\n\n // 保存问题到数据库(不关联GA pair)\n await saveQuestions(projectId, labelQuestions, chunkId);\n\n allGeneratedQuestions = labelQuestions;\n }\n\n // 返回生成的问题\n return {\n chunkId,\n questions: allGeneratedQuestions,\n total: allGeneratedQuestions.length,\n expectedTotal: totalExpectedQuestions,\n gaExpansionUsed: useGaExpansion,\n gaPairsCount: activeGaPairs.length\n };\n } catch (error) {\n logger.error('GA增强问题生成时出错:', error);\n throw error;\n }\n}\n\nexport default {\n generateQuestionsForChunk,\n generateQuestionsForChunkWithGA\n};\n"], ["/easy-dataset/app/api/projects/[projectId]/playground/chat/route.js", "import { NextResponse } from 'next/server';\nimport LLMClient from '@/lib/llm/core/index';\n\nexport async function POST(request, { params }) {\n try {\n const { projectId } = params;\n\n // 验证项目ID\n if (!projectId) {\n return NextResponse.json({ error: 'The project ID cannot be empty' }, { status: 400 });\n }\n\n // 获取请求体\n const { model, messages } = await request.json();\n\n // 验证请求参数\n if (!model) {\n return NextResponse.json({ error: 'The model parameters cannot be empty' }, { status: 400 });\n }\n\n if (!Array.isArray(messages) || messages.length === 0) {\n return NextResponse.json({ error: 'The message list cannot be empty' }, { status: 400 });\n }\n\n // 使用自定义的LLM客户端\n const llmClient = new LLMClient(model);\n\n // 格式化消息历史\n const formattedMessages = messages.map(msg => {\n // 处理纯文本消息\n if (typeof msg.content === 'string') {\n return {\n role: msg.role,\n content: msg.content\n };\n }\n // 处理包含图片的复合消息(用于视觉模型)\n else if (Array.isArray(msg.content)) {\n return {\n role: msg.role,\n content: msg.content\n };\n }\n // 默认情况\n return {\n role: msg.role,\n content: msg.content\n };\n });\n\n // 调用LLM API\n let response = '';\n try {\n const { answer, cot } = await llmClient.getResponseWithCOT(formattedMessages);\n response = `${cot}${answer}`;\n } catch (error) {\n console.error('Failed to call LLM API:', String(error));\n return NextResponse.json(\n {\n error: `Failed to call ${model.provider} model: ${error.message}`\n },\n { status: 500 }\n );\n }\n\n return NextResponse.json({ response });\n } catch (error) {\n console.error('Failed to process chat request:', String(error));\n return NextResponse.json({ error: `Failed to process chat request: ${error.message}` }, { status: 500 });\n }\n}\n"], ["/easy-dataset/app/api/projects/[projectId]/playground/chat/stream/route.js", "import { NextResponse } from 'next/server';\nimport LLMClient from '@/lib/llm/core/index';\n\n/**\n * 流式输出的聊天接口\n */\nexport async function POST(request, { params }) {\n const { projectId } = params;\n\n try {\n const body = await request.json();\n const { model, messages } = body;\n\n if (!model || !messages) {\n return NextResponse.json({ error: 'Missing necessary parameters' }, { status: 400 });\n }\n\n // 创建 LLM 客户端\n const llmClient = new LLMClient(model);\n\n // 格式化消息历史\n const formattedMessages = messages.map(msg => {\n // 处理纯文本消息\n if (typeof msg.content === 'string') {\n return {\n role: msg.role,\n content: msg.content\n };\n }\n // 处理包含图片的复合消息(用于视觉模型)\n else if (Array.isArray(msg.content)) {\n return {\n role: msg.role,\n content: msg.content\n };\n }\n // 默认情况\n return {\n role: msg.role,\n content: msg.content\n };\n });\n\n try {\n // 调用纯API流式输出\n const response = await llmClient.chatStreamAPI(formattedMessages);\n // 返回流式响应\n return response;\n } catch (error) {\n console.error('Failed to call LLM API:', error);\n return NextResponse.json(\n {\n error: `Failed to call ${model.provider} model: ${error.message}`\n },\n { status: 500 }\n );\n }\n } catch (error) {\n console.error('Failed to process stream chat request:', String(error));\n return NextResponse.json({ error: `Failed to process stream chat request: ${error.message}` }, { status: 500 });\n }\n}\n"], ["/easy-dataset/lib/services/ga/ga-generation.js", "import { getActiveModel } from '@/lib/services/models';\nimport logger from '@/lib/util/logger';\nimport { GA_GENERATION_PROMPT } from '@/lib/llm/prompts/ga-generation';\nimport { GA_GENERATION_PROMPT_EN } from '@/lib/llm/prompts/ga-generationEn';\nimport { extractJsonFromLLMOutput } from '@/lib/llm/common/util';\nconst LLMClient = require('@/lib/llm/core');\n\n/**\n * Generate GA pairs for text content using LLM\n * @param {string} textContent - The text content to analyze\n * @param {string} projectId - The project ID to get the active model for\n * @param {string} language - Language for generation (default: '中文')\n * @returns {Promise} - Generated GA pairs\n */\nexport async function generateGaPairs(textContent, projectId, language = '中文') {\n try {\n logger.info('Starting GA pairs generation');\n\n // 验证输入参数\n if (!textContent || typeof textContent !== 'string') {\n throw new Error('Invalid text content provided');\n }\n\n if (!projectId) {\n throw new Error('Project ID is required');\n }\n\n // Get model configuration\n const model = await getActiveModel(projectId);\n if (!model) {\n throw new Error('No active model available for GA generation');\n }\n\n logger.info(`Using model: ${model.modelName} for project ${projectId}`);\n\n const promptTemplate = language === 'en' ? GA_GENERATION_PROMPT_EN : GA_GENERATION_PROMPT;\n\n // Prepare the prompt with text content\n const prompt = promptTemplate.replace('{text_content}', textContent.slice(0, 10000));\n\n if (!prompt) {\n throw new Error('Failed to generate prompt');\n }\n\n // Call the LLM API\n const response = await callLLMAPI(model, prompt);\n\n if (!response) {\n throw new Error('Empty response from LLM');\n }\n\n // Parse the response\n const gaPairs = parseGaResponse(response);\n\n logger.info(`Successfully generated ${gaPairs.length} GA pairs`);\n return gaPairs;\n } catch (error) {\n logger.error('Failed to generate GA pairs:', error);\n throw error;\n }\n}\n\n/**\n * Call LLM API with the given model and prompt\n * @param {Object} model - Model configuration\n * @param {string} prompt - The prompt to send\n * @returns {Promise} - Parsed JSON object/array\n */\nasync function callLLMAPI(model, prompt) {\n try {\n if (!model || !prompt) {\n throw new Error('Model and prompt are required');\n }\n\n logger.info('Calling LLM API...');\n\n const llmClient = new LLMClient(model);\n const response = await llmClient.getResponse(prompt); // Changed from llmClient.chat\n\n if (!response) {\n throw new Error('Invalid response from LLM');\n }\n\n return response;\n } catch (error) {\n logger.error('LLM API call failed:', error);\n throw new Error(`LLM API call failed: ${error.message}`);\n }\n}\n\n/**\n * Parse GA pairs from LLM response\n * @param {string} response - Raw LLM response\n * @returns {Array} - Parsed GA pairs\n */\nfunction parseGaResponse(response) {\n try {\n // Log the raw response for debugging\n logger.info('Raw LLM response length:', response.length);\n\n const parsed = extractJsonFromLLMOutput(response);\n\n if (!parsed) {\n throw new Error('Failed to extract JSON from LLM response');\n }\n\n // Handle case where response is wrapped in an object\n let gaPairsArray = parsed;\n if (!Array.isArray(parsed)) {\n // Check if it's wrapped in a property\n if (parsed.gaPairs && Array.isArray(parsed.gaPairs)) {\n gaPairsArray = parsed.gaPairs;\n } else if (parsed.pairs && Array.isArray(parsed.pairs)) {\n gaPairsArray = parsed.pairs;\n } else if (parsed.results && Array.isArray(parsed.results)) {\n gaPairsArray = parsed.results;\n } else {\n // Try to convert object format to array format\n const objectKeys = Object.keys(parsed);\n const audienceKeys = objectKeys.filter(key => key.startsWith('audience_'));\n const genreKeys = objectKeys.filter(key => key.startsWith('genre_'));\n\n if (audienceKeys.length > 0 && genreKeys.length > 0) {\n gaPairsArray = [];\n for (let i = 1; i <= Math.min(audienceKeys.length, genreKeys.length); i++) {\n const audience = parsed[`audience_${i}`];\n const genre = parsed[`genre_${i}`];\n if (audience && genre) {\n gaPairsArray.push({ audience, genre });\n }\n }\n } else {\n throw new Error('Response is not an array and no recognized array property found');\n }\n }\n }\n\n // Validate the structure\n const validatedPairs = gaPairsArray.map((pair, index) => {\n if (!pair.genre || !pair.audience) {\n throw new Error(`GA pair ${index + 1} missing genre or audience`);\n }\n\n if (!pair.genre.title || !pair.genre.description || !pair.audience.title || !pair.audience.description) {\n throw new Error(`GA pair ${index + 1} missing required fields`);\n }\n\n return {\n genre: {\n title: String(pair.genre.title).trim(),\n description: String(pair.genre.description).trim()\n },\n audience: {\n title: String(pair.audience.title).trim(),\n description: String(pair.audience.description).trim()\n }\n };\n });\n\n // Ensure we have exactly 5 pairs\n if (validatedPairs.length !== 5) {\n logger.warn(`Expected 5 GA pairs, got ${validatedPairs.length}. Using first 5 or padding with fallbacks.`);\n\n // If we have more than 5, take the first 5\n if (validatedPairs.length > 5) {\n return validatedPairs.slice(0, 5);\n }\n\n // If we have fewer than 5, pad with fallbacks\n const fallbacks = getFallbackGaPairs();\n while (validatedPairs.length < 5) {\n validatedPairs.push(fallbacks[validatedPairs.length]);\n }\n }\n\n logger.info(`Successfully parsed ${validatedPairs.length} GA pairs`);\n return validatedPairs;\n } catch (error) {\n logger.error('Failed to parse GA response:', error);\n logger.error('Raw response:', response);\n\n // Return fallback GA pairs if parsing fails\n logger.info('Using fallback GA pairs due to parsing failure');\n return getFallbackGaPairs();\n }\n}\n\n/**\n * Get fallback GA pairs when generation fails\n * @returns {Array} - Default GA pairs\n */\nfunction getFallbackGaPairs() {\n return [\n {\n genre: {\n title: '学术研究',\n description: '学术性、研究导向的内容,具有正式的语调和详细的分析'\n },\n audience: {\n title: '研究人员',\n description: '寻求深入知识的学术研究人员和研究生'\n }\n },\n {\n genre: {\n title: '教育指南',\n description: '结构化的学习材料,具有清晰的解释和示例'\n },\n audience: {\n title: '学生',\n description: '本科生和该主题的新学习者'\n }\n },\n {\n genre: {\n title: '专业手册',\n description: '实用、以实施为重点的内容,用于工作场所应用'\n },\n audience: {\n title: '从业者',\n description: '在实践中应用知识的行业专业人员'\n }\n },\n {\n genre: {\n title: '科普文章',\n description: '使复杂主题易于理解的可访问内容'\n },\n audience: {\n title: '普通公众',\n description: '没有专业背景的好奇读者'\n }\n },\n {\n genre: {\n title: '技术文档',\n description: '详细的规范和实施指南'\n },\n audience: {\n title: '开发人员',\n description: '技术专家和系统实施人员'\n }\n }\n ];\n}\n"], ["/easy-dataset/app/api/projects/[projectId]/distill/tags/route.js", "import { NextResponse } from 'next/server';\nimport { distillTagsPrompt } from '@/lib/llm/prompts/distillTags';\nimport { distillTagsEnPrompt } from '@/lib/llm/prompts/distillTagsEn';\nimport { db } from '@/lib/db';\nimport { getProject } from '@/lib/db/projects';\n\nconst LLMClient = require('@/lib/llm/core');\n\n/**\n * 生成标签接口:根据顶级主题、某级标签构造指定数量的子标签\n */\nexport async function POST(request, { params }) {\n try {\n const { projectId } = params;\n\n // 验证项目ID\n if (!projectId) {\n return NextResponse.json({ error: '项目ID不能为空' }, { status: 400 });\n }\n\n const { parentTag, parentTagId, tagPath, count = 10, model, language = 'zh' } = await request.json();\n\n if (!parentTag) {\n const errorMsg = language === 'en' ? 'Topic tag name cannot be empty' : '主题标签名称不能为空';\n return NextResponse.json({ error: errorMsg }, { status: 400 });\n }\n\n // 查询现有标签\n const existingTags = await db.tags.findMany({\n where: {\n projectId,\n parentId: parentTagId || null\n }\n });\n\n const existingTagNames = existingTags.map(tag => tag.label);\n\n // 创建LLM客户端\n const llmClient = new LLMClient(model);\n\n // 获取项目配置\n const project = await getProject(projectId);\n const { globalPrompt } = project || {};\n\n // 生成提示词\n const promptFunc = language === 'en' ? distillTagsEnPrompt : distillTagsPrompt;\n const prompt = promptFunc(tagPath, parentTag, existingTagNames, count, globalPrompt);\n\n // 调用大模型生成标签\n const { answer } = await llmClient.getResponseWithCOT(prompt);\n\n // 解析返回的标签\n let tags = [];\n\n try {\n tags = JSON.parse(answer);\n } catch (error) {\n console.error('解析标签JSON失败:', String(error));\n // 尝试使用正则表达式提取标签\n const matches = answer.match(/\"([^\"]+)\"/g);\n if (matches) {\n tags = matches.map(match => match.replace(/\"/g, ''));\n }\n }\n\n // 保存标签到数据库\n const savedTags = [];\n for (let i = 0; i < tags.length; i++) {\n const tagName = tags[i];\n try {\n const tag = await db.tags.create({\n data: {\n label: tagName,\n projectId,\n parentId: parentTagId || null\n }\n });\n savedTags.push(tag);\n } catch (error) {\n console.error(`[标签生成] 保存标签 ${tagName} 失败:`, String(error));\n throw error;\n }\n }\n return NextResponse.json(savedTags);\n } catch (error) {\n console.error('[标签生成] 生成标签失败:', String(error));\n console.error('[标签生成] 错误堆栈:', error.stack);\n return NextResponse.json({ error: error.message || '生成标签失败' }, { status: 500 });\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/app/api/projects/[projectId]/datasets/optimize/route.js", "import { NextResponse } from 'next/server';\nimport { getDatasetsById, updateDataset } from '@/lib/db/datasets';\nimport LLMClient from '@/lib/llm/core/index';\nimport getNewAnswerPrompt from '@/lib/llm/prompts/newAnswer';\nimport getNewAnswerEnPrompt from '@/lib/llm/prompts/newAnswerEn';\nimport { extractJsonFromLLMOutput } from '@/lib/llm/common/util';\n\n// 优化数据集答案\nexport async function POST(request, { params }) {\n try {\n const { projectId } = params;\n\n // 验证项目ID\n if (!projectId) {\n return NextResponse.json({ error: 'Project ID cannot be empty' }, { status: 400 });\n }\n\n // 获取请求体\n const { datasetId, model, advice, language } = await request.json();\n\n if (!datasetId) {\n return NextResponse.json({ error: 'Dataset ID cannot be empty' }, { status: 400 });\n }\n\n if (!model) {\n return NextResponse.json({ error: 'Model cannot be empty' }, { status: 400 });\n }\n\n if (!advice) {\n return NextResponse.json({ error: 'Please provide optimization suggestions' }, { status: 400 });\n }\n\n // 获取数据集内容\n const dataset = await getDatasetsById(datasetId);\n if (!dataset) {\n return NextResponse.json({ error: 'Dataset does not exist' }, { status: 404 });\n }\n\n // 创建LLM客户端\n const llmClient = new LLMClient(model);\n\n // 生成优化后的答案和思维链\n const prompt =\n language === 'en'\n ? getNewAnswerEnPrompt(dataset.question, dataset.answer || '', dataset.cot || '', advice)\n : getNewAnswerPrompt(dataset.question, dataset.answer || '', dataset.cot || '', advice);\n\n const response = await llmClient.getResponse(prompt);\n\n // 从LLM输出中提取JSON格式的优化结果\n const optimizedResult = extractJsonFromLLMOutput(response);\n\n if (!optimizedResult || !optimizedResult.answer) {\n return NextResponse.json({ error: 'Failed to optimize answer, please try again' }, { status: 500 });\n }\n\n // 更新数据集\n const updatedDataset = {\n ...dataset,\n answer: optimizedResult.answer,\n cot: optimizedResult.cot || dataset.cot\n };\n\n await updateDataset(updatedDataset);\n\n // 返回优化后的数据集\n return NextResponse.json({\n success: true,\n dataset: updatedDataset\n });\n } catch (error) {\n console.error('Failed to optimize answer:', String(error));\n return NextResponse.json({ error: error.message || 'Failed to optimize answer' }, { status: 500 });\n }\n}\n"], ["/easy-dataset/app/api/projects/[projectId]/distill/questions/route.js", "import { NextResponse } from 'next/server';\nimport { distillQuestionsPrompt } from '@/lib/llm/prompts/distillQuestions';\nimport { distillQuestionsEnPrompt } from '@/lib/llm/prompts/distillQuestionsEn';\nimport { db } from '@/lib/db';\nimport { getProject } from '@/lib/db/projects';\n\nconst LLMClient = require('@/lib/llm/core');\n\n/**\n * 生成问题接口:根据某个标签链路构造指定数量的问题\n */\nexport async function POST(request, { params }) {\n try {\n const { projectId } = params;\n\n // 验证项目ID\n if (!projectId) {\n return NextResponse.json({ error: '项目ID不能为空' }, { status: 400 });\n }\n\n const { tagPath, currentTag, tagId, count = 5, model, language = 'zh' } = await request.json();\n\n if (!currentTag || !tagPath) {\n const errorMsg = language === 'en' ? 'Tag information cannot be empty' : '标签信息不能为空';\n return NextResponse.json({ error: errorMsg }, { status: 400 });\n }\n\n // 首先获取或创建蒸馏文本块\n let distillChunk = await db.chunks.findFirst({\n where: {\n projectId,\n name: 'Distilled Content'\n }\n });\n\n if (!distillChunk) {\n // 创建一个特殊的蒸馏文本块\n distillChunk = await db.chunks.create({\n data: {\n name: 'Distilled Content',\n projectId,\n fileId: 'distilled',\n fileName: 'distilled.md',\n content:\n 'This text block is used to store questions generated through data distillation and is not related to actual literature.',\n summary: 'Questions generated through data distillation',\n size: 0\n }\n });\n }\n\n // 获取已有的问题,避免重复\n const existingQuestions = await db.questions.findMany({\n where: {\n projectId,\n label: currentTag,\n chunkId: distillChunk.id // 使用蒸馏文本块的 ID\n },\n select: { question: true }\n });\n\n const existingQuestionTexts = existingQuestions.map(q => q.question);\n\n // 创建LLM客户端\n // 使用前端传过来的模型配置\n const llmClient = new LLMClient(model);\n\n // 获取项目配置\n const project = await getProject(projectId);\n const { globalPrompt } = project || {};\n\n // 生成提示词\n const promptFunc = language === 'en' ? distillQuestionsEnPrompt : distillQuestionsPrompt;\n const prompt = promptFunc(tagPath, currentTag, count, existingQuestionTexts, globalPrompt);\n\n // 调用大模型生成问题\n const { answer } = await llmClient.getResponseWithCOT(prompt);\n\n // 解析返回的问题\n let questions = [];\n\n try {\n questions = JSON.parse(answer);\n } catch (error) {\n console.error('解析问题JSON失败:', String(error));\n // 尝试使用正则表达式提取问题\n const matches = answer.match(/\"([^\"]+)\"/g);\n if (matches) {\n questions = matches.map(match => match.replace(/\"/g, ''));\n }\n }\n\n // 保存问题到数据库\n const savedQuestions = [];\n for (const questionText of questions) {\n const question = await db.questions.create({\n data: {\n question: questionText,\n projectId,\n label: currentTag,\n chunkId: distillChunk.id\n }\n });\n savedQuestions.push(question);\n }\n\n return NextResponse.json(savedQuestions);\n } catch (error) {\n console.error('生成问题失败:', String(error));\n return NextResponse.json({ error: error.message || '生成问题失败' }, { status: 500 });\n }\n}\n"], ["/easy-dataset/lib/file/file-process/pdf/vision.js", "import { getProjectRoot } from '@/lib/db/base';\nimport { getTaskConfig } from '@/lib/db/projects';\nimport convertPrompt from '@/lib/llm/prompts/pdfToMarkdown';\nimport convertPromptEn from '@/lib/llm/prompts/pdfToMarkdownEn';\nimport reTitlePrompt from '@/lib/llm/prompts/optimalTitle';\nimport reTitlePromptEn from '@/lib/llm/prompts/optimalTitleEn';\nimport path from 'path';\n\nexport async function visionProcessing(projectId, fileName, options = {}) {\n try {\n const { updateTask, task, message } = options;\n\n let taskCompletedCount = task.completedCount;\n\n console.log('executing vision conversion strategy......');\n\n // 获取项目路径\n const projectRoot = await getProjectRoot();\n const projectPath = path.join(projectRoot, projectId);\n const filePath = path.join(projectPath, 'files', fileName);\n\n // 获取项目配置\n const taskConfig = await getTaskConfig(projectId);\n\n const model = task.vsionModel;\n\n if (!model) {\n throw new Error('please check if pdf conversion vision model is configured');\n }\n\n if (model.type !== 'vision') {\n throw new Error(\n `${model.modelName}(${model.providerName}) this model is not a vision model, please check [model configuration]`\n );\n }\n\n if (!model.apiKey) {\n throw new Error(\n `${model.modelName}(${model.providerName}) this model has no api key configured, please check [model configuration]`\n );\n }\n\n const convert = task.language === 'en' ? convertPromptEn : convertPrompt;\n const reTitle = task.language === 'en' ? reTitlePromptEn : reTitlePrompt;\n\n //创建临时文件夹分割不同任务产生的临时图片文件,防止同时读写一个文件夹,导致内容出错\n const config = {\n pdfPath: filePath,\n outputDir: path.join(projectPath, 'files'),\n apiKey: model.apiKey,\n model: model.modelId,\n baseUrl: model.endpoint,\n useFullPage: true,\n verbose: false,\n concurrency: taskConfig.visionConcurrencyLimit,\n prompt: convert(),\n textPrompt: reTitle(),\n onProgress: async ({ current, total, taskStatus }) => {\n if (updateTask && task.id) {\n message.current.processedPage = current;\n message.setpInfo = `processing ${fileName} ${current}/${total} pages progress: ${(current / total) * 100}% `;\n await updateTask(task.id, {\n completedCount: taskCompletedCount + current,\n detail: JSON.stringify(message)\n });\n }\n }\n };\n\n console.log('vision strategy: starting pdf file processing');\n\n const { parsePdf } = await import('pdf2md-js');\n await parsePdf(filePath, config);\n\n //转换结束\n return { success: true };\n } catch (error) {\n console.error('vision strategy processing error:', error);\n throw error;\n }\n}\n\nexport default {\n visionProcessing\n};\n"], ["/easy-dataset/lib/file/file-process/pdf/mineru.js", "import http from 'http';\nimport https from 'https';\nimport AdmZip from 'adm-zip';\nimport { getProjectRoot } from '@/lib/db/base';\nimport fs from 'fs';\nimport path from 'path';\n\n// 常量定义\nconst MINERU_API_BASE = 'https://mineru.net/api/v4';\nconst POLL_INTERVAL = 3000; // 3秒\nconst MAX_POLL_ATTEMPTS = 90; // 最多尝试90次\nconst PROCESSING_STATES = {\n DONE: 'done',\n FAILED: 'failed'\n};\n\nexport async function minerUProcessing(projectId, fileName, options = {}) {\n console.log('executing pdf mineru conversion strategy......');\n try {\n const { updateTask, task, message } = options;\n\n let taskCompletedCount = task.completedCount;\n\n // 获取项目路径\n const projectRoot = await getProjectRoot();\n const projectPath = path.join(projectRoot, projectId);\n const filePath = path.join(projectPath, 'files', fileName);\n\n // 读取任务配置\n const taskConfigPath = path.join(projectPath, 'task-config.json');\n let taskConfig;\n try {\n await fs.promises.access(taskConfigPath);\n const taskConfigData = await fs.promises.readFile(taskConfigPath, 'utf8');\n taskConfig = JSON.parse(taskConfigData);\n } catch (error) {\n console.error('error getting mineru token configuration:', error);\n throw new Error('token configuration not found, please check if mineru token is configured in task settings');\n }\n\n const key = taskConfig?.minerUToken;\n if (key === undefined || key === null || key === '') {\n throw new Error('token configuration not found, please check if mineru token is configured in task settings');\n }\n\n // 准备请求选项\n const requestOptions = JSON.stringify({\n enable_formula: true,\n layout_model: 'doclayout_yolo',\n enable_table: true,\n files: [{ name: fileName, is_ocr: true, data_id: 'abcd' }]\n });\n\n // 1. 获取文件上传地址\n console.log('mineru getting file upload url...');\n const urlResponse = await makeHttpRequest(`${MINERU_API_BASE}/file-urls/batch`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Content-Length': Buffer.byteLength(requestOptions),\n Authorization: `Bearer ${key}`\n },\n body: requestOptions\n });\n\n if (urlResponse.code !== 0 || !urlResponse.data?.file_urls?.[0]) {\n throw new Error('failed to get file upload url: ' + JSON.stringify(urlResponse));\n }\n\n //上传文件后会自动执行任务\n let batchId = null;\n let uploadUrl = null;\n console.log('mineru executing file upload task...');\n if (urlResponse.code == 0) {\n //上传文件地址\n uploadUrl = urlResponse.data?.file_urls?.[0];\n //此次任务id\n batchId = urlResponse.data?.batch_id;\n }\n\n // 2. 上传文件\n await uploadFile(filePath, uploadUrl);\n console.log('mineru file upload completed!');\n\n // 3. 轮询查询转换状态\n console.log('mineru starting to check task progress...');\n let currentPage = 0;\n let totalPage = 0;\n while (true) {\n try {\n //查询任务进度API\n const resultResponse = await makeHttpRequest(`${MINERU_API_BASE}/extract-results/batch/${batchId}`, {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${key}`\n }\n });\n\n // 任务状态\n const currentState = resultResponse.data?.extract_result?.[0]?.state;\n const extract_progress = resultResponse.data?.extract_result?.[0]?.extract_progress;\n\n if (extract_progress) {\n // 任务进度\n currentPage = extract_progress.extracted_pages;\n // 总页数\n totalPage = extract_progress.total_pages;\n } else {\n currentPage = totalPage;\n }\n message.current.processedPage = currentPage;\n message.stepInfo = `processing ${fileName} ${currentPage}/${totalPage} pages progress: ${(currentPage / totalPage) * 100}%`;\n\n //更新任务状态\n await updateTask(task.id, {\n completedCount: currentPage + taskCompletedCount,\n detail: JSON.stringify(message)\n });\n\n console.log(`mineru ${fileName} current progress: ${currentPage}/${totalPage}, status: ${currentState}`);\n\n //解析成功结束回写状态定时器\n if (resultResponse.code === 0 && currentState === PROCESSING_STATES.DONE) {\n const zipUrl = resultResponse.data.extract_result[0].full_zip_url;\n const savePath = path.join(projectPath, 'files');\n await downloadAndExtractZip(zipUrl, savePath, fileName);\n break;\n }\n // 检查是否失败\n if (resultResponse.code !== 0 || currentState === PROCESSING_STATES.FAILED) {\n throw new Error(`task processing failed: ${JSON.stringify(resultResponse)}`);\n }\n\n // 等待下次轮询\n await new Promise(resolve => setTimeout(resolve, POLL_INTERVAL));\n } catch (error) {\n throw error;\n }\n }\n console.log('mineru pdf conversion completed!');\n return { success: true };\n } catch (error) {\n console.error('mineru api call error:', error);\n throw error;\n }\n}\n\n/**\n * 发送 HTTP 请求\n */\nasync function makeHttpRequest(url, options) {\n return new Promise((resolve, reject) => {\n const isHttps = url.startsWith('https');\n const client = isHttps ? https : http;\n\n const urlObj = new URL(url);\n const requestOptions = {\n hostname: urlObj.hostname,\n port: urlObj.port || (isHttps ? 443 : 80),\n path: `${urlObj.pathname}${urlObj.search}`,\n method: options.method,\n headers: options.headers\n };\n\n const req = client.request(requestOptions, res => {\n let data = '';\n\n res.on('data', chunk => {\n data += chunk;\n });\n\n res.on('end', () => {\n try {\n if (res.statusCode >= 200 && res.statusCode < 300) {\n resolve(JSON.parse(data));\n } else {\n reject(new Error(`request failed, status code: ${res.statusCode}, response: ${data}`));\n }\n } catch (error) {\n reject(new Error('failed to parse response'));\n }\n });\n });\n\n req.on('error', error => {\n reject(error);\n });\n\n if (options.body) {\n req.write(options.body);\n }\n\n req.end();\n });\n}\n\n/**\n * 上传文件至MinerU指定地址\n */\nasync function uploadFile(filePath, uploadUrl) {\n return new Promise((resolve, reject) => {\n const isHttps = uploadUrl.startsWith('https');\n const url = new URL(uploadUrl);\n const client = url.protocol === 'https:' ? https : http;\n const fileStream = fs.createReadStream(filePath);\n const options = {\n hostname: url.hostname,\n port: url.port || (isHttps ? 443 : 80),\n path: `${url.pathname}${url.search}`,\n method: 'PUT'\n };\n\n const req = client.request(options, res => {\n let responseData = '';\n\n res.on('data', chunk => {\n responseData += chunk;\n });\n\n res.on('end', () => {\n if (res.statusCode === 200) {\n resolve(responseData);\n } else {\n reject(new Error(`Upload failed with status ${res.statusCode}: ${responseData}`));\n }\n });\n });\n\n req.on('error', error => {\n reject(error);\n });\n\n fileStream.pipe(req);\n });\n}\n\n/**\n * 获取任务执行完成后的压缩包,仅解压md文件\n */\nasync function downloadAndExtractZip(zipUrl, targetDir, fileName) {\n // 创建目标目录\n if (!fs.existsSync(targetDir)) {\n fs.mkdirSync(targetDir, { recursive: true });\n }\n\n // 下载 ZIP 文件到内存\n const zipBuffer = await new Promise((resolve, reject) => {\n https.get(zipUrl, res => {\n const chunks = [];\n res.on('data', chunk => chunks.push(chunk));\n res.on('end', () => resolve(Buffer.concat(chunks)));\n res.on('error', reject);\n });\n });\n\n // 解压到目标目录\n const zip = new AdmZip(zipBuffer);\n const zipEntries = zip.getEntries();\n zipEntries.forEach(entry => {\n if (entry.entryName.toLowerCase().endsWith('.md')) {\n // 获取文件内容为 Buffer\n const content = zip.readFile(entry);\n // 尝试用 UTF-8 解码,如果失败则尝试其他编码\n const text = content.toString('utf8');\n // 创建输出文件路径\n const outputPath = path.join(targetDir, fileName.replace('.pdf', '.md'));\n // 写入文件,确保使用 UTF-8 编码\n fs.writeFileSync(outputPath, text, { encoding: 'utf8' });\n console.log(`extracted to directory: ${outputPath}`);\n }\n });\n}\n\nexport default {\n minerUProcessing\n};\n"], ["/easy-dataset/lib/llm/core/providers/openai.js", "import { createOpenAI } from '@ai-sdk/openai';\nimport BaseClient from './base.js';\n\nclass OpenAIClient extends BaseClient {\n constructor(config) {\n super(config);\n this.openai = createOpenAI({\n baseURL: this.endpoint,\n apiKey: this.apiKey\n });\n }\n\n _getModel() {\n return this.openai(this.model);\n }\n}\n\nmodule.exports = OpenAIClient;\n"], ["/easy-dataset/lib/db/fileToDb.js", "import { getProjectRoot, readJsonFile } from '@/lib/db/base';\nimport fs from 'fs';\nimport path from 'path';\nimport { db } from '@/lib/db/index';\nimport { DEFAULT_MODEL_SETTINGS } from '@/constant/model';\nimport { getFileMD5 } from '@/lib/util/file';\n\n/**\n * 执行迁移操作\n * @param {Object} task 任务对象,用于更新进度\n * @returns {Promise} 迁移项目数量\n */\nexport async function main(task = null) {\n const projectRoot = await getProjectRoot();\n let count = 0;\n const files = await fs.promises.readdir(projectRoot, { withFileTypes: true });\n\n // 筛选出未迁移的项目\n const unmigratedProjects = [];\n for (const file of files) {\n if (!file.isDirectory()) continue;\n\n const project = await db.projects.findUnique({ where: { id: file.name } });\n if (!project) {\n unmigratedProjects.push({\n file,\n projectPath: path.join(projectRoot, file.name)\n });\n }\n }\n\n // 如果有任务对象,初始化任务信息\n if (task) {\n task.total = unmigratedProjects.length;\n task.completed = 0;\n task.errors = [];\n\n if (task.total === 0) {\n task.progress = 100;\n task.status = 'completed';\n return 0;\n }\n }\n\n // 使用互斥锁来安全地更新计数器\n let completedCount = 0;\n\n // 创建并行任务,保留原有的 Promise.all 高效并行处理\n const promises = unmigratedProjects.map(async ({ file, projectPath }) => {\n try {\n const projectId = file.name;\n const project = await db.projects.findUnique({ where: { id: projectId } });\n if (!project) {\n // 再次检查项目是否已迁移\n let projectDB = await projectHandle(projectId, projectRoot, projectPath);\n if (projectDB) {\n await chunkHandle(projectId, projectPath);\n await tagsHandle(projectId, projectPath);\n await modelConfigHandle(projectId, projectPath);\n await questionHandle(projectId, projectPath);\n await datasetHandle(projectId, projectPath);\n await updateQuestions(projectId);\n\n // 原子操作增加完成数量\n completedCount++;\n\n // 更新进度\n if (task) {\n task.completed = completedCount;\n task.progress = Math.floor((completedCount / task.total) * 100);\n }\n\n return 1; // 返回1表示迁移了一个项目\n }\n }\n return 0;\n } catch (error) {\n console.error(`处理项目出错:${projectPath}`, error);\n if (task) {\n task.errors.push({\n projectId: file.name,\n error: error.message\n });\n }\n return 0; // 出错时返回0\n }\n });\n\n // 等待所有并行任务完成\n const results = await Promise.all(promises);\n\n // 统计总完成数量\n count = results.reduce((total, curr) => total + curr, 0);\n\n // 确保最终进度为100%\n if (task && count > 0) {\n task.progress = 100;\n }\n\n return count;\n}\n\n//备份文件\nasync function backupHandle(projectRoot, projectPath) {\n const projectName = path.basename(projectPath);\n const newProjectName = projectName + '-backup';\n const newProjectPath = path.join(path.dirname(projectPath), newProjectName);\n try {\n await fs.promises.rename(projectPath, newProjectPath);\n console.log(`File renamed from ${projectPath} to ${newProjectPath}`);\n } catch (error) {\n console.error(`Failed to rename file from ${projectPath} to ${newProjectPath}`, error);\n }\n}\n\n//项目文件数据处理\nasync function projectHandle(projectId, projectRoot, projectPath) {\n try {\n const configPath = path.join(projectPath, 'config.json');\n let projectData = await readJsonFile(configPath);\n if (!projectData) return null;\n let project = await db.projects.create({\n data: {\n id: projectId,\n name: projectData.name,\n description: projectData.description\n }\n });\n if (projectData.uploadedFiles && projectData.uploadedFiles.length > 0) {\n let projectId = project.id;\n const newProjectPath = path.join(projectRoot, projectId, 'files');\n let uploadFileList = [];\n const filesPath = path.join(projectPath, 'files');\n for (const fileName of projectData.uploadedFiles) {\n const fPath = path.join(filesPath, fileName);\n //获取文件大小\n const stats = await fs.promises.stat(fPath);\n //获取文件md5\n const md5 = await getFileMD5(fPath);\n //获取文件扩展名\n const ext = path.extname(fPath);\n let data = {\n projectId,\n fileName,\n size: stats.size,\n md5,\n fileExt: ext,\n path: newProjectPath\n };\n uploadFileList.push(data);\n }\n await db.uploadFiles.createMany({ data: uploadFileList });\n }\n return project;\n } catch (error) {\n console.error('Error project insert db:', error);\n throw error;\n }\n}\n\n//同步其他配置文件\nasync function syncOtherConfigFile(projectRoot, projectPath, projectNewId) {\n if (fs.existsSync(projectPath)) {\n const newProjectPath = path.join(projectRoot, projectNewId);\n try {\n await copyDirRecursive(projectPath, newProjectPath, projectNewId);\n console.log(`sync config at: ${newProjectPath}`);\n } catch (error) {\n console.error(`Failed to sync config at: ${newProjectPath}`, error);\n }\n } else {\n console.error(`Project not found at path: ${projectPath}`);\n }\n}\n\nasync function tagsHandle(projectId, projectPath) {\n const tagsPath = path.join(projectPath, 'tags.json');\n try {\n if (!fs.existsSync(tagsPath)) {\n return;\n }\n const tagsData = await readJsonFile(tagsPath);\n if (tagsData.length === 0) return;\n await insertTags(projectId, tagsData);\n } catch (error) {\n console.error('Error tags.json insert db:', error);\n throw error;\n }\n}\n\nasync function insertTags(projectId, tags, parentId = null) {\n for (const tag of tags) {\n // 插入当前节点\n const createdTag = await db.tags.create({\n data: {\n projectId,\n label: tag.label,\n parentId: parentId\n }\n });\n // 如果有子节点,递归插入\n if (tag.child && tag.child.length > 0) {\n await insertTags(projectId, tag.child, createdTag.id);\n }\n }\n}\n\nasync function modelConfigHandle(projectId, projectPath) {\n const modelConfigPath = path.join(projectPath, 'model-config.json');\n try {\n if (!fs.existsSync(modelConfigPath)) {\n return;\n }\n const modelConfigData = await readJsonFile(modelConfigPath);\n if (modelConfigData.length === 0) return;\n let modelConfigList = [];\n for (const modelConfig of modelConfigData) {\n if (!modelConfig.name) continue;\n modelConfigList.push({\n projectId,\n providerId: modelConfig.providerId,\n providerName: modelConfig.provider,\n endpoint: modelConfig.endpoint,\n apiKey: modelConfig.apiKey,\n modelId: modelConfig.name,\n modelName: modelConfig.name,\n type: modelConfig.type ? modelConfig.type : 'text',\n maxTokens: modelConfig.maxTokens ? modelConfig.maxTokens : DEFAULT_MODEL_SETTINGS.maxTokens,\n temperature: modelConfig.temperature ? modelConfig.temperature : DEFAULT_MODEL_SETTINGS.temperature,\n topK: 0,\n topP: 0,\n status: 1\n });\n }\n return await db.modelConfig.createMany({ data: modelConfigList });\n } catch (error) {\n console.error('Error model-config.json insert db:', error);\n throw error;\n }\n}\n\n//chunk文件数据处理\nasync function chunkHandle(projectId, projectPath) {\n try {\n const filesPath = path.join(projectPath, 'files');\n const fileList = await safeReadDir(filesPath);\n\n let chunkList = [];\n for (const fileName of fileList) {\n const baseName = path.basename(fileName, path.extname(fileName));\n let file = await db.uploadFiles.findFirst({ where: { fileName, projectId } });\n const chunksPath = path.join(projectPath, 'chunks');\n const chunks = await safeReadDir(chunksPath, { withFileTypes: true });\n for (const chunk of chunks) {\n if (chunk.name.startsWith(baseName + '-part-')) {\n const content = await fs.promises.readFile(path.join(chunksPath, chunk.name), 'utf8');\n chunkList.push({\n name: path.basename(chunk.name, path.extname(chunk.name)),\n projectId,\n fileId: file !== null ? file.id : '',\n fileName,\n content,\n // TODO summary 暂时使用 content\n summary: content,\n size: content.length\n });\n }\n }\n }\n return await db.chunks.createMany({ data: chunkList });\n } catch (error) {\n console.error('Error chunk insert db:', error);\n throw error;\n }\n}\n\n//问题文件处理\nasync function questionHandle(projectId, projectPath) {\n const questionsPath = path.join(projectPath, 'questions.json');\n let questionList = [];\n try {\n const questionsData = await readJsonFile(questionsPath);\n if (questionsData.length === 0) return;\n for (const question of questionsData) {\n // 确保 chunk 已存在\n let chunk = await db.chunks.findFirst({ where: { name: question.chunkId, projectId } });\n if (!chunk) {\n console.error(`Chunk with name ${question.chunkId} not found for project ${projectPath}`);\n continue;\n }\n if (!question.questions || question.questions.length === 0) continue;\n for (const item of question.questions) {\n const questionData = {\n projectId: projectId,\n chunkId: chunk.id,\n question: item.question,\n label: item.label\n };\n questionList.push(questionData);\n }\n }\n return await db.questions.createMany({ data: questionList });\n } catch (error) {\n console.error('Error questions.json insert db:', error);\n throw error;\n }\n}\n\n//数据集文件处理\nasync function datasetHandle(projectId, projectPath) {\n const datasetsPath = path.join(projectPath, 'datasets.json');\n let datasetList = [];\n try {\n const datasetsData = await readJsonFile(datasetsPath);\n if (datasetsData.length === 0) return;\n for (const dataset of datasetsData) {\n let chunk = await db.chunks.findFirst({ where: { name: dataset.chunkId, projectId } });\n if (!chunk) {\n console.error(`Chunk with name ${dataset.chunkId} not found for project ${projectPath}`);\n continue;\n }\n let question = await db.questions.findFirst({ where: { question: dataset.question } });\n if (!question) {\n console.error(`Question with name ${dataset.question} not found for project ${projectPath}`);\n continue;\n }\n const datasetData = {\n projectId: projectId,\n chunkName: chunk.name,\n chunkContent: '',\n questionId: question.id,\n question: dataset.question,\n answer: dataset.answer,\n model: dataset.model,\n questionLabel: dataset.questionLabel,\n createAt: dataset.createdAt,\n cot: dataset.cot ? dataset.cot : '',\n confirmed: dataset.confirmed ? dataset.confirmed : false\n };\n datasetList.push(datasetData);\n }\n return await db.datasets.createMany({ data: datasetList });\n } catch (error) {\n console.error('Error datasets.json insert db:', error);\n throw error;\n }\n}\n\n//批量更新问题的答案状态\nasync function updateQuestions(projectId) {\n const result = await db.$queryRaw`\n UPDATE Questions\n SET answered = 1\n WHERE EXISTS (\n SELECT 1\n FROM Datasets d\n WHERE d.question = Questions.question\n AND Questions.projectId = ${projectId}\n )\n `;\n\n console.log(result);\n}\n\n// 复制文件夹\nasync function copyDirRecursive(src, dest, projectNewId) {\n try {\n // 检查源路径是否存在\n if (!fs.existsSync(src)) {\n console.error(`Source directory not found: ${src}`);\n return;\n }\n\n // 确保目标路径存在\n if (!fs.existsSync(dest)) {\n fs.mkdirSync(dest, { recursive: true });\n }\n\n // 读取源路径下的所有文件和子目录\n const entries = await fs.promises.readdir(src, { withFileTypes: true });\n\n let old = ['config.json', 'chunks', 'questions.json', 'datasets.json', 'model-config.json'];\n for (const entry of entries) {\n if (old.includes(entry.name)) {\n continue;\n }\n const srcPath = path.join(src, entry.name);\n const destPath = path.join(dest, entry.name);\n\n if (entry.isDirectory()) {\n // 如果是目录,递归复制\n await copyDirRecursive(srcPath, destPath, projectNewId);\n } else {\n // 如果是文件,直接复制\n await fs.promises.copyFile(srcPath, destPath);\n }\n }\n } catch (error) {\n console.error(`Failed to copy directory from ${src} to ${dest}`, error);\n }\n}\n\nasync function safeReadDir(dirPath, options = {}) {\n try {\n if (fs.existsSync(dirPath)) {\n return await fs.promises.readdir(dirPath, options);\n }\n return [];\n } catch (error) {\n console.error(`Error reading directory: ${dirPath}`, error);\n return [];\n }\n}\n"], ["/easy-dataset/app/projects/[projectId]/datasets/hooks/useDatasetExport.js", "'use client';\n\nimport { useTranslation } from 'react-i18next';\nimport { toast } from 'sonner';\nimport axios from 'axios';\n\nconst useDatasetExport = projectId => {\n const { t } = useTranslation();\n\n // 导出数据集\n const exportDatasets = async exportOptions => {\n try {\n let apiUrl = `/api/projects/${projectId}/datasets/export`;\n if (exportOptions.confirmedOnly) {\n apiUrl += `?status=confirmed`;\n }\n const response = await axios.get(apiUrl);\n let dataToExport = response.data;\n\n // 根据选择的格式转换数据\n let formattedData;\n // 不同文件格式\n let mimeType = 'application/json';\n\n if (exportOptions.formatType === 'alpaca') {\n // 根据选择的字段类型生成不同的数据格式\n if (exportOptions.alpacaFieldType === 'instruction') {\n // 使用 instruction 字段\n formattedData = dataToExport.map(({ question, answer, cot }) => ({\n instruction: question,\n input: '',\n output: cot && exportOptions.includeCOT ? `${cot}\\n${answer}` : answer,\n system: exportOptions.systemPrompt || ''\n }));\n } else {\n // 使用 input 字段\n formattedData = dataToExport.map(({ question, answer, cot }) => ({\n instruction: exportOptions.customInstruction || '',\n input: question,\n output: cot && exportOptions.includeCOT ? `${cot}\\n${answer}` : answer,\n system: exportOptions.systemPrompt || ''\n }));\n }\n } else if (exportOptions.formatType === 'sharegpt') {\n formattedData = dataToExport.map(({ question, answer, cot }) => {\n const messages = [];\n\n // 添加系统提示词(如果有)\n if (exportOptions.systemPrompt) {\n messages.push({\n role: 'system',\n content: exportOptions.systemPrompt\n });\n }\n\n // 添加用户问题\n messages.push({\n role: 'user',\n content: question\n });\n\n // 添加助手回答\n messages.push({\n role: 'assistant',\n content: cot && exportOptions.includeCOT ? `${cot}\\n${answer}` : answer\n });\n\n return { messages };\n });\n } else if (exportOptions.formatType === 'custom') {\n // 处理自定义格式\n const { questionField, answerField, cotField, includeLabels, includeChunk } = exportOptions.customFields;\n formattedData = dataToExport.map(({ question, answer, cot, questionLabel: labels, chunkId }) => {\n const item = {\n [questionField]: question,\n [answerField]: answer\n };\n\n // 如果有思维链且用户选择包含思维链,则添加思维链字段\n if (cot && exportOptions.includeCOT && cotField) {\n item[cotField] = cot;\n }\n\n // 如果需要包含标签\n if (includeLabels && labels && labels.length > 0) {\n item.label = labels.split(' ')[1];\n }\n\n // 如果需要包含文本块\n if (includeChunk && chunkId) {\n item.chunk = chunkId;\n }\n\n return item;\n });\n }\n\n // 处理不同的文件格式\n let content;\n let fileExtension;\n\n if (exportOptions.fileFormat === 'jsonl') {\n // JSONL 格式:每行一个 JSON 对象\n content = formattedData.map(item => JSON.stringify(item)).join('\\n');\n fileExtension = 'jsonl';\n } else if (exportOptions.fileFormat === 'csv') {\n // CSV 格式\n const headers = Object.keys(formattedData[0] || {});\n const csvRows = [\n // 添加表头\n headers.join(','),\n // 添加数据行\n ...formattedData.map(item =>\n headers\n .map(header => {\n // 处理包含逗号、换行符或双引号的字段\n let field = item[header]?.toString() || '';\n if (exportOptions.formatType === 'sharegpt') field = JSON.stringify(item[header]);\n if (field.includes(',') || field.includes('\\n') || field.includes('\"')) {\n field = `\"${field.replace(/\"/g, '\"\"')}\"`;\n }\n return field;\n })\n .join(',')\n )\n ];\n content = csvRows.join('\\n');\n fileExtension = 'csv';\n } else {\n // 默认 JSON 格式\n content = JSON.stringify(formattedData, null, 2);\n fileExtension = 'json';\n }\n\n // 创建 Blob 对象\n const blob = new Blob([content], { type: mimeType || 'application/json' });\n\n // 创建下载链接\n const url = URL.createObjectURL(blob);\n const a = document.createElement('a');\n a.href = url;\n const formatSuffix = exportOptions.formatType === 'alpaca' ? 'alpaca' : 'sharegpt';\n a.download = `datasets-${projectId}-${formatSuffix}-${new Date().toISOString().slice(0, 10)}.${fileExtension}`;\n\n // 触发下载\n document.body.appendChild(a);\n a.click();\n\n // 清理\n document.body.removeChild(a);\n URL.revokeObjectURL(url);\n\n toast.success(t('datasets.exportSuccess'));\n return true;\n } catch (error) {\n toast.error(error.message);\n return false;\n }\n };\n\n return { exportDatasets };\n};\n\nexport default useDatasetExport;\n"], ["/easy-dataset/app/api/projects/[projectId]/llamaFactory/generate/route.js", "import { NextResponse } from 'next/server';\nimport path from 'path';\nimport fs from 'fs';\nimport { getProjectRoot } from '@/lib/db/base';\nimport { getDatasets } from '@/lib/db/datasets';\n\nexport async function POST(request, { params }) {\n try {\n const { projectId } = params;\n const { formatType, systemPrompt, confirmedOnly, includeCOT } = await request.json();\n\n if (!projectId) {\n return NextResponse.json({ error: 'The project ID cannot be empty' }, { status: 400 });\n }\n\n // 获取项目根目录\n const projectRoot = await getProjectRoot();\n const projectPath = path.join(projectRoot, projectId);\n const configPath = path.join(projectPath, 'dataset_info.json');\n const alpacaPath = path.join(projectPath, 'alpaca.json');\n const sharegptPath = path.join(projectPath, 'sharegpt.json');\n\n // 获取数据集\n let datasets = await getDatasets(projectId, !!confirmedOnly);\n\n // 创建 dataset_info.json 配置\n const config = {\n [`[Easy Dataset] [${projectId}] Alpaca`]: {\n file_name: 'alpaca.json',\n columns: {\n prompt: 'instruction',\n query: 'input',\n response: 'output',\n system: 'system'\n }\n },\n [`[Easy Dataset] [${projectId}] ShareGPT`]: {\n file_name: 'sharegpt.json',\n formatting: 'sharegpt',\n columns: {\n messages: 'messages'\n },\n tags: {\n role_tag: 'role',\n content_tag: 'content',\n user_tag: 'user',\n assistant_tag: 'assistant',\n system_tag: 'system'\n }\n }\n };\n\n // 生成数据文件\n const alpacaData = datasets.map(({ question, answer, cot }) => ({\n instruction: question,\n input: '',\n output: cot && includeCOT ? `${cot}\\n${answer}` : answer,\n system: systemPrompt || ''\n }));\n\n const sharegptData = datasets.map(({ question, answer, cot }) => {\n const messages = [];\n if (systemPrompt) {\n messages.push({\n role: 'system',\n content: systemPrompt\n });\n }\n messages.push({\n role: 'user',\n content: question\n });\n messages.push({\n role: 'assistant',\n content: cot && includeCOT ? `${cot}\\n${answer}` : answer\n });\n return { messages };\n });\n\n // 写入文件\n await fs.promises.writeFile(configPath, JSON.stringify(config, null, 2));\n await fs.promises.writeFile(alpacaPath, JSON.stringify(alpacaData, null, 2));\n await fs.promises.writeFile(sharegptPath, JSON.stringify(sharegptData, null, 2));\n\n return NextResponse.json({\n success: true,\n configPath,\n files: [\n { path: alpacaPath, format: 'alpaca' },\n { path: sharegptPath, format: 'sharegpt' }\n ]\n });\n } catch (error) {\n console.error('Error generating Llama Factory config:', String(error));\n return NextResponse.json({ error: error.message }, { status: 500 });\n }\n}\n"], ["/easy-dataset/app/api/llm/ollama/models/route.js", "import { NextResponse } from 'next/server';\n\nconst OllamaClient = require('@/lib/llm/core/providers/ollama');\n\n// 设置为强制动态路由,防止静态生成\nexport const dynamic = 'force-dynamic';\n\nexport async function GET(request) {\n try {\n // 从查询参数中获取 host 和 port\n const { searchParams } = new URL(request.url);\n const host = searchParams.get('host') || '127.0.0.1';\n const port = searchParams.get('port') || '11434';\n\n // 创建 Ollama API 实例\n const ollama = new OllamaClient({\n endpoint: `http://${host}:${port}/api`\n });\n // 获取模型列表\n const models = await ollama.getModels();\n return NextResponse.json(models);\n } catch (error) {\n // console.error('fetch Ollama models error:', error);\n return NextResponse.json({ error: 'fetch Models failed' }, { status: 500 });\n }\n}\n"], ["/easy-dataset/app/api/projects/[projectId]/model-config/route.js", "import { NextResponse } from 'next/server';\nimport { createInitModelConfig, getModelConfigByProjectId, saveModelConfig } from '@/lib/db/model-config';\nimport { DEFAULT_MODEL_SETTINGS, MODEL_PROVIDERS } from '@/constant/model';\nimport { getProject } from '@/lib/db/projects';\n\n// 获取模型配置列表\nexport async function GET(request, { params }) {\n try {\n const { projectId } = params;\n // 验证项目 ID\n if (!projectId) {\n return NextResponse.json({ error: 'The project ID cannot be empty' }, { status: 400 });\n }\n let modelConfigList = await getModelConfigByProjectId(projectId);\n if (!modelConfigList || modelConfigList.length === 0) {\n let insertModelConfigList = [];\n MODEL_PROVIDERS.forEach(item => {\n let data = {\n projectId: projectId,\n providerId: item.id,\n providerName: item.name,\n endpoint: item.defaultEndpoint,\n apiKey: '',\n modelId: item.defaultModels.length > 0 ? item.defaultModels[0] : '',\n modelName: item.defaultModels.length > 0 ? item.defaultModels[0] : '',\n type: 'text',\n temperature: DEFAULT_MODEL_SETTINGS.temperature,\n maxTokens: DEFAULT_MODEL_SETTINGS.maxTokens,\n topK: 0,\n topP: 0,\n status: 1\n };\n insertModelConfigList.push(data);\n });\n modelConfigList = await createInitModelConfig(insertModelConfigList);\n }\n let project = await getProject(projectId);\n return NextResponse.json({ data: modelConfigList, defaultModelConfigId: project.defaultModelConfigId });\n } catch (error) {\n console.error('Error obtaining model configuration:', String(error));\n return NextResponse.json({ error: 'Failed to obtain model configuration' }, { status: 500 });\n }\n}\n\n// 保存模型配置\nexport async function POST(request, { params }) {\n try {\n const { projectId } = params;\n\n // 验证项目 ID\n if (!projectId) {\n return NextResponse.json({ error: 'The project ID cannot be empty' }, { status: 400 });\n }\n // 获取请求体\n const modelConfig = await request.json();\n\n // 验证请求体\n if (!modelConfig) {\n return NextResponse.json({ error: 'The model configuration cannot be empty ' }, { status: 400 });\n }\n modelConfig.projectId = projectId;\n if (!modelConfig.modelId) {\n modelConfig.modelId = modelConfig.modelName;\n }\n const res = await saveModelConfig(modelConfig);\n\n return NextResponse.json(res);\n } catch (error) {\n console.error('Error updating model configuration:', String(error));\n return NextResponse.json({ error: 'Failed to update model configuration' }, { status: 500 });\n }\n}\n"], ["/easy-dataset/lib/llm/core/providers/zhipu.js", "import { createZhipu } from 'zhipu-ai-provider';\n\nimport BaseClient from './base.js';\n\nclass ZhiPuClient extends BaseClient {\n constructor(config) {\n super(config);\n this.zhipu = createZhipu({\n baseURL: this.endpoint,\n apiKey: this.apiKey\n });\n }\n\n _getModel() {\n return this.zhipu(this.model);\n }\n}\n\nmodule.exports = ZhiPuClient;\n"], ["/easy-dataset/app/projects/[projectId]/distill/autoDistillService.js", "'use client';\n\nimport axios from 'axios';\n\n/**\n * 自动蒸馏服务\n */\nclass AutoDistillService {\n /**\n * 执行自动蒸馆任务\n * @param {Object} config - 配置信息\n * @param {string} config.projectId - 项目ID\n * @param {string} config.topic - 蒸馆主题\n * @param {number} config.levels - 标签层级\n * @param {number} config.tagsPerLevel - 每层标签数量\n * @param {number} config.questionsPerTag - 每个标签问题数量\n * @param {Object} config.model - 模型信息\n * @param {string} config.language - 语言\n * @param {Function} config.onProgress - 进度回调\n * @param {Function} config.onLog - 日志回调\n * @returns {Promise}\n */\n async executeDistillTask(config) {\n const {\n projectId,\n topic,\n levels,\n tagsPerLevel,\n questionsPerTag,\n model,\n language,\n concurrencyLimit = 5,\n onProgress,\n onLog\n } = config;\n\n // 项目名称存储,用于整个流程共享\n this.projectName = '';\n\n try {\n // 初始化进度信息\n if (onProgress) {\n onProgress({\n stage: 'initializing',\n tagsTotal: 0,\n tagsBuilt: 0,\n questionsTotal: 0,\n questionsBuilt: 0,\n datasetsTotal: 0,\n datasetsBuilt: 0\n });\n }\n\n // 获取项目名称,只需获取一次\n try {\n const projectResponse = await axios.get(`/api/projects/${projectId}`);\n if (projectResponse && projectResponse.data && projectResponse.data.name) {\n this.projectName = projectResponse.data.name;\n this.addLog(onLog, `Using project name \"${this.projectName}\" as the top-level tag`);\n } else {\n this.projectName = topic; // 如果无法获取项目名称,则使用主题作为默认值\n this.addLog(onLog, `Could not find project name, using topic \"${topic}\" as the top-level tag`);\n }\n } catch (error) {\n this.projectName = topic; // 出错时使用主题作为默认值\n this.addLog(onLog, `Failed to get project name, using topic \"${topic}\" instead: ${error.message}`);\n }\n\n // 添加日志\n this.addLog(\n onLog,\n `Starting to build tag tree for \"${topic}\", number of levels: ${levels}, tags per level: ${tagsPerLevel}, questions per tag: ${questionsPerTag}`\n );\n\n // 从根节点开始构建标签树\n await this.buildTagTree({\n projectId,\n topic,\n levels,\n tagsPerLevel,\n model,\n language,\n onProgress,\n onLog\n });\n\n // 所有标签构建完成后,生成问题\n await this.generateQuestionsForTags({\n projectId,\n levels,\n questionsPerTag,\n model,\n language,\n concurrencyLimit,\n onProgress,\n onLog\n });\n\n // 生成数据集\n await this.generateDatasetsForQuestions({\n projectId,\n model,\n language,\n concurrencyLimit,\n onProgress,\n onLog\n });\n\n // 任务完成\n if (onProgress) {\n onProgress({\n stage: 'completed'\n });\n }\n\n this.addLog(onLog, 'Auto distillation task completed');\n } catch (error) {\n console.error('自动蒸馏任务执行失败:', error);\n this.addLog(onLog, `Task execution error: ${error.message || 'Unknown error'}`);\n throw error;\n }\n }\n\n /**\n * 构建标签树\n * @param {Object} config - 配置信息\n * @param {string} config.projectId - 项目ID\n * @param {string} config.topic - 蒸馆主题\n * @param {number} config.levels - 标签层级\n * @param {number} config.tagsPerLevel - 每层标签数量\n * @param {Object} config.model - 模型信息\n * @param {string} config.language - 语言\n * @param {Function} config.onProgress - 进度回调\n * @param {Function} config.onLog - 日志回调\n * @returns {Promise}\n */\n async buildTagTree(config) {\n const { projectId, topic, levels, tagsPerLevel, model, language, onProgress, onLog } = config;\n\n // 使用已经获取的项目名称,如果未获取到,则使用主题\n const projectName = this.projectName || topic;\n\n // 递归构建标签树\n const buildTagsForLevel = async (parentTag = null, parentTagPath = '', level = 1) => {\n // 设置当前阶段\n if (onProgress) {\n onProgress({\n stage: `level${level}`\n });\n }\n\n // 如果已经达到目标层级,停止递归\n if (level > levels) {\n return;\n }\n\n // 获取当前级别的标签\n let currentLevelTags = [];\n try {\n // 获取所有标签,然后根据父标签ID进行过滤\n const response = await axios.get(`/api/projects/${projectId}/distill/tags/all`);\n\n // 如果有父标签,过滤出当前父标签下的子标签\n if (parentTag) {\n currentLevelTags = response.data.filter(tag => tag.parentId === parentTag.id);\n } else {\n // 如果没有父标签,则获取所有根标签(没有parentId的标签)\n currentLevelTags = response.data.filter(tag => !tag.parentId);\n }\n } catch (error) {\n console.error(`获取${level}级标签失败:`, error);\n this.addLog(onLog, `Failed to get ${level} level tags: ${error.message}`);\n return;\n }\n\n // 计算需要创建的标签数量\n const targetCount = tagsPerLevel;\n const currentCount = currentLevelTags.length;\n const needToCreate = Math.max(0, targetCount - currentCount);\n\n // 如果需要创建标签\n if (needToCreate > 0) {\n // 如果是第一级标签,使用配置中的主题名称\n const parentTagName = level === 1 ? topic : parentTag?.label || '';\n\n this.addLog(onLog, `Tag tree level ${level}: Creating ${tagsPerLevel} subtags for \"${parentTagName}\"...`);\n\n // 构建标签路径,确保以项目名称开头\n let tagPathWithProjectName;\n if (level === 1) {\n // 如果是第一级,使用项目名称\n tagPathWithProjectName = projectName;\n } else {\n // 如果不是第一级,确保标签路径以项目名称开头\n if (!parentTagPath) {\n tagPathWithProjectName = projectName;\n } else if (!parentTagPath.startsWith(projectName)) {\n tagPathWithProjectName = `${projectName} > ${parentTagPath}`;\n } else {\n tagPathWithProjectName = parentTagPath;\n }\n }\n\n try {\n const response = await axios.post(`/api/projects/${projectId}/distill/tags`, {\n parentTag: parentTagName,\n parentTagId: parentTag ? parentTag.id : null,\n tagPath: tagPathWithProjectName || parentTagName,\n count: needToCreate,\n model,\n language\n });\n\n // 更新构建的标签数量\n if (onProgress) {\n onProgress({\n tagsBuilt: response.data.length,\n updateType: 'increment'\n });\n }\n\n // 添加日志\n this.addLog(\n onLog,\n `Successfully created ${response.data.length} tags: ${response.data.map(tag => tag.label).join(', ')}`\n );\n\n // 将新创建的标签添加到当前级别标签列表中\n currentLevelTags = [...currentLevelTags, ...response.data];\n } catch (error) {\n console.error(`创建${level}级标签失败:`, error);\n this.addLog(onLog, `Failed to create ${level} level tags: ${error.message || 'Unknown error'}`);\n }\n }\n\n // 如果不是最后一层,继续递归构建下一层标签\n if (level < levels) {\n for (const tag of currentLevelTags) {\n // 构建标签路径,确保以项目名称开头\n let tagPath;\n if (parentTagPath) {\n tagPath = `${parentTagPath} > ${tag.label}`;\n } else {\n tagPath = `${projectName} > ${tag.label}`;\n }\n\n // 递归构建子标签\n await buildTagsForLevel(tag, tagPath, level + 1);\n }\n }\n };\n\n // 获取叶子节点总数,更新进度条\n const leafTags = Math.pow(tagsPerLevel, levels);\n if (onProgress) {\n onProgress({\n tagsTotal: leafTags\n });\n }\n\n // 从第一层开始构建标签树\n await buildTagsForLevel();\n }\n\n /**\n * 为标签生成问题\n * @param {Object} config - 配置信息\n * @param {string} config.projectId - 项目ID\n * @param {number} config.levels - 标签层级\n * @param {number} config.questionsPerTag - 每个标签问题数量\n * @param {Object} config.model - 模型信息\n * @param {string} config.language - 语言\n * @param {Function} config.onProgress - 进度回调\n * @param {Function} config.onLog - 日志回调\n * @returns {Promise}\n */\n async generateQuestionsForTags(config) {\n const { projectId, levels, questionsPerTag, model, language, concurrencyLimit = 5, onProgress, onLog } = config;\n\n // 设置当前阶段\n if (onProgress) {\n onProgress({\n stage: 'questions'\n });\n }\n\n this.addLog(onLog, 'Tag tree built, starting to generate questions for leaf tags...');\n\n try {\n // 获取所有标签\n const response = await axios.get(`/api/projects/${projectId}/distill/tags/all`);\n const allTags = response.data;\n\n // 找出所有叶子标签(没有子标签的标签)\n const leafTags = [];\n\n // 创建一个映射表,记录每个标签的子标签\n const childrenMap = {};\n allTags.forEach(tag => {\n if (tag.parentId) {\n if (!childrenMap[tag.parentId]) {\n childrenMap[tag.parentId] = [];\n }\n childrenMap[tag.parentId].push(tag);\n }\n });\n\n // 找出所有叶子标签\n allTags.forEach(tag => {\n // 如果没有子标签,并且深度是最大层级,则为叶子标签\n if (!childrenMap[tag.id] && this.getTagDepth(tag, allTags) === levels) {\n leafTags.push(tag);\n }\n });\n\n this.addLog(onLog, `Found ${leafTags.length} leaf tags, starting to generate questions...`);\n\n // 获取所有问题\n const questionsResponse = await axios.get(`/api/projects/${projectId}/questions/tree?isDistill=true`);\n const allQuestions = questionsResponse.data;\n\n // 更新总问题数量\n const totalQuestionsToGenerate = leafTags.length * questionsPerTag;\n if (onProgress) {\n onProgress({\n questionsTotal: totalQuestionsToGenerate\n });\n }\n\n // 准备并发任务\n const generateQuestionTasks = [];\n const processedTags = [];\n\n // 准备所有需要生成问题的叶子标签任务\n for (const tag of leafTags) {\n // 获取标签路径\n const tagPath = this.getTagPath(tag, allTags);\n\n // 计算已有问题数量\n const existingQuestions = allQuestions.filter(q => q.label === tag.label);\n const needToCreate = Math.max(0, questionsPerTag - existingQuestions.length);\n\n if (needToCreate > 0) {\n // 只添加需要生成问题的标签任务\n generateQuestionTasks.push({\n tag,\n tagPath,\n needToCreate\n });\n\n this.addLog(onLog, `Preparing to generate ${needToCreate} questions for tag \"${tag.label}\"...`);\n } else {\n this.addLog(\n onLog,\n `Tag \"${tag.label}\" already has ${existingQuestions.length} questions, no need to generate new questions`\n );\n }\n }\n\n // 分批执行生成问题任务,控制并发数\n this.addLog(\n onLog,\n `Total ${generateQuestionTasks.length} tags need questions, concurrency limit: ${concurrencyLimit}`\n );\n\n // 使用分组批量处理\n for (let i = 0; i < generateQuestionTasks.length; i += concurrencyLimit) {\n const batch = generateQuestionTasks.slice(i, i + concurrencyLimit);\n\n // 并行处理批次任务\n await Promise.all(\n batch.map(async task => {\n const { tag, tagPath, needToCreate } = task;\n\n this.addLog(onLog, `Generating ${needToCreate} questions for tag \"${tag.label}\"...`);\n\n try {\n const response = await axios.post(`/api/projects/${projectId}/distill/questions`, {\n tagPath,\n currentTag: tag.label,\n tagId: tag.id,\n count: needToCreate,\n model,\n language\n });\n\n // 更新生成的问题数量\n if (onProgress) {\n onProgress({\n questionsBuilt: response.data.length,\n updateType: 'increment'\n });\n }\n\n const questions = response.data\n .map(r => r.question || r.content)\n .slice(0, 3)\n .join('\\n'); // 只显示前3个问题以避免日志过长\n this.addLog(onLog, `Successfully generated ${response.data.length} questions for tag \"${tag.label}\"`);\n } catch (error) {\n console.error(`为标签 \"${tag.label}\" 生成问题失败:`, error);\n this.addLog(\n onLog,\n `Failed to generate questions for tag \"${tag.label}\": ${error.message || 'Unknown error'}`\n );\n }\n })\n );\n\n // 每完成一批,输出一次进度日志\n this.addLog(\n onLog,\n `Completed batch ${Math.min(i + concurrencyLimit, generateQuestionTasks.length)}/${generateQuestionTasks.length} of question generation`\n );\n }\n } catch (error) {\n console.error('获取标签失败:', error);\n this.addLog(onLog, `Failed to get tags: ${error.message || 'Unknown error'}`);\n }\n }\n\n /**\n * 为问题生成数据集\n * @param {Object} config - 配置信息\n * @param {string} config.projectId - 项目ID\n * @param {Object} config.model - 模型信息\n * @param {string} config.language - 语言\n * @param {Function} config.onProgress - 进度回调\n * @param {Function} config.onLog - 日志回调\n * @returns {Promise}\n */\n async generateDatasetsForQuestions(config) {\n const { projectId, model, language, concurrencyLimit = 5, onProgress, onLog } = config;\n\n // 设置当前阶段\n if (onProgress) {\n onProgress({\n stage: 'datasets'\n });\n }\n\n this.addLog(onLog, 'Question generation completed, starting to generate answers...');\n\n try {\n // 获取所有问题\n const response = await axios.get(`/api/projects/${projectId}/questions/tree?isDistill=true`);\n const allQuestions = response.data;\n\n // 找出未回答的问题\n const unansweredQuestions = allQuestions.filter(q => !q.answered);\n const answeredQuestions = allQuestions.filter(q => q.answered);\n\n // 更新总数据集数量和已生成数量\n if (onProgress) {\n onProgress({\n datasetsTotal: allQuestions.length, // 总数据集数量应为总问题数量\n datasetsBuilt: answeredQuestions.length // 已生成的数据集数量即已回答的问题数量\n });\n }\n\n this.addLog(onLog, `Found ${unansweredQuestions.length} unanswered questions, preparing to generate answers...`);\n this.addLog(onLog, `Dataset generation concurrency limit: ${concurrencyLimit}`);\n\n // 分批处理未回答的问题,控制并发数\n for (let i = 0; i < unansweredQuestions.length; i += concurrencyLimit) {\n const batch = unansweredQuestions.slice(i, i + concurrencyLimit);\n\n // 并行处理批次任务\n await Promise.all(\n batch.map(async question => {\n const questionContent = `${question.label} 下的问题ID:${question.id}`;\n this.addLog(onLog, `Generating answer for \"${questionContent}\"...`);\n\n try {\n // 调用生成数据集的函数\n await this.generateSingleDataset({\n projectId,\n questionId: question.id,\n questionInfo: question,\n model,\n language\n });\n\n // 更新生成的数据集数量\n if (onProgress) {\n onProgress({\n datasetsBuilt: 1,\n updateType: 'increment'\n });\n }\n\n this.addLog(onLog, `Successfully generated answer for question \"${questionContent}\"`);\n } catch (error) {\n console.error(`Failed to generate dataset for question \"${question.id}\":`, error);\n this.addLog(\n onLog,\n `Failed to generate answer for question \"${questionContent}\": ${error.message || 'Unknown error'}`\n );\n }\n })\n );\n\n // 每完成一批,输出一次进度日志\n this.addLog(\n onLog,\n `Completed batch ${Math.min(i + concurrencyLimit, unansweredQuestions.length)}/${unansweredQuestions.length} of dataset generation`\n );\n }\n } catch (error) {\n console.error('Failed to get questions:', error);\n this.addLog(onLog, `Failed to get questions: ${error.message || 'Unknown error'}`);\n }\n }\n\n /**\n * 生成单个数据集\n * @param {Object} config - 配置信息\n * @param {string} config.projectId - 项目ID\n * @param {string} config.questionId - 问题ID\n * @param {Object} config.questionInfo - 问题信息\n * @param {Object} config.model - 模型信息\n * @param {string} config.language - 语言\n * @returns {Promise} - 数据集信息\n */\n async generateSingleDataset({ projectId, questionId, questionInfo, model, language }) {\n try {\n // 构建请求参数\n const params = {\n model,\n language: language || 'zh-CN'\n };\n\n // 获取问题信息\n let question = questionInfo;\n if (!question) {\n const response = await axios.get(`/api/projects/${projectId}/questions/${questionId}`);\n question = response.data;\n }\n\n // 生成数据集\n const response = await axios.post(`/api/projects/${projectId}/datasets`, {\n projectId,\n questionId,\n model,\n language: language || 'zh-CN'\n });\n\n return response.data;\n } catch (error) {\n console.error('Failed to generate dataset:', error);\n throw new Error(`Failed to generate dataset: ${error.message}`);\n }\n }\n\n /**\n * 获取标签深度\n * @param {Object} tag - 标签信息\n * @param {Array} allTags - 所有标签\n * @returns {number} - 标签深度\n */\n getTagDepth(tag, allTags) {\n let depth = 1;\n let currentTag = tag;\n\n while (currentTag.parentId) {\n depth++;\n currentTag = allTags.find(t => t.id === currentTag.parentId);\n if (!currentTag) break;\n }\n\n return depth;\n }\n\n /**\n * 获取标签路径\n * @param {Object} tag - 标签信息\n * @param {Array} allTags - 所有标签\n * @returns {string} - 标签路径\n */\n /**\n * 获取标签路径,确保始终以项目名称开头\n * @param {Object} tag - 标签对象\n * @param {Array} allTags - 所有标签数组\n * @returns {string} 标签路径\n */\n getTagPath(tag, allTags) {\n // 使用已经获取的项目名称\n const projectName = this.projectName || '';\n\n // 构建标签路径\n const path = [];\n let currentTag = tag;\n\n while (currentTag) {\n path.unshift(currentTag.label);\n if (currentTag.parentId) {\n currentTag = allTags.find(t => t.id === currentTag.parentId);\n } else {\n currentTag = null;\n }\n }\n\n // 确保路径以项目名称开头\n if (projectName && path.length > 0 && path[0] !== projectName) {\n path.unshift(projectName);\n }\n\n return path.join(' > ');\n }\n\n /**\n * 添加日志\n * @param {Function} onLog - 日志回调\n * @param {string} message - 日志消息\n */\n addLog(onLog, message) {\n if (onLog && typeof onLog === 'function') {\n onLog(message);\n }\n }\n}\n\nexport const autoDistillService = new AutoDistillService();\nexport default autoDistillService;\n"], ["/easy-dataset/lib/llm/core/providers/openrouter.js", "import { createOpenRouter } from '@openrouter/ai-sdk-provider';\n\nimport BaseClient from './base.js';\n\nclass OpenRouterClient extends BaseClient {\n constructor(config) {\n super(config);\n this.openrouter = createOpenRouter({\n baseURL: this.endpoint,\n apiKey: this.apiKey\n });\n }\n\n _getModel() {\n return this.openrouter(this.model);\n }\n}\n\nmodule.exports = OpenRouterClient;\n"], ["/easy-dataset/lib/llm/common/util.js", "// 从 LLM 输出中提取 JSON\nfunction extractJsonFromLLMOutput(output) {\n console.log('LLM 输出:', output);\n if (output.trim().startsWith('', ''];\n const endTags = ['', ''];\n let startIndex = -1;\n let endIndex = -1;\n let usedStartTag = '';\n let usedEndTag = '';\n\n for (let i = 0; i < startTags.length; i++) {\n const currentStartIndex = text.indexOf(startTags[i]);\n if (currentStartIndex !== -1) {\n startIndex = currentStartIndex;\n usedStartTag = startTags[i];\n usedEndTag = endTags[i];\n break;\n }\n }\n\n if (startIndex === -1) {\n return '';\n }\n\n endIndex = text.indexOf(usedEndTag, startIndex + usedStartTag.length);\n\n if (endIndex === -1) {\n return '';\n }\n\n return text.slice(startIndex + usedStartTag.length, endIndex).trim();\n}\n\nfunction extractAnswer(text) {\n const startTags = ['', ''];\n const endTags = ['', ''];\n for (let i = 0; i < startTags.length; i++) {\n const start = startTags[i];\n const end = endTags[i];\n if (text.includes(start) && text.includes(end)) {\n const partsBefore = text.split(start);\n const partsAfter = partsBefore[1].split(end);\n return (partsBefore[0].trim() + ' ' + partsAfter[1].trim()).trim();\n }\n }\n return text;\n}\n\nmodule.exports = {\n extractJsonFromLLMOutput,\n extractThinkChain,\n extractAnswer\n};\n"], ["/easy-dataset/hooks/useModelPlayground.js", "'use client';\n\nimport { useState, useEffect } from 'react';\nimport { useAtomValue } from 'jotai/index';\nimport { modelConfigListAtom } from '@/lib/store';\n\nexport default function useModelPlayground(projectId, defaultModelId = null) {\n // 状态管理\n const [selectedModels, setSelectedModels] = useState(defaultModelId ? [defaultModelId] : []);\n const [loading, setLoading] = useState({});\n const [userInput, setUserInput] = useState('');\n const [conversations, setConversations] = useState({});\n const [error, setError] = useState(null);\n const [outputMode, setOutputMode] = useState('normal'); // 'normal' 或 'streaming'\n const [uploadedImage, setUploadedImage] = useState(null); // 存储上传的图片Base64\n\n const availableModels = useAtomValue(modelConfigListAtom);\n\n // 初始化会话状态\n useEffect(() => {\n if (selectedModels.length > 0) {\n const initialConversations = {};\n selectedModels.forEach(modelId => {\n if (!conversations[modelId]) {\n initialConversations[modelId] = [];\n }\n });\n\n if (Object.keys(initialConversations).length > 0) {\n setConversations(prev => ({\n ...prev,\n ...initialConversations\n }));\n }\n }\n }, [selectedModels]);\n\n // 处理模型选择\n const handleModelSelection = event => {\n const {\n target: { value }\n } = event;\n\n // 限制最多选择 3 个模型\n const selectedValues = typeof value === 'string' ? value.split(',') : value;\n const limitedSelection = selectedValues.slice(0, 3);\n\n setSelectedModels(limitedSelection);\n };\n\n // 处理用户输入\n const handleInputChange = e => {\n setUserInput(e.target.value);\n };\n\n // 处理图片上传\n const handleImageUpload = e => {\n const file = e.target.files[0];\n if (file) {\n const reader = new FileReader();\n reader.onloadend = () => {\n setUploadedImage(reader.result);\n };\n reader.readAsDataURL(file);\n }\n };\n\n // 删除已上传的图片\n const handleRemoveImage = () => {\n setUploadedImage(null);\n };\n\n // 处理输出模式切换\n const handleOutputModeChange = event => {\n setOutputMode(event.target.value);\n };\n\n // 发送消息给所有选中的模型\n const handleSendMessage = async () => {\n if (!userInput.trim() || Object.values(loading).some(value => value) || selectedModels.length === 0) return;\n\n // 获取用户输入\n const input = userInput.trim();\n setUserInput('');\n\n // 获取图片(如果有的话)\n const image = uploadedImage;\n setUploadedImage(null); // 清除图片\n\n // 更新所有选中模型的对话\n const updatedConversations = { ...conversations };\n selectedModels.forEach(modelId => {\n if (!updatedConversations[modelId]) {\n updatedConversations[modelId] = [];\n }\n // 检查是否有图片并且当前模型是视觉模型\n const model = availableModels.find(m => m.id === modelId);\n const isVisionModel = model && model.type === 'vision';\n\n if (isVisionModel && image) {\n // 如果是视觉模型并且有图片,使用复合格式\n updatedConversations[modelId].push({\n role: 'user',\n content: [\n { type: 'text', text: input || '请描述这个图片' },\n { type: 'image_url', image_url: { url: image } }\n ]\n });\n } else {\n // 其他情况使用纯文本\n updatedConversations[modelId].push({\n role: 'user',\n content: input\n });\n }\n });\n\n setConversations(updatedConversations);\n\n // 为每个模型设置独立的加载状态\n const updatedLoading = {};\n selectedModels.forEach(modelId => {\n updatedLoading[modelId] = true;\n });\n setLoading(updatedLoading);\n\n // 为每个模型单独发送请求\n selectedModels.forEach(async modelId => {\n const model = availableModels.find(m => m.id === modelId);\n if (!model) {\n // 模型配置不存在\n const modelConversation = [...(updatedConversations[modelId] || [])];\n\n // 更新对话状态\n setConversations(prev => ({\n ...prev,\n [modelId]: [...modelConversation, { role: 'error', content: '模型配置不存在' }]\n }));\n\n // 更新加载状态\n setLoading(prev => ({ ...prev, [modelId]: false }));\n return;\n }\n\n try {\n // 检查是否是视觉模型且有图片\n const isVisionModel = model.type === 'vision';\n\n // 构建请求消息\n let requestMessages = [...updatedConversations[modelId]]; // 复制当前消息历史\n\n // 如果是vision模型并且有图片,将最后一条用户消息替换为包含图片的消息\n if (isVisionModel && image && requestMessages.length > 0) {\n // 找到最后一条用户消息\n const lastUserMsgIndex = requestMessages.length - 1;\n // 替换为包含图片的消息\n requestMessages[lastUserMsgIndex] = {\n role: 'user',\n content: [\n { type: 'text', text: input || '请描述这个图片' },\n { type: 'image_url', image_url: { url: image } }\n ]\n };\n }\n\n // 根据输出模式选择不同的处理方式\n if (outputMode === 'streaming') {\n // 流式输出处理\n // 先添加一个空的助手回复,用于后续流式更新\n setConversations(prev => {\n const modelConversation = [...(prev[modelId] || [])];\n return {\n ...prev,\n [modelId]: [\n ...modelConversation,\n {\n role: 'assistant',\n content: '',\n isStreaming: true,\n thinking: '', // 添加推理过程字段\n showThinking: true // 默认显示推理过程\n }\n ]\n };\n });\n\n const response = await fetch(`/api/projects/${projectId}/playground/chat/stream`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n model: model,\n messages: requestMessages\n })\n });\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder('utf-8');\n let accumulatedContent = '';\n\n // 状态变量,用于跟踪是否正在处理思维链\n let isInThinking = false;\n let currentThinking = '';\n let currentContent = '';\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n // 解码收到的数据块\n const chunk = decoder.decode(value, { stream: true });\n\n // 处理当前数据块\n for (let i = 0; i < chunk.length; i++) {\n const char = chunk[i];\n\n // 检测开始标签 \n if (i + 6 <= chunk.length && chunk.substring(i, i + 7) === '') {\n isInThinking = true;\n i += 6; // 跳过标签\n continue;\n }\n\n // 检测结束标签 \n if (i + 7 <= chunk.length && chunk.substring(i, i + 8) === '') {\n isInThinking = false;\n i += 7; // 跳过标签\n continue;\n }\n\n // 根据当前状态添加到对应内容中\n if (isInThinking) {\n currentThinking += char;\n } else {\n currentContent += char;\n }\n }\n\n // 累积全部内容以便最终处理\n accumulatedContent += chunk;\n\n // 更新对话内容\n setConversations(prev => {\n const modelConversation = [...prev[modelId]];\n const lastIndex = modelConversation.length - 1;\n\n // 更新最后一条消息的内容,包括思维链\n modelConversation[lastIndex] = {\n ...modelConversation[lastIndex],\n content: currentContent,\n thinking: currentThinking,\n showThinking: currentThinking.length > 0 // 只要有思维链内容就显示\n };\n\n return {\n ...prev,\n [modelId]: modelConversation\n };\n });\n }\n\n // 完成流式传输,移除流式标记\n // 使用刚刚实时跟踪的 currentThinking 和 currentContent作为最终的思维链和内容\n let finalThinking = currentThinking;\n let finalAnswer = currentContent;\n\n // 如果到流结束时还在思维链中,确保解析完整的思维链内容\n if (isInThinking) {\n console.log('警告: 流结束时仍在思维链中,可能有标签不完整');\n isInThinking = false;\n }\n\n setConversations(prev => {\n const modelConversation = [...prev[modelId]];\n const lastIndex = modelConversation.length - 1;\n\n // 更新最后一条消息,移除流式标记\n modelConversation[lastIndex] = {\n role: 'assistant',\n content: finalAnswer,\n thinking: finalThinking,\n showThinking: finalThinking ? true : false,\n isStreaming: false\n };\n\n return {\n ...prev,\n [modelId]: modelConversation\n };\n });\n } else {\n // 普通输出处理\n const response = await fetch(`/api/projects/${projectId}/playground/chat`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n model: {\n ...model,\n extra_body: { enable_thinking: true } // 启用思考链\n },\n messages: requestMessages\n })\n });\n\n // 获取响应数据\n const data = await response.json();\n\n // 独立更新此模型的对话状态\n setConversations(prev => {\n const modelConversation = [...(prev[modelId] || [])];\n\n if (response.ok) {\n // 处理可能包含思考链的内容\n let thinking = '';\n let content = data.response;\n\n // 检查是否包含思考链\n if (content && content.includes('')) {\n const thinkParts = content.split(/(.*?)<\\/think>/s);\n if (thinkParts.length >= 3) {\n thinking = thinkParts[1] || '';\n // 移除思考链部分,只保留最终回答\n content = thinkParts.filter((_, i) => i % 2 === 0).join('');\n }\n }\n\n return {\n ...prev,\n [modelId]: [\n ...modelConversation,\n {\n role: 'assistant',\n content: content,\n thinking: thinking,\n showThinking: thinking ? true : false\n }\n ]\n };\n } else {\n return {\n ...prev,\n [modelId]: [...modelConversation, { role: 'error', content: `错误: ${data.error || '请求失败'}` }]\n };\n }\n });\n }\n } catch (error) {\n console.error(`请求模型 ${model.name} 失败:`, error);\n\n // 独立更新此模型的对话状态 - 添加错误消息\n setConversations(prev => {\n const modelConversation = [...(prev[modelId] || [])];\n return {\n ...prev,\n [modelId]: [...modelConversation, { role: 'error', content: `错误: ${error.message}` }]\n };\n });\n } finally {\n // 更新此模型的加载状态\n setLoading(prev => ({ ...prev, [modelId]: false }));\n }\n });\n };\n\n // 清空所有对话\n const handleClearConversations = () => {\n const clearedConversations = {};\n selectedModels.forEach(modelId => {\n clearedConversations[modelId] = [];\n });\n setConversations(clearedConversations);\n setLoading({});\n };\n\n // 获取模型名称\n const getModelName = modelId => {\n const model = availableModels.find(m => m.id === modelId);\n return model ? `${model.provider}: ${model.name}` : modelId;\n };\n\n return {\n availableModels,\n selectedModels,\n loading,\n userInput,\n conversations,\n error,\n outputMode,\n uploadedImage,\n handleModelSelection,\n handleInputChange,\n handleImageUpload,\n handleRemoveImage,\n handleSendMessage,\n handleClearConversations,\n handleOutputModeChange,\n getModelName\n };\n}\n"], ["/easy-dataset/components/ModelSelect.js", "'use client';\n\nimport React, { useEffect, useState, useMemo } from 'react';\nimport { FormControl, Select, MenuItem, useTheme, ListSubheader, Box } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\nimport { useAtom, useAtomValue } from 'jotai/index';\nimport { modelConfigListAtom, selectedModelInfoAtom } from '@/lib/store';\nimport axios from 'axios';\n\n// 获取模型对应的图标路径\nconst getModelIcon = modelName => {\n if (!modelName) return '/imgs/models/default.svg';\n\n // 将模型名称转换为小写以便比较\n const lowerModelName = modelName.toLowerCase();\n\n // 定义已知模型前缀映射\n const modelPrefixes = [\n { prefix: 'doubao', icon: 'doubao.svg' },\n { prefix: 'qwen', icon: 'qwen.svg' },\n { prefix: 'gpt', icon: 'gpt.svg' },\n { prefix: 'gemini', icon: 'gemini.svg' },\n { prefix: 'claude', icon: 'claude.svg' },\n { prefix: 'llama', icon: 'llama.svg' },\n { prefix: 'mistral', icon: 'mistral.svg' },\n { prefix: 'yi', icon: 'yi.svg' },\n { prefix: 'deepseek', icon: 'deepseek.svg' },\n { prefix: 'chatglm', icon: 'chatglm.svg' },\n { prefix: 'wenxin', icon: 'wenxin.svg' },\n { prefix: 'glm', icon: 'glm.svg' },\n { prefix: 'hunyuan', icon: 'hunyuan.svg' }\n\n // 添加更多模型前缀映射...\n ];\n\n // 查找匹配的模型前缀\n const matchedPrefix = modelPrefixes.find(({ prefix }) => lowerModelName.includes(prefix));\n\n // 返回对应的图标路径,如果没有匹配则返回默认图标\n return `/imgs/models/${matchedPrefix ? matchedPrefix.icon : 'default.svg'}`;\n};\n\nexport default function ModelSelect({\n size = 'small',\n minWidth = 50,\n projectId,\n minHeight = 36,\n required = false,\n onError\n}) {\n const theme = useTheme();\n const { t } = useTranslation();\n const models = useAtomValue(modelConfigListAtom);\n const [selectedModelInfo, setSelectedModelInfo] = useAtom(selectedModelInfoAtom);\n // 确保始终使用字符串值初始化 selectedModel,避免从非受控变为受控\n const [selectedModel, setSelectedModel] = useState(() => {\n if (selectedModelInfo && selectedModelInfo.id) {\n return selectedModelInfo.id;\n } else if (models && models.length > 0 && models[0]?.id) {\n return models[0].id;\n }\n return '';\n });\n const [error, setError] = useState(false);\n const handleModelChange = event => {\n if (!event || !event.target) return;\n const newModelId = event.target.value;\n\n // 清除错误状态\n if (error) {\n setError(false);\n if (onError) onError(false);\n }\n\n // 找到选中的模型对象\n const selectedModelObj = models.find(model => model.id === newModelId);\n if (selectedModelObj) {\n setSelectedModel(newModelId);\n // 将完整的模型信息存储到 localStorage\n setSelectedModelInfo(selectedModelObj);\n updateDefaultModel(newModelId);\n } else {\n setSelectedModelInfo({\n id: newModelId\n });\n }\n };\n\n const updateDefaultModel = async id => {\n const res = await axios.put(`/api/projects/${projectId}`, { projectId, defaultModelConfigId: id });\n if (res.status === 200) {\n console.log('更新成功');\n }\n };\n\n // 检查是否选择了模型\n const validateModel = () => {\n if (required && (!selectedModel || selectedModel === '')) {\n setError(true);\n if (onError) onError(true);\n return false;\n }\n return true;\n };\n\n useEffect(() => {\n if (selectedModelInfo && selectedModelInfo.id) {\n setSelectedModel(selectedModelInfo.id);\n }\n }, [selectedModelInfo]);\n\n // 初始检查\n useEffect(() => {\n if (required) {\n validateModel();\n }\n }, [required]);\n\n // 获取当前选中模型的显示内容\n const renderSelectedValue = value => {\n const selectedModelObj = models.find(model => model.id === value);\n if (!selectedModelObj) return null;\n\n return (\n \n {\n e.target.src = '/imgs/models/default.svg';\n }}\n />\n {selectedModelObj.modelName}\n \n );\n };\n\n return (\n \n \n \n {error ? t('models.pleaseSelectModel') : t('playground.selectModelFirst')}\n \n {(() => {\n // 按 provider 分组\n const filteredModels = models.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\n // 获取所有 provider\n const providers = [...new Set(filteredModels.map(m => m.providerName || 'Other'))];\n\n return providers.map(provider => {\n const providerModels = filteredModels.filter(m => (m.providerName || 'Other') === provider);\n return [\n \n {provider || 'Other'}\n ,\n ...providerModels.map(model => (\n \n {\n e.target.src = '/imgs/models/default.svg';\n }}\n />\n \n {model.modelName}\n \n \n ))\n ];\n });\n })()}\n \n \n );\n}\n"], ["/easy-dataset/constant/model.js", "export const MODEL_PROVIDERS = [\n {\n id: 'ollama',\n name: 'Ollama',\n defaultEndpoint: 'http://127.0.0.1:11434/api',\n defaultModels: []\n },\n {\n id: 'openai',\n name: 'OpenAI',\n defaultEndpoint: 'https://api.openai.com/v1/',\n defaultModels: ['gpt-4o', 'gpt-4o-mini', 'o1-mini']\n },\n {\n id: 'siliconcloud',\n name: '硅基流动',\n defaultEndpoint: 'https://api.siliconflow.cn/v1/',\n defaultModels: [\n 'deepseek-ai/DeepSeek-R1',\n 'deepseek-ai/DeepSeek-V3',\n 'Qwen2.5-7B-Instruct',\n 'meta-llama/Llama-3.3-70B-Instruct'\n ]\n },\n {\n id: 'deepseek',\n name: 'DeepSeek',\n defaultEndpoint: 'https://api.deepseek.com/v1/',\n defaultModels: ['deepseek-chat', 'deepseek-reasoner']\n },\n {\n id: '302ai',\n name: '302.AI',\n defaultEndpoint: 'https://api.302.ai/v1/',\n defaultModels: ['Doubao-pro-128k', 'deepseek-r1', 'kimi-latest', 'qwen-max']\n },\n {\n id: 'zhipu',\n name: '智谱AI',\n defaultEndpoint: 'https://open.bigmodel.cn/api/paas/v4/',\n defaultModels: ['glm-4-flash', 'glm-4-flashx', 'glm-4-plus', 'glm-4-long']\n },\n {\n id: 'Doubao',\n name: '火山引擎',\n defaultEndpoint: 'https://ark.cn-beijing.volces.com/api/v3/',\n defaultModels: []\n },\n {\n id: 'groq',\n name: 'Groq',\n defaultEndpoint: 'https://api.groq.com/openai',\n defaultModels: ['Gemma 7B', 'LLaMA3 8B', 'LLaMA3 70B']\n },\n {\n id: 'grok',\n name: 'Grok',\n defaultEndpoint: 'https://api.x.ai/v1',\n defaultModels: ['Grok Beta']\n },\n {\n id: 'OpenRouter',\n name: 'OpenRouter',\n defaultEndpoint: 'https://openrouter.ai/api/v1/',\n defaultModels: [\n 'google/gemma-2-9b-it:free',\n 'meta-llama/llama-3-8b-instruct:free',\n 'microsoft/phi-3-mini-128k-instruct:free'\n ]\n },\n {\n id: 'alibailian',\n name: '阿里云百炼',\n defaultEndpoint: 'https://dashscope.aliyuncs.com/compatible-mode/v1',\n defaultModels: ['qwen-max-latest', 'qwen-max-2025-01-25']\n }\n];\n\nexport const DEFAULT_MODEL_SETTINGS = {\n temperature: 0.7,\n maxTokens: 8192\n};\n"], ["/easy-dataset/lib/db/llm-providers.js", "'use server';\nimport { db } from '@/lib/db/index';\n\nexport async function getLlmProviders() {\n try {\n let list = await db.llmProviders.findMany();\n if (list.length !== 0) {\n return list;\n }\n\n let data = [\n {\n id: 'ollama',\n name: 'Ollama',\n apiUrl: 'http://127.0.0.1:11434/api'\n },\n {\n id: 'openai',\n name: 'OpenAI',\n apiUrl: 'https://api.openai.com/v1/'\n },\n {\n id: 'siliconcloud',\n name: '硅基流动',\n apiUrl: 'https://api.siliconflow.cn/v1/'\n },\n {\n id: 'deepseek',\n name: 'DeepSeek',\n apiUrl: 'https://api.deepseek.com/v1/'\n },\n {\n id: '302ai',\n name: '302.AI',\n apiUrl: 'https://api.302.ai/v1/'\n },\n {\n id: 'zhipu',\n name: '智谱AI',\n apiUrl: 'https://open.bigmodel.cn/api/paas/v4/'\n },\n {\n id: 'Doubao',\n name: '火山引擎',\n apiUrl: 'https://ark.cn-beijing.volces.com/api/v3/'\n },\n {\n id: 'groq',\n name: 'Groq',\n apiUrl: 'https://api.groq.com/openai'\n },\n {\n id: 'grok',\n name: 'Grok',\n apiUrl: 'https://api.x.ai'\n },\n {\n id: 'openRouter',\n name: 'OpenRouter',\n apiUrl: 'https://openrouter.ai/api/v1/'\n },\n {\n id: 'alibailian',\n name: '阿里云百炼',\n apiUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1'\n }\n ];\n await db.llmProviders.createMany({ data });\n return data;\n } catch (error) {\n console.error('Failed to get llmProviders in database');\n throw error;\n }\n}\n"], ["/easy-dataset/app/projects/[projectId]/datasets/[datasetId]/useDatasetDetails.js", "'use client';\n\nimport { useState, useEffect } from 'react';\nimport { useRouter } from 'next/navigation';\nimport { useAtomValue } from 'jotai/index';\nimport { selectedModelInfoAtom } from '@/lib/store';\nimport axios from 'axios';\nimport { toast } from 'sonner';\nimport i18n from '@/lib/i18n';\n\n/**\n * 数据集详情页面业务逻辑 Hook\n */\nexport default function useDatasetDetails(projectId, datasetId) {\n const router = useRouter();\n const [datasets, setDatasets] = useState([]);\n const [currentDataset, setCurrentDataset] = useState(null);\n const [loading, setLoading] = useState(true);\n const [editingAnswer, setEditingAnswer] = useState(false);\n const [editingCot, setEditingCot] = useState(false);\n const [answerValue, setAnswerValue] = useState('');\n const [cotValue, setCotValue] = useState('');\n const [snackbar, setSnackbar] = useState({\n open: false,\n message: '',\n severity: 'success'\n });\n const [confirming, setConfirming] = useState(false);\n const [optimizeDialog, setOptimizeDialog] = useState({\n open: false,\n loading: false\n });\n const [viewDialogOpen, setViewDialogOpen] = useState(false);\n const [viewChunk, setViewChunk] = useState(null);\n const [datasetsAllCount, setDatasetsAllCount] = useState(0);\n const [datasetsConfirmCount, setDatasetsConfirmCount] = useState(0);\n const [answerTokens, setAnswerTokens] = useState(0);\n const [cotTokens, setCotTokens] = useState(0);\n const model = useAtomValue(selectedModelInfoAtom);\n const [shortcutsEnabled, setShortcutsEnabled] = useState(() => {\n const storedValue = localStorage.getItem('shortcutsEnabled');\n return storedValue !== null ? storedValue === 'true' : false;\n });\n\n // 异步获取Token数量\n const fetchTokenCount = async () => {\n try {\n const response = await fetch(`/api/projects/${projectId}/datasets/${datasetId}/token-count`);\n if (response.ok) {\n const data = await response.json();\n if (data.answerTokens !== undefined) {\n setAnswerTokens(data.answerTokens);\n }\n if (data.cotTokens !== undefined) {\n setCotTokens(data.cotTokens);\n }\n }\n } catch (error) {\n console.error('获取Token数量失败:', error);\n // Token加载失败不阻塞主界面或显示错误提示\n }\n };\n\n // 获取数据集详情\n const fetchDatasets = async () => {\n try {\n const response = await fetch(`/api/projects/${projectId}/datasets/${datasetId}`);\n if (!response.ok) throw new Error('获取数据集详情失败');\n const data = await response.json();\n setCurrentDataset(data.datasets);\n setCotValue(data.datasets?.cot);\n setAnswerValue(data.datasets?.answer);\n setDatasetsAllCount(data.total);\n setDatasetsConfirmCount(data.confirmedCount);\n\n // 数据加载完成后,异步获取Token数量\n fetchTokenCount();\n } catch (error) {\n setSnackbar({\n open: true,\n message: error.message,\n severity: 'error'\n });\n } finally {\n setLoading(false);\n }\n };\n\n // 确认并保存数据集\n const handleConfirm = async () => {\n try {\n setConfirming(true);\n const response = await fetch(`/api/projects/${projectId}/datasets?id=${datasetId}`, {\n method: 'PATCH',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n confirmed: true\n })\n });\n\n if (!response.ok) {\n throw new Error('操作失败');\n }\n\n setCurrentDataset(prev => ({ ...prev, confirmed: true }));\n\n setSnackbar({\n open: true,\n message: '操作成功',\n severity: 'success'\n });\n\n // 导航到下一个数据集\n handleNavigate('next');\n } catch (error) {\n setSnackbar({\n open: true,\n message: error.message || '操作失败',\n severity: 'error'\n });\n } finally {\n setConfirming(false);\n }\n };\n\n // 导航到其他数据集\n const handleNavigate = async direction => {\n const response = await axios.get(`/api/projects/${projectId}/datasets/${datasetId}?operateType=${direction}`);\n if (response.data) {\n router.push(`/projects/${projectId}/datasets/${response.data.id}`);\n } else {\n toast.warning(`已经是${direction === 'next' ? '最后' : '第'}一条数据了`);\n }\n };\n\n // 保存编辑\n const handleSave = async (field, value) => {\n try {\n const response = await fetch(`/api/projects/${projectId}/datasets?id=${datasetId}`, {\n method: 'PATCH',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n [field]: value\n })\n });\n\n if (!response.ok) {\n throw new Error('保存失败');\n }\n\n const data = await response.json();\n setCurrentDataset(prev => ({ ...prev, [field]: value }));\n\n setSnackbar({\n open: true,\n message: '保存成功',\n severity: 'success'\n });\n\n // 重置编辑状态\n if (field === 'answer') setEditingAnswer(false);\n if (field === 'cot') setEditingCot(false);\n } catch (error) {\n setSnackbar({\n open: true,\n message: error.message || '保存失败',\n severity: 'error'\n });\n }\n };\n\n // 删除数据集\n const handleDelete = async () => {\n if (!confirm('确定要删除这条数据吗?此操作不可撤销。')) return;\n\n try {\n // 尝试获取下一个数据集,在删除前先确保有可导航的目标\n const nextResponse = await axios.get(`/api/projects/${projectId}/datasets/${datasetId}?operateType=next`);\n const hasNextDataset = !!nextResponse.data;\n const nextDatasetId = hasNextDataset ? nextResponse.data.id : null;\n\n // 删除当前数据集\n const deleteResponse = await fetch(`/api/projects/${projectId}/datasets?id=${datasetId}`, {\n method: 'DELETE'\n });\n\n if (!deleteResponse.ok) {\n throw new Error('删除失败');\n }\n\n // 导航逻辑:有下一个就跳转下一个,没有则返回列表页\n if (hasNextDataset) {\n router.push(`/projects/${projectId}/datasets/${nextDatasetId}`);\n } else {\n // 没有更多数据集,返回列表页面\n router.push(`/projects/${projectId}/datasets`);\n }\n\n toast.success('删除成功');\n } catch (error) {\n setSnackbar({\n open: true,\n message: error.message || '删除失败',\n severity: 'error'\n });\n }\n };\n\n // 优化对话框相关操作\n const handleOpenOptimizeDialog = () => {\n setOptimizeDialog({\n open: true,\n loading: false\n });\n };\n\n const handleCloseOptimizeDialog = () => {\n if (optimizeDialog.loading) return;\n setOptimizeDialog({\n open: false,\n loading: false\n });\n };\n\n // 优化操作\n const handleOptimize = async advice => {\n if (!model) {\n setSnackbar({\n open: true,\n message: '请先选择模型,可以在顶部导航栏选择',\n severity: 'error'\n });\n setOptimizeDialog(prev => ({ ...prev, open: false }));\n return;\n }\n\n try {\n setOptimizeDialog(prev => ({ ...prev, loading: true }));\n const language = i18n.language === 'zh-CN' ? '中文' : 'en';\n const response = await fetch(`/api/projects/${projectId}/datasets/optimize`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n datasetId,\n model,\n advice,\n language\n })\n });\n\n if (!response.ok) {\n const errorData = await response.json();\n throw new Error(errorData.error || '优化失败');\n }\n\n // 优化成功后,重新查询数据以获取最新状态\n await fetchDatasets();\n // 优化可能改变了文本内容,重新获取Token计数\n fetchTokenCount();\n\n setSnackbar({\n open: true,\n message: 'AI智能优化成功',\n severity: 'success'\n });\n } catch (error) {\n setSnackbar({\n open: true,\n message: error.message || '优化失败',\n severity: 'error'\n });\n } finally {\n setOptimizeDialog({\n open: false,\n loading: false\n });\n }\n };\n\n // 查看文本块详情\n const handleViewChunk = async chunkContent => {\n try {\n setViewChunk(chunkContent);\n setViewDialogOpen(true);\n } catch (error) {\n console.error('查看文本块出错', error);\n setSnackbar({\n open: true,\n message: error.message,\n severity: 'error'\n });\n setViewDialogOpen(false);\n }\n };\n\n // 关闭文本块详情对话框\n const handleCloseViewDialog = () => {\n setViewDialogOpen(false);\n };\n\n // 初始化和快捷键事件\n useEffect(() => {\n fetchDatasets();\n }, [projectId, datasetId]);\n\n // 快捷键状态变化\n useEffect(() => {\n localStorage.setItem('shortcutsEnabled', shortcutsEnabled);\n }, [shortcutsEnabled]);\n\n // 监听键盘事件\n useEffect(() => {\n const handleKeyDown = event => {\n if (!shortcutsEnabled) return;\n switch (event.key) {\n case 'ArrowLeft': // 上一个\n handleNavigate('prev');\n break;\n case 'ArrowRight': // 下一个\n handleNavigate('next');\n break;\n case 'y': // 确认\n case 'Y':\n if (!confirming && currentDataset && !currentDataset.confirmed) {\n handleConfirm();\n }\n break;\n case 'd': // 删除\n case 'D':\n handleDelete();\n break;\n default:\n break;\n }\n };\n window.addEventListener('keydown', handleKeyDown);\n return () => {\n window.removeEventListener('keydown', handleKeyDown);\n };\n }, [shortcutsEnabled, confirming, currentDataset]);\n\n return {\n loading,\n currentDataset,\n answerValue,\n cotValue,\n editingAnswer,\n editingCot,\n confirming,\n snackbar,\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 };\n}\n"], ["/easy-dataset/app/api/llm/fetch-models/route.js", "import { NextResponse } from 'next/server';\nimport axios from 'axios';\n\n// 从模型提供商获取模型列表\nexport async function POST(request) {\n try {\n const { endpoint, providerId, apiKey } = await request.json();\n\n if (!endpoint) {\n return NextResponse.json({ error: '缺少 endpoint 参数' }, { status: 400 });\n }\n\n let url = endpoint.replace(/\\/$/, ''); // 去除末尾的斜杠\n url += providerId === 'ollama' ? '/tags' : '/models';\n\n const headers = {};\n if (apiKey) {\n headers.Authorization = `Bearer ${apiKey}`;\n }\n\n const response = await axios.get(url, { headers });\n\n // 根据不同提供商格式化返回数据\n let formattedModels = [];\n if (providerId === 'ollama') {\n formattedModels = response.data.models.map(item => ({\n modelId: item.model,\n modelName: item.name,\n providerId\n }));\n } else {\n // 默认处理方式(适用于 OpenAI 等)\n formattedModels = response.data.data.map(item => ({\n modelId: item.id,\n modelName: item.id,\n providerId\n }));\n }\n\n return NextResponse.json(formattedModels);\n } catch (error) {\n console.error('获取模型列表失败:', String(error));\n\n // 处理特定错误\n if (error.response) {\n if (error.response.status === 401) {\n return NextResponse.json({ error: 'API Key 无效' }, { status: 401 });\n }\n return NextResponse.json(\n { error: `获取模型列表失败: ${error.response.statusText}` },\n { status: error.response.status }\n );\n }\n\n return NextResponse.json({ error: `获取模型列表失败: ${error.message}` }, { status: 500 });\n }\n}\n"], ["/easy-dataset/components/export/LlamaFactoryTab.js", "// LlamaFactoryTab.js 组件\nimport React, { useState, useEffect } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport {\n Button,\n FormControlLabel,\n Checkbox,\n Typography,\n Box,\n TextField,\n Alert,\n CircularProgress,\n IconButton,\n Tooltip\n} from '@mui/material';\nimport ContentCopyIcon from '@mui/icons-material/ContentCopy';\nimport CheckIcon from '@mui/icons-material/Check';\n\nconst LlamaFactoryTab = ({\n projectId,\n systemPrompt,\n confirmedOnly,\n includeCOT,\n formatType,\n handleSystemPromptChange,\n handleConfirmedOnlyChange,\n handleIncludeCOTChange\n}) => {\n const { t } = useTranslation();\n const [configExists, setConfigExists] = useState(false);\n const [configPath, setConfigPath] = useState('');\n const [generating, setGenerating] = useState(false);\n const [error, setError] = useState('');\n const [copied, setCopied] = useState(false);\n\n // 检查配置文件是否存在\n useEffect(() => {\n if (projectId) {\n fetch(`/api/projects/${projectId}/llamaFactory/checkConfig`)\n .then(res => res.json())\n .then(data => {\n setConfigExists(data.exists);\n if (data.exists) {\n setConfigPath(data.configPath);\n }\n })\n .catch(err => {\n setError(err.message);\n });\n }\n }, [projectId, configExists]);\n\n // 复制路径到剪贴板\n const handleCopyPath = () => {\n const path = configPath.replace('dataset_info.json', '');\n navigator.clipboard.writeText(path).then(() => {\n setCopied(true);\n setTimeout(() => setCopied(false), 2000);\n });\n };\n\n // 处理生成 Llama Factory 配置\n const handleGenerateConfig = async () => {\n try {\n setGenerating(true);\n setError('');\n\n const response = await fetch(`/api/projects/${projectId}/llamaFactory/generate`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n formatType,\n systemPrompt,\n confirmedOnly,\n includeCOT\n })\n });\n\n const data = await response.json();\n if (!response.ok) {\n throw new Error(data.error);\n }\n\n setConfigExists(true);\n } catch (err) {\n setError(err.message);\n } finally {\n setGenerating(false);\n }\n };\n\n return (\n \n {error && (\n \n {error}\n \n )}\n\n \n \n {t('export.systemPrompt')}\n \n \n \n\n \n }\n label={t('export.onlyConfirmed')}\n />\n\n }\n label={t('export.includeCOT')}\n />\n \n\n {configExists ? (\n <>\n \n {t('export.configExists')}\n \n \n \n {t('export.configPath')}: {configPath.replace('dataset_info.json', '')}\n \n \n \n {copied ? : }\n \n \n \n \n ) : (\n \n {t('export.noConfig')}\n \n )}\n\n \n \n \n \n );\n};\n\nexport default LlamaFactoryTab;\n"], ["/easy-dataset/lib/file/split-markdown/core/toc.js", "/**\n * Markdown目录提取模块\n */\n\n/**\n * 提取Markdown文档的目录结构\n * @param {string} text - Markdown文本\n * @param {Object} options - 配置选项\n * @param {number} options.maxLevel - 提取的最大标题级别,默认为6\n * @param {boolean} options.includeLinks - 是否包含锚点链接,默认为true\n * @param {boolean} options.flatList - 是否返回扁平列表,默认为false(返回嵌套结构)\n * @returns {Array} - 目录结构数组\n */\nfunction extractTableOfContents(text, options = {}) {\n const { maxLevel = 6, includeLinks = true, flatList = false } = options;\n\n // 匹配标题的正则表达式\n const headingRegex = /^(#{1,6})\\s+(.+?)(?:\\s*\\{#[\\w-]+\\})?\\s*$/gm;\n const tocItems = [];\n let match;\n\n while ((match = headingRegex.exec(text)) !== null) {\n const level = match[1].length;\n\n // 如果标题级别超过了设定的最大级别,则跳过\n if (level > maxLevel) {\n continue;\n }\n\n const title = match[2].trim();\n const position = match.index;\n\n // 生成锚点ID(用于链接)\n const anchorId = generateAnchorId(title);\n\n tocItems.push({\n level,\n title,\n position,\n anchorId,\n children: []\n });\n }\n\n // 如果需要返回扁平列表,直接返回处理后的结果\n if (flatList) {\n return tocItems.map(item => {\n const result = {\n level: item.level,\n title: item.title,\n position: item.position\n };\n\n if (includeLinks) {\n result.link = `#${item.anchorId}`;\n }\n\n return result;\n });\n }\n\n // 构建嵌套结构\n return buildNestedToc(tocItems, includeLinks);\n}\n\n/**\n * 生成标题的锚点ID\n * @param {string} title - 标题文本\n * @returns {string} - 生成的锚点ID\n */\nfunction generateAnchorId(title) {\n return title\n .toLowerCase()\n .replace(/\\s+/g, '-')\n .replace(/[^\\w\\-]/g, '')\n .replace(/\\-+/g, '-')\n .replace(/^\\-+|\\-+$/g, '');\n}\n\n/**\n * 构建嵌套的目录结构\n * @param {Array} items - 扁平的目录项数组\n * @param {boolean} includeLinks - 是否包含链接\n * @returns {Array} - 嵌套的目录结构\n */\nfunction buildNestedToc(items, includeLinks) {\n const result = [];\n const stack = [{ level: 0, children: result }];\n\n items.forEach(item => {\n const tocItem = {\n title: item.title,\n level: item.level,\n position: item.position,\n children: []\n };\n\n if (includeLinks) {\n tocItem.link = `#${item.anchorId}`;\n }\n\n // 找到当前项的父级\n while (stack[stack.length - 1].level >= item.level) {\n stack.pop();\n }\n\n // 将当前项添加到父级的children中\n stack[stack.length - 1].children.push(tocItem);\n\n // 将当前项入栈\n stack.push(tocItem);\n });\n\n return result;\n}\n\n/**\n * 将目录结构转换为Markdown格式\n * @param {Array} toc - 目录结构(嵌套或扁平)\n * @param {Object} options - 配置选项\n * @param {boolean} options.isNested - 是否为嵌套结构,默认为true\n * @param {boolean} options.includeLinks - 是否包含链接,默认为true\n * @returns {string} - Markdown格式的目录\n */\nfunction tocToMarkdown(toc, options = {}) {\n const { isNested = true, includeLinks = true } = options;\n\n if (isNested) {\n return nestedTocToMarkdown(toc, 0, includeLinks);\n } else {\n return flatTocToMarkdown(toc, includeLinks);\n }\n}\n\n/**\n * 将嵌套的目录结构转换为Markdown格式\n * @private\n */\nfunction nestedTocToMarkdown(items, indent = 0, includeLinks) {\n let result = '';\n const indentStr = ' '.repeat(indent);\n\n // 添加数据验证\n if (!Array.isArray(items)) {\n console.warn('Warning: items is not an array in nestedTocToMarkdown');\n return result;\n }\n\n items.forEach(item => {\n const titleText = includeLinks && item.link ? `[${item.title}](${item.link})` : item.title;\n\n result += `${indentStr}- ${titleText}\\n`;\n\n if (item.children && item.children.length > 0) {\n result += nestedTocToMarkdown(item.children, indent + 1, includeLinks);\n }\n });\n\n return result;\n}\n\n/**\n * 将扁平的目录结构转换为Markdown格式\n * @private\n */\nfunction flatTocToMarkdown(items, includeLinks) {\n let result = '';\n\n items.forEach(item => {\n const indent = ' '.repeat(item.level - 1);\n const titleText = includeLinks && item.link ? `[${item.title}](${item.link})` : item.title;\n\n result += `${indent}- ${titleText}\\n`;\n });\n\n return result;\n}\n\nmodule.exports = {\n extractTableOfContents,\n tocToMarkdown\n};\n"], ["/easy-dataset/lib/file/text-splitter.js", "'use server';\n\nimport fs from 'fs';\nimport path from 'path';\nimport { getProjectRoot, ensureDir } from '../db/base';\nimport { getProject } from '@/lib/db/projects';\nimport { getChunkByProjectId, saveChunks } from '@/lib/db/chunks';\nconst {\n TokenTextSplitter,\n CharacterTextSplitter,\n RecursiveCharacterTextSplitter\n} = require('@langchain/textsplitters');\nconst { Document } = require('@langchain/core/documents');\n\n// 导入Markdown分割工具\nconst markdownSplitter = require('./split-markdown/index');\n\nasync function splitFileByType({ projectPath, fileContent, fileName, projectId, fileId }) {\n // 获取任务配置\n const taskConfigPath = path.join(projectPath, 'task-config.json');\n let taskConfig;\n\n try {\n await fs.promises.access(taskConfigPath);\n const taskConfigData = await fs.promises.readFile(taskConfigPath, 'utf8');\n taskConfig = JSON.parse(taskConfigData);\n } catch (error) {\n taskConfig = {\n textSplitMinLength: 1500,\n textSplitMaxLength: 2000\n };\n }\n // 获取分割参数\n const minLength = taskConfig.textSplitMinLength || 1500;\n const maxLength = taskConfig.textSplitMaxLength || 2000;\n const chunkSize = taskConfig.chunkSize || 1500;\n const chunkOverlap = taskConfig.chunkOverlap || 200;\n const separator = taskConfig.separator || '\\n\\n';\n const separators = taskConfig.separators || ['|', '##', '>', '-'];\n const splitLanguage = taskConfig.splitType || 'js';\n const splitType = taskConfig.splitType;\n\n if (splitType === 'text') {\n // 字符分块\n const textSplitter = new CharacterTextSplitter({\n separator,\n chunkSize,\n chunkOverlap\n });\n const splitResult = await textSplitter.createDocuments([fileContent]);\n return splitResult.map((part, index) => {\n const chunkId = `${path.basename(fileName, path.extname(fileName))}-part-${index + 1}`;\n return {\n projectId,\n name: chunkId,\n fileId,\n fileName,\n content: part.pageContent,\n summary: '',\n size: part.pageContent.length\n };\n });\n } else if (splitType === 'token') {\n // Token 分块\n const textSplitter = new TokenTextSplitter({\n chunkSize,\n chunkOverlap\n });\n const splitResult = await textSplitter.splitText(fileContent);\n return splitResult.map((part, index) => {\n const chunkId = `${path.basename(fileName, path.extname(fileName))}-part-${index + 1}`;\n return {\n projectId,\n name: chunkId,\n fileId,\n fileName,\n content: part,\n summary: '',\n size: part.length\n };\n });\n } else if (splitType === 'code') {\n // 递归分块\n const textSplitter = new RecursiveCharacterTextSplitter({\n chunkSize,\n chunkOverlap,\n separators\n });\n const jsSplitter = RecursiveCharacterTextSplitter.fromLanguage(splitLanguage, {\n chunkSize,\n chunkOverlap\n });\n const splitResult = await jsSplitter.createDocuments([fileContent]);\n return splitResult.map((part, index) => {\n const chunkId = `${path.basename(fileName, path.extname(fileName))}-part-${index + 1}`;\n return {\n projectId,\n name: chunkId,\n fileId,\n fileName,\n content: part.pageContent,\n summary: '',\n size: part.pageContent.length\n };\n });\n } else if (splitType === 'recursive') {\n // 递归分块\n const textSplitter = new RecursiveCharacterTextSplitter({\n chunkSize,\n chunkOverlap,\n separators\n });\n const splitResult = await textSplitter.splitDocuments([new Document({ pageContent: fileContent })]);\n return splitResult.map((part, index) => {\n const chunkId = `${path.basename(fileName, path.extname(fileName))}-part-${index + 1}`;\n return {\n projectId,\n name: chunkId,\n fileId,\n fileName,\n content: part.pageContent,\n summary: '',\n size: part.pageContent.length\n };\n });\n } else {\n // 默认采用之前的分块方法\n const splitResult = markdownSplitter.splitMarkdown(fileContent, minLength, maxLength);\n return splitResult.map((part, index) => {\n const chunkId = `${path.basename(fileName, path.extname(fileName))}-part-${index + 1}`;\n return {\n projectId,\n name: chunkId,\n fileId,\n fileName,\n content: part.content,\n summary: part.summary,\n size: part.content.length\n };\n });\n }\n}\n\n/**\n * 分割项目中的Markdown文件\n * @param {string} projectId - 项目ID\n * @param {string} fileName - 文件名\n * @returns {Promise} - 分割结果数组\n */\nexport async function splitProjectFile(projectId, file) {\n const { fileName, fileId } = file;\n try {\n // 获取项目根目录\n const projectRoot = await getProjectRoot();\n const projectPath = path.join(projectRoot, projectId);\n let filePath = path.join(projectPath, 'files', fileName);\n\n if (!filePath.endsWith('.md')) {\n filePath = path.join(projectPath, 'files', fileName.replace(/\\.[^/.]+$/, '.md'));\n }\n try {\n await fs.promises.access(filePath);\n } catch (error) {\n throw new Error(`文件 ${fileName} 不存在`);\n }\n\n // 读取文件内容\n const fileContent = await fs.promises.readFile(filePath, 'utf8');\n\n // 保存分割结果到chunks目录\n const savedChunks = await splitFileByType({ projectPath, fileContent, fileName, projectId, fileId });\n await saveChunks(savedChunks);\n\n // 提取目录结构(如果需要所有文件的内容拼接后再提取目录)\n const tocJSON = markdownSplitter.extractTableOfContents(fileContent);\n const toc = markdownSplitter.tocToMarkdown(tocJSON, { isNested: true });\n\n // 保存目录结构到单独的toc文件夹\n const tocDir = path.join(projectPath, 'toc');\n await ensureDir(tocDir);\n const tocPath = path.join(tocDir, `${path.basename(fileName, path.extname(fileName))}-toc.json`);\n await fs.promises.writeFile(tocPath, JSON.stringify(tocJSON, null, 2));\n\n return {\n fileName,\n totalChunks: savedChunks.length,\n chunks: savedChunks,\n toc\n };\n } catch (error) {\n console.error('文本分割出错:', error);\n throw error;\n }\n}\n\n/**\n * 获取项目中的所有文本块\n * @param {string} projectId - 项目ID\n * @returns {Promise} - 文本块详细信息数组\n */\nexport async function getProjectChunks(projectId, filter) {\n try {\n const projectRoot = await getProjectRoot();\n const projectPath = path.join(projectRoot, projectId);\n const tocDir = path.join(projectPath, 'toc');\n const project = await getProject(projectId);\n\n let chunks = await getChunkByProjectId(projectId, filter);\n // 读取所有TOC文件\n const tocByFile = {};\n let toc = '';\n try {\n await fs.promises.access(tocDir);\n const tocFiles = await fs.promises.readdir(tocDir);\n\n for (const tocFile of tocFiles) {\n if (tocFile.endsWith('-toc.json')) {\n const tocPath = path.join(tocDir, tocFile);\n const tocContent = await fs.promises.readFile(tocPath, 'utf8');\n const fileName = tocFile.replace('-toc.json', '.md');\n\n try {\n tocByFile[fileName] = JSON.parse(tocContent);\n toc += '# File:' + fileName + '\\n';\n toc += markdownSplitter.tocToMarkdown(tocByFile[fileName], { isNested: true }) + '\\n';\n } catch (e) {\n console.error(`解析TOC文件 ${tocFile} 出错:`, e);\n }\n }\n }\n } catch (error) {\n // TOC目录不存在或读取出错,继续处理\n }\n // 整合结果\n let fileResult = {\n fileName: project.name + '.md',\n totalChunks: chunks.length,\n chunks,\n toc\n };\n\n return {\n fileResult, // 单个文件结果,而不是数组\n chunks\n };\n } catch (error) {\n console.error('获取文本块出错:', error);\n throw error;\n }\n}\n\n/**\n * 获取项目中的所有目录\n * @param {string} projectId - 项目ID\n */\nexport async function getProjectTocs(projectId) {\n try {\n const projectRoot = await getProjectRoot();\n const projectPath = path.join(projectRoot, projectId);\n const tocDir = path.join(projectPath, 'toc');\n\n // 读取所有TOC文件\n const tocByFile = {};\n let toc = '';\n try {\n await fs.promises.access(tocDir);\n const tocFiles = await fs.promises.readdir(tocDir);\n\n for (const tocFile of tocFiles) {\n if (tocFile.endsWith('-toc.json')) {\n const tocPath = path.join(tocDir, tocFile);\n const tocContent = await fs.promises.readFile(tocPath, 'utf8');\n const fileName = tocFile.replace('-toc.json', '.md');\n\n try {\n tocByFile[fileName] = JSON.parse(tocContent);\n toc += '# File:' + fileName + '\\n';\n toc += markdownSplitter.tocToMarkdown(tocByFile[fileName], { isNested: true }) + '\\n';\n } catch (e) {\n console.error(`解析TOC文件 ${tocFile} 出错:`, e);\n }\n }\n }\n } catch (error) {\n // TOC目录不存在或读取出错,继续处理\n }\n\n return toc;\n } catch (error) {\n console.error('获取文本块出错:', error);\n throw error;\n }\n}\n\n/**\n * 指定文件的目录\n */\nexport async function getProjectTocByName(projectId, fileName) {\n try {\n const projectRoot = await getProjectRoot();\n const projectPath = path.join(projectRoot, projectId);\n const tocDir = path.join(projectPath, 'toc');\n\n // 读取所有TOC文件\n const tocByFile = {};\n let toc = '';\n try {\n await fs.promises.access(tocDir);\n const tocFiles = await fs.promises.readdir(tocDir);\n\n for (const tocFile of tocFiles) {\n if (tocFile.endsWith(fileName.replace('.md', '') + '-toc.json')) {\n const tocPath = path.join(tocDir, tocFile);\n const tocContent = await fs.promises.readFile(tocPath, 'utf8');\n const fileName = tocFile.replace('-toc.json', '.md');\n\n try {\n tocByFile[fileName] = JSON.parse(tocContent);\n toc += '# File:' + fileName + '\\n';\n toc += markdownSplitter.tocToMarkdown(tocByFile[fileName], { isNested: true }) + '\\n';\n } catch (e) {\n console.error(`解析TOC文件 ${tocFile} 出错:`, e);\n }\n }\n }\n } catch (error) {\n // TOC目录不存在或读取出错,继续处理\n }\n\n return toc;\n } catch (error) {\n console.error('获取文本块出错:', error);\n throw error;\n }\n}\n"], ["/easy-dataset/app/api/projects/[projectId]/huggingface/upload/route.js", "import { NextResponse } from 'next/server';\nimport { getProject } from '@/lib/db/projects';\nimport { getDatasets } from '@/lib/db/datasets';\nimport fs from 'fs';\nimport path from 'path';\nimport os from 'os';\nimport { uploadFiles, createRepo, checkRepoAccess } from '@huggingface/hub';\n\n// 上传数据集到 HuggingFace\nexport async function POST(request, { params }) {\n try {\n const projectId = params.projectId;\n const {\n token,\n datasetName,\n isPrivate,\n formatType,\n systemPrompt,\n confirmedOnly,\n includeCOT,\n fileFormat,\n customFields\n } = await request.json();\n\n // 获取项目信息\n const project = await getProject(projectId);\n if (!project) {\n return NextResponse.json({ error: '项目不存在' }, { status: 404 });\n }\n\n // 获取数据集问题\n const questions = await getDatasets(projectId, confirmedOnly);\n if (!questions || questions.length === 0) {\n return NextResponse.json({ error: '没有可用的数据集问题' }, { status: 400 });\n }\n\n // 格式化数据集\n const formattedData = formatDataset(questions, formatType, systemPrompt, includeCOT, customFields);\n\n // 创建临时目录\n const tempDir = path.join(os.tmpdir(), `hf-upload-${projectId}-${Date.now()}`);\n fs.mkdirSync(tempDir, { recursive: true });\n\n // 创建数据集文件\n const datasetFilePath = path.join(tempDir, `dataset.${fileFormat}`);\n if (fileFormat === 'json') {\n fs.writeFileSync(datasetFilePath, JSON.stringify(formattedData, null, 2));\n } else if (fileFormat === 'jsonl') {\n const jsonlContent = formattedData.map(item => JSON.stringify(item)).join('\\n');\n fs.writeFileSync(datasetFilePath, jsonlContent);\n } else if (fileFormat === 'csv') {\n const csvContent = convertToCSV(formattedData);\n fs.writeFileSync(datasetFilePath, csvContent);\n }\n\n // 创建 README.md 文件\n const readmePath = path.join(tempDir, 'README.md');\n const readmeContent = generateReadme(project.name, project.description, formatType);\n fs.writeFileSync(readmePath, readmeContent);\n\n // 使用 Hugging Face REST API 上传数据集\n const visibility = isPrivate ? 'private' : 'public';\n\n try {\n // 准备仓库配置\n const repo = { type: 'dataset', name: datasetName };\n\n // 检查仓库是否存在\n let repoExists = true;\n try {\n await checkRepoAccess({ repo, accessToken: token });\n console.log(`Repository ${datasetName} exists, continuing to upload files`);\n } catch (error) {\n // If error code is 404, the repository does not exist\n if (error.statusCode === 404) {\n repoExists = false;\n console.log(`Repository ${datasetName} does not exist, preparing to create`);\n } else {\n // Other errors (e.g., permission errors)\n throw new Error(`Failed to check repository access: ${error.message}`);\n }\n }\n\n // If the repository does not exist, create a new one\n if (!repoExists) {\n try {\n await createRepo({\n repo,\n accessToken: token,\n private: isPrivate,\n license: 'mit',\n description: project.description || 'Dataset created with Easy Dataset'\n });\n console.log(`Successfully created dataset repository: ${datasetName}`);\n } catch (error) {\n throw new Error(`Failed to create dataset repository: ${error.message}`);\n }\n }\n\n // 2. 上传数据集文件\n await uploadFile(token, datasetName, datasetFilePath, `dataset.${fileFormat}`);\n\n // 3. 上传 README.md\n await uploadFile(token, datasetName, readmePath, 'README.md');\n } catch (error) {\n console.error('Upload to HuggingFace Failed:', String(error));\n return NextResponse.json({ error: `Upload Error: ${error.message}` }, { status: 500 });\n }\n\n // 清理临时目录\n fs.rmSync(tempDir, { recursive: true, force: true });\n\n // 返回成功信息\n const datasetUrl = `https://huggingface.co/datasets/${datasetName}`;\n return NextResponse.json({\n success: true,\n message: 'Upload successfully HuggingFace',\n url: datasetUrl\n });\n } catch (error) {\n console.error('Upload Faile:', String(error));\n return NextResponse.json({ error: error.message }, { status: 500 });\n }\n}\n\n// 格式化数据集\nfunction formatDataset(questions, formatType, systemPrompt, includeCOT, customFields) {\n if (formatType === 'alpaca') {\n return questions.map(q => {\n const item = {\n instruction: q.question,\n input: '',\n output: includeCOT && q.cot ? `${q.cot}\\n\\n${q.answer}` : q.answer\n };\n\n if (systemPrompt) {\n item.system = systemPrompt;\n }\n\n return item;\n });\n } else if (formatType === 'sharegpt') {\n return questions.map(q => {\n const messages = [];\n\n if (systemPrompt) {\n messages.push({\n role: 'system',\n content: systemPrompt\n });\n }\n\n messages.push({\n role: 'user',\n content: q.question\n });\n\n messages.push({\n role: 'assistant',\n content: includeCOT && q.cot ? `${q.cot}\\n\\n${q.answer}` : q.answer\n });\n\n return { messages };\n });\n } else if (formatType === 'custom' && customFields) {\n return questions.map(q => {\n const item = {\n [customFields.questionField]: q.question,\n [customFields.answerField]: q.answer\n };\n\n if (includeCOT && q.cot) {\n item[customFields.cotField] = q.cot;\n }\n\n if (customFields.includeLabels && q.labels) {\n item.labels = q.labels;\n }\n\n if (customFields.includeChunk && q.chunkId) {\n item.chunkId = q.chunkId;\n }\n\n return item;\n });\n }\n\n // 默认返回 alpaca 格式\n return questions.map(q => ({\n instruction: q.question,\n output: includeCOT && q.cot ? `${q.cot}\\n\\n${q.answer}` : q.answer\n }));\n}\n\n// 将数据转换为 CSV 格式\nfunction convertToCSV(data) {\n if (!data || data.length === 0) return '';\n\n const headers = Object.keys(data[0]);\n const headerRow = headers.join(',');\n\n const rows = data.map(item => {\n return headers\n .map(header => {\n const value = item[header];\n if (typeof value === 'string') {\n // 处理字符串中的逗号和引号\n return `\"${value.replace(/\"/g, '\"\"')}\"`;\n } else if (Array.isArray(value)) {\n return `\"${JSON.stringify(value).replace(/\"/g, '\"\"')}\"`;\n } else if (typeof value === 'object' && value !== null) {\n return `\"${JSON.stringify(value).replace(/\"/g, '\"\"')}\"`;\n }\n return value;\n })\n .join(',');\n });\n\n return [headerRow, ...rows].join('\\n');\n}\n\n// 使用 @huggingface/hub 包上传文件到 HuggingFace\nasync function uploadFile(token, datasetName, filePath, destFileName) {\n try {\n // 准备仓库配置\n const repo = { type: 'dataset', name: datasetName };\n\n // 创建文件 URL\n const fileUrl = new URL(`file://${filePath}`);\n\n // 使用 @huggingface/hub 包上传文件\n await uploadFiles({\n repo,\n accessToken: token,\n files: [\n {\n path: destFileName,\n content: fileUrl\n }\n ],\n commitTitle: `Upload ${destFileName}`,\n commitDescription: `Files uploaded using Easy Dataset`\n });\n\n return { success: true };\n } catch (error) {\n console.error(`File ${destFileName} Upload Error:`, String(error));\n throw error;\n }\n}\n\n// Generate README.md file\nfunction generateReadme(projectName, projectDescription, formatType) {\n return `# ${projectName}\n\n## Description\n${projectDescription || 'This dataset was created using the Easy Dataset tool.'}\n\n## Format\nThis dataset is in ${formatType} format.\n\n## Creation Method\nThis dataset was created using the [Easy Dataset](https://github.com/ConardLi/easy-dataset) tool.\n\n> Easy Dataset is a specialized application designed to streamline the creation of fine-tuning datasets for Large Language Models (LLMs). It offers an intuitive interface for uploading domain-specific files, intelligently splitting content, generating questions, and producing high-quality training data for model fine-tuning.\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/app/api/projects/[projectId]/files/[fileId]/ga-pairs/route.js", "import { NextResponse } from 'next/server';\nimport { getGaPairsByFileId, toggleGaPairActive, saveGaPairs, createGaPairs } from '@/lib/db/ga-pairs';\nimport { getUploadFileInfoById } from '@/lib/db/upload-files';\nimport { generateGaPairs } from '@/lib/services/ga/ga-generation';\nimport logger from '@/lib/util/logger';\nimport { db } from '@/lib/db/index';\n\n/**\n * 生成文件的 GA 对\n */\nexport async function POST(request, { params }) {\n try {\n const { projectId, fileId } = params;\n const { regenerate = false, appendMode = false, language = '中文' } = await request.json();\n\n // 验证参数\n if (!projectId || !fileId) {\n return NextResponse.json({ error: 'Project ID and File ID are required' }, { status: 400 });\n }\n\n logger.info(`Starting GA pairs generation for project: ${projectId}, file: ${fileId}, appendMode: ${appendMode}`);\n\n // 检查文件是否存在\n const file = await getUploadFileInfoById(fileId);\n if (!file || file.projectId !== projectId) {\n return NextResponse.json({ error: 'File not found or does not belong to the project' }, { status: 404 });\n }\n\n // 获取现有的GA对\n const existingGaPairs = await getGaPairsByFileId(fileId);\n\n // 如果是追加模式且已有GA对,或者不是重新生成且已存在GA对\n if (!regenerate && !appendMode && existingGaPairs.length > 0) {\n return NextResponse.json({\n success: true,\n message: 'GA pairs already exist for this file',\n data: existingGaPairs\n });\n }\n\n // 读取文件内容\n const fileContent = await getFileContent(projectId, file.fileName);\n if (!fileContent) {\n return NextResponse.json({ error: 'Failed to read file content' }, { status: 500 });\n }\n\n logger.info(`File content loaded successfully, length: ${fileContent.length}`);\n\n // 检查模型配置\n try {\n const { getActiveModel } = await import('@/lib/services/models');\n const activeModel = await getActiveModel(projectId);\n\n if (!activeModel) {\n logger.error('No active model configuration found');\n return NextResponse.json(\n { error: 'No active AI model configured. Please configure a model in settings first.' },\n { status: 400 }\n );\n }\n\n logger.info(`Using active model: ${activeModel.provider} - ${activeModel.model}`);\n } catch (modelError) {\n logger.error('Error checking model configuration:', modelError);\n return NextResponse.json(\n { error: 'Failed to load model configuration. Please check your AI model settings.' },\n { status: 500 }\n );\n }\n\n // 调用 LLM 生成 GA 对\n logger.info(`Generating GA pairs for file: ${file.fileName}`);\n let generatedGaPairs;\n\n try {\n generatedGaPairs = await generateGaPairs(fileContent, projectId, language);\n\n if (!generatedGaPairs || generatedGaPairs.length === 0) {\n logger.warn('No GA pairs generated from LLM');\n return NextResponse.json(\n {\n error:\n 'No GA pairs could be generated from the file content. The content might be too short or not suitable for GA pair generation.'\n },\n { status: 400 }\n );\n }\n\n logger.info(`Successfully generated ${generatedGaPairs.length} GA pairs from LLM`);\n } catch (generationError) {\n logger.error('GA pairs generation failed:', generationError);\n\n // 现有的错误处理逻辑...\n let errorMessage = 'Failed to generate GA pairs';\n if (generationError.message.includes('No active model')) {\n errorMessage = 'No active AI model available. Please configure and activate a model in settings.';\n } else if (generationError.message.includes('API key')) {\n errorMessage = 'Invalid API key or model configuration. Please check your AI model settings.';\n } else if (generationError.message.includes('rate limit')) {\n errorMessage = 'API rate limit exceeded. Please try again later.';\n } else {\n errorMessage = `AI model error: ${generationError.message}`;\n }\n\n return NextResponse.json({ error: errorMessage }, { status: 500 });\n }\n\n // 保存到数据库\n try {\n if (appendMode && existingGaPairs.length > 0) {\n // 追加模式:只保存新生成的GA对,不删除现有的\n logger.info(`Appending ${generatedGaPairs.length} new GA pairs to existing ${existingGaPairs.length} pairs`);\n\n // 为新GA对设置正确的pairNumber\n const startPairNumber = existingGaPairs.length + 1;\n const newGaPairData = generatedGaPairs.map((pair, index) => ({\n projectId,\n fileId,\n pairNumber: startPairNumber + index,\n genreTitle: pair.genre?.title || pair.genreTitle || '',\n genreDesc: pair.genre?.description || pair.genreDesc || '',\n audienceTitle: pair.audience?.title || pair.audienceTitle || '',\n audienceDesc: pair.audience?.description || pair.audienceDesc || '',\n isActive: true\n }));\n\n // 只创建新的GA对,不删除现有的\n await createGaPairs(newGaPairData);\n logger.info('New GA pairs appended to database successfully');\n } else {\n // 覆盖模式:删除现有的,保存新的\n await saveGaPairs(projectId, fileId, generatedGaPairs);\n logger.info('GA pairs saved to database successfully');\n }\n } catch (saveError) {\n logger.error('Failed to save GA pairs to database:', saveError);\n return NextResponse.json(\n { error: 'Generated GA pairs successfully but failed to save to database' },\n { status: 500 }\n );\n }\n\n // 获取保存后的所有GA对\n const allGaPairs = await getGaPairsByFileId(fileId);\n\n if (appendMode && existingGaPairs.length > 0) {\n // 追加模式:只返回新生成的GA对\n const newGaPairs = allGaPairs.slice(existingGaPairs.length);\n logger.info(`Successfully appended ${newGaPairs.length} GA pairs. Total pairs: ${allGaPairs.length}`);\n\n return NextResponse.json({\n success: true,\n message: `${newGaPairs.length} new GA pairs appended successfully`,\n data: newGaPairs,\n total: allGaPairs.length\n });\n } else {\n // 覆盖模式:返回所有GA对\n logger.info(`Successfully generated and saved ${allGaPairs.length} GA pairs for file: ${file.fileName}`);\n\n return NextResponse.json({\n success: true,\n message: 'GA pairs generated successfully',\n data: allGaPairs\n });\n }\n } catch (error) {\n logger.error('Unexpected error in GA pairs generation:', error);\n return NextResponse.json(\n { error: error.message || 'Unexpected error occurred during GA pairs generation' },\n { status: 500 }\n );\n }\n}\n\n/**\n * 获取文件的 GA 对\n */\nexport async function GET(request, { params }) {\n try {\n const { projectId, fileId } = params;\n\n if (!projectId || !fileId) {\n return NextResponse.json({ error: 'Project ID and File ID are required' }, { status: 400 });\n }\n\n const gaPairs = await getGaPairsByFileId(fileId);\n\n return NextResponse.json({\n success: true,\n data: gaPairs\n });\n } catch (error) {\n console.error('Error getting GA pairs:', String(error));\n return NextResponse.json({ error: 'Failed to get GA pairs' }, { status: 500 });\n }\n}\n\n/**\n * 更新/替换文件的所有 GA 对\n */\nexport async function PUT(request, { params }) {\n try {\n const { projectId, fileId } = params;\n const body = await request.json();\n\n if (!projectId || !fileId) {\n return NextResponse.json({ error: 'Project ID and File ID are required' }, { status: 400 });\n }\n\n const { updates } = body;\n\n if (!updates || !Array.isArray(updates)) {\n return NextResponse.json({ error: 'Updates array is required' }, { status: 400 });\n }\n\n logger.info(`Replacing all GA pairs for file ${fileId} with ${updates.length} pairs`);\n\n // 使用数据库事务确保原子性操作\n const results = await db.$transaction(async tx => {\n // 1. 先删除所有现有的GA对\n await tx.gaPairs.deleteMany({\n where: { fileId }\n });\n\n // 2. 然后创建新的GA对\n if (updates.length > 0) {\n const gaPairData = updates.map((pair, index) => ({\n projectId,\n fileId,\n pairNumber: index + 1,\n genreTitle: pair.genreTitle || pair.genre?.title || pair.genre || '',\n genreDesc: pair.genreDesc || pair.genre?.description || '',\n audienceTitle: pair.audienceTitle || pair.audience?.title || pair.audience || '',\n audienceDesc: pair.audienceDesc || pair.audience?.description || '',\n isActive: pair.isActive !== undefined ? pair.isActive : true\n }));\n\n // 验证数据\n for (const data of gaPairData) {\n if (!data.genreTitle || !data.audienceTitle) {\n throw new Error(`Invalid GA pair data: missing genre or audience title`);\n }\n }\n\n await tx.gaPairs.createMany({ data: gaPairData });\n }\n\n // 3. 返回新创建的GA对\n return await tx.gaPairs.findMany({\n where: { fileId },\n orderBy: { pairNumber: 'asc' }\n });\n });\n\n logger.info(`Successfully replaced GA pairs, new count: ${results.length}`);\n\n return NextResponse.json({\n success: true,\n data: results\n });\n } catch (error) {\n logger.error('Error updating GA pairs:', error);\n return NextResponse.json({ error: error.message || 'Failed to update GA pairs' }, { status: 500 });\n }\n}\n\n/**\n * 切换 GA 对激活状态\n */\nexport async function PATCH(request, { params }) {\n try {\n const { projectId, fileId } = params;\n const body = await request.json();\n\n if (!projectId || !fileId) {\n return NextResponse.json({ error: 'Project ID and File ID are required' }, { status: 400 });\n }\n\n const { gaPairId, isActive } = body;\n\n if (!gaPairId || typeof isActive !== 'boolean') {\n return NextResponse.json({ error: 'GA pair ID and active status are required' }, { status: 400 });\n }\n\n const updatedPair = await toggleGaPairActive(gaPairId, isActive);\n\n return NextResponse.json({\n success: true,\n data: updatedPair\n });\n } catch (error) {\n console.error('Error toggling GA pair active status:', String(error));\n return NextResponse.json({ error: 'Failed to toggle GA pair active status' }, { status: 500 });\n }\n}\n\n// Helper function to read file content\nasync function getFileContent(projectId, fileName) {\n try {\n const { getProjectRoot } = await import('@/lib/db/base');\n const path = await import('path');\n const fs = await import('fs');\n\n const projectRoot = await getProjectRoot();\n const filePath = path.join(projectRoot, projectId, 'files', fileName.replace('.pdf', '.md'));\n\n return await fs.promises.readFile(filePath, 'utf8');\n } catch (error) {\n logger.error('Failed to read file content:', error);\n return null;\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/app/projects/[projectId]/settings/components/PromptSettings.js", "import React, { useState, useEffect } from 'react';\nimport { Box, TextField, Button, Typography, Alert, Grid, Card, CardContent } from '@mui/material';\nimport SaveIcon from '@mui/icons-material/Save';\nimport { useTranslation } from 'react-i18next';\nimport fetchWithRetry from '@/lib/util/request';\nimport { useSnackbar } from '@/hooks/useSnackbar';\n\nexport default function PromptSettings({ projectId }) {\n const { t } = useTranslation();\n const { showSuccess, showError, SnackbarComponent } = useSnackbar();\n const [prompts, setPrompts] = useState({\n globalPrompt: '',\n questionPrompt: '',\n answerPrompt: '',\n labelPrompt: '',\n domainTreePrompt: ''\n });\n const [loading, setLoading] = useState(false);\n\n // 加载提示词配置\n useEffect(() => {\n const loadPrompts = async () => {\n try {\n const response = await fetchWithRetry(`/api/projects/${projectId}/config`);\n const config = await response.json();\n // 提取提示词相关的字段\n const promptFields = {\n globalPrompt: config.globalPrompt || '',\n questionPrompt: config.questionPrompt || '',\n answerPrompt: config.answerPrompt || '',\n labelPrompt: config.labelPrompt || '',\n domainTreePrompt: config.domainTreePrompt || ''\n };\n setPrompts(promptFields);\n } catch (error) {\n console.error('加载提示词配置失败:', error);\n showError(t('settings.loadPromptsFailed'));\n }\n };\n loadPrompts();\n }, [projectId]);\n\n // 保存提示词配置\n const handleSave = async () => {\n setLoading(true);\n try {\n const response = await fetchWithRetry(`/api/projects/${projectId}/config`, {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({ prompts: { ...prompts } })\n });\n const data = await response.json();\n if (response.ok) {\n showSuccess(t('settings.savePromptsSuccess'));\n } else {\n throw new Error(data.error || '保存失败');\n }\n } catch (error) {\n console.error('保存提示词配置失败:', error);\n showError(t('settings.savePromptsFailed'));\n } finally {\n setLoading(false);\n }\n };\n\n const handleChange = field => event => {\n setPrompts(prev => ({\n ...prev,\n [field]: event.target.value\n }));\n };\n\n return (\n \n \n {t('settings.promptsDescription')}\n \n \n \n {/* 全局提示词 */}\n \n \n \n \n {t('settings.globalPrompt')}\n \n \n \n \n \n\n {/* 生成问题提示词 */}\n \n \n \n \n {t('settings.questionPrompt')}\n \n \n \n \n \n\n {/* 生成答案提示词 */}\n \n \n \n \n {t('settings.answerPrompt')}\n \n \n \n \n \n\n {/* 问题打标提示词 */}\n \n \n \n \n {t('settings.labelPrompt')}\n \n \n \n \n \n\n {/* 构建领域树提示词 */}\n \n \n \n \n {t('settings.domainTreePrompt')}\n \n \n \n \n \n \n\n \n \n \n \n );\n}\n"], ["/easy-dataset/components/export/LocalExportTab.js", "// LocalExportTab.js 组件\nimport React from 'react';\nimport { useTranslation } from 'react-i18next';\nimport {\n Button,\n FormControl,\n FormControlLabel,\n RadioGroup,\n Radio,\n TextField,\n Checkbox,\n Typography,\n Box,\n Paper,\n useTheme,\n Grid,\n Table,\n TableRow,\n TableHead,\n TableBody,\n TableCell,\n TableContainer\n} from '@mui/material';\n\nconst LocalExportTab = ({\n fileFormat,\n formatType,\n systemPrompt,\n confirmedOnly,\n includeCOT,\n customFields,\n alpacaFieldType,\n customInstruction,\n handleFileFormatChange,\n handleFormatChange,\n handleSystemPromptChange,\n handleConfirmedOnlyChange,\n handleIncludeCOTChange,\n handleCustomFieldChange,\n handleIncludeLabelsChange,\n handleIncludeChunkChange,\n handleAlpacaFieldTypeChange,\n handleCustomInstructionChange,\n handleExport\n}) => {\n const theme = useTheme();\n const { t } = useTranslation();\n\n // 自定义格式的示例\n const getCustomFormatExample = () => {\n const { questionField, answerField, cotField, includeLabels, includeChunk } = customFields;\n const example = {\n [questionField]: '问题内容',\n [answerField]: '答案内容'\n };\n\n // 如果包含思维链字段,添加到示例中\n if (includeCOT) {\n example[cotField] = '思维链过程内容';\n }\n\n if (includeLabels) {\n example.labels = ['领域标签1'];\n }\n\n if (includeChunk) {\n example.chunk = '文本块';\n }\n\n return fileFormat === 'json' ? JSON.stringify([example], null, 2) : JSON.stringify(example);\n };\n\n // CSV 自定义格式化示例\n const getPreviewData = () => {\n if (formatType === 'alpaca') {\n // 根据选择的字段类型生成不同的示例\n if (alpacaFieldType === 'instruction') {\n return {\n headers: ['instruction', 'input', 'output', 'system'],\n rows: [\n {\n instruction: '人类指令(必填)',\n input: '',\n output: '模型回答(必填)',\n system: '系统提示词(选填)'\n },\n {\n instruction: '第二个指令',\n input: '',\n output: '第二个回答',\n system: '系统提示词'\n }\n ]\n };\n } else {\n // input\n return {\n headers: ['instruction', 'input', 'output', 'system'],\n rows: [\n {\n instruction: customInstruction || '固定的指令内容',\n input: '人类问题(必填)',\n output: '模型回答(必填)',\n system: '系统提示词(选填)'\n },\n {\n instruction: customInstruction || '固定的指令内容',\n input: '第二个问题',\n output: '第二个回答',\n system: '系统提示词'\n }\n ]\n };\n }\n } else if (formatType === 'sharegpt') {\n return {\n headers: ['messages'],\n rows: [\n {\n messages: JSON.stringify(\n [\n {\n messages: [\n {\n role: 'system',\n content: '系统提示词(选填)'\n },\n {\n role: 'user',\n content: '人类指令' // 映射到 question 字段\n },\n {\n role: 'assistant',\n content: '模型回答' // 映射到 cot+answer 字段\n }\n ]\n }\n ],\n null,\n 2\n )\n }\n ]\n };\n } else if (formatType === 'custom') {\n const headers = [customFields.questionField, customFields.answerField];\n if (includeCOT) headers.push(customFields.cotField);\n if (customFields.includeLabels) headers.push('labels');\n if (customFields.includeChunk) headers.push('chunkId');\n\n const row = {\n [customFields.questionField]: '问题内容',\n [customFields.answerField]: '答案内容'\n };\n if (includeCOT) row[customFields.cotField] = '思维链过程内容';\n if (customFields.includeLabels) row.labels = '领域标签';\n if (customFields.includeChunk) row.chunkId = '文本块';\n return {\n headers,\n rows: [row]\n };\n }\n };\n\n return (\n <>\n \n \n {t('export.fileFormat')}\n \n \n \n } label=\"JSON\" />\n } label=\"JSONL\" />\n } label=\"CSV\" />\n \n \n \n\n {/* 数据集风格 */}\n \n \n {t('export.format')}\n \n \n \n } label=\"Alpaca\" />\n } label=\"ShareGPT\" />\n } label={t('export.customFormat')} />\n \n \n \n\n {/* Alpaca 格式特有的设置 */}\n {formatType === 'alpaca' && (\n \n \n {t('export.alpacaSettings') || 'Alpaca 格式设置'}\n \n \n \n {t('export.questionFieldType') || '问题字段类型'}\n \n \n }\n label={t('export.useInstruction') || '使用 instruction 字段'}\n />\n } label={t('export.useInput') || '使用 input 字段'} />\n \n\n {alpacaFieldType === 'input' && (\n \n )}\n \n \n )}\n\n {/* 自定义格式选项 */}\n {formatType === 'custom' && (\n \n \n {t('export.customFormatSettings')}\n \n \n \n \n \n \n \n \n {/* 添加思维链字段名输入框 */}\n \n \n \n \n \n }\n label={t('export.includeLabels')}\n />\n {/* }\n label={t('export.includeChunk')}\n /> */}\n \n )}\n\n \n \n {t('export.example')}\n \n\n {fileFormat === 'csv' ? (\n \n {(() => {\n const { headers, rows } = getPreviewData();\n const tableKey = `${formatType}-${fileFormat}-${JSON.stringify(customFields)}`;\n return (\n \n \n \n {headers.map(header => (\n {header}\n ))}\n \n \n \n {rows.map((row, index) => (\n \n {headers.map(header => (\n \n {Array.isArray(row[header]) ? row[header].join(', ') : row[header] || ''}\n \n ))}\n \n ))}\n \n
\n );\n })()}\n
\n ) : (\n \n
\n              {formatType === 'custom'\n                ? getCustomFormatExample()\n                : formatType === 'alpaca'\n                  ? fileFormat === 'json'\n                    ? JSON.stringify(\n                        [\n                          {\n                            instruction: '人类指令(必填)', // 映射到 question 字段\n                            input: '人类输入(选填)',\n                            output: '模型回答(必填)', // 映射到 cot+answer 字段\n                            system: '系统提示词(选填)'\n                          }\n                        ],\n                        null,\n                        2\n                      )\n                    : '{\"instruction\": \"人类指令(必填)\", \"input\": \"人类输入(选填)\", \"output\": \"模型回答(必填)\", \"system\": \"系统提示词(选填)\"}\\n{\"instruction\": \"第二个指令\", \"input\": \"\", \"output\": \"第二个回答\", \"system\": \"系统提示词\"}'\n                  : fileFormat === 'json'\n                    ? JSON.stringify(\n                        [\n                          {\n                            messages: [\n                              {\n                                role: 'system',\n                                content: '系统提示词(选填)'\n                              },\n                              {\n                                role: 'user',\n                                content: '人类指令' // 映射到 question 字段\n                              },\n                              {\n                                role: 'assistant',\n                                content: '模型回答' // 映射到 cot+answer 字段\n                              }\n                            ]\n                          }\n                        ],\n                        null,\n                        2\n                      )\n                    : '{\"messages\": [{\"role\": \"system\", \"content\": \"系统提示词(选填)\"}, {\"role\": \"user\", \"content\": \"人类指令\"}, {\"role\": \"assistant\", \"content\": \"模型回答\"}]}\\n{\"messages\": [{\"role\": \"user\", \"content\": \"第二个问题\"}, {\"role\": \"assistant\", \"content\": \"第二个回答\"}]}'}\n            
\n \n )}\n
\n\n \n \n {t('export.systemPrompt')}\n \n \n \n\n \n }\n label={t('export.onlyConfirmed')}\n />\n\n }\n label={t('export.includeCOT')}\n />\n \n\n \n \n \n \n );\n};\n\nexport default LocalExportTab;\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/lib/file/split-markdown/core/splitter.js", "/**\n * Markdown文档分割模块\n */\n\n/**\n * 分割超长段落\n * @param {Object} section - 段落对象\n * @param {number} maxSplitLength - 最大分割字数\n * @returns {Array} - 分割后的段落数组\n */\nfunction splitLongSection(section, maxSplitLength) {\n const content = section.content;\n const paragraphs = content.split(/\\n\\n+/);\n const result = [];\n let currentChunk = '';\n\n for (const paragraph of paragraphs) {\n // 如果当前段落本身超过最大长度,可能需要进一步拆分\n if (paragraph.length > maxSplitLength) {\n // 如果当前块不为空,先加入结果\n if (currentChunk.length > 0) {\n result.push(currentChunk);\n currentChunk = '';\n }\n\n // 对超长段落进行分割(例如,按句子或固定长度)\n const sentenceSplit = paragraph.match(/[^.!?。!?]+[.!?。!?]+/g) || [paragraph];\n\n // 处理分割后的句子\n let sentenceChunk = '';\n for (const sentence of sentenceSplit) {\n if ((sentenceChunk + sentence).length <= maxSplitLength) {\n sentenceChunk += sentence;\n } else {\n if (sentenceChunk.length > 0) {\n result.push(sentenceChunk);\n }\n // 如果单个句子超过最大长度,可能需要进一步拆分\n if (sentence.length > maxSplitLength) {\n // 简单地按固定长度分割\n for (let i = 0; i < sentence.length; i += maxSplitLength) {\n result.push(sentence.substr(i, maxSplitLength));\n }\n } else {\n sentenceChunk = sentence;\n }\n }\n }\n\n if (sentenceChunk.length > 0) {\n currentChunk = sentenceChunk;\n }\n } else if ((currentChunk + '\\n\\n' + paragraph).length <= maxSplitLength) {\n // 如果添加当前段落不超过最大长度,则添加到当前块\n currentChunk = currentChunk.length > 0 ? currentChunk + '\\n\\n' + paragraph : paragraph;\n } else {\n // 如果添加当前段落超过最大长度,则将当前块加入结果,并重新开始一个新块\n result.push(currentChunk);\n currentChunk = paragraph;\n }\n }\n\n // 添加最后一个块(如果有)\n if (currentChunk.length > 0) {\n result.push(currentChunk);\n }\n\n return result;\n}\n\n/**\n * 处理段落,根据最小和最大分割字数进行分割\n * @param {Array} sections - 段落数组\n * @param {Array} outline - 目录大纲\n * @param {number} minSplitLength - 最小分割字数\n * @param {number} maxSplitLength - 最大分割字数\n * @returns {Array} - 处理后的段落数组\n */\nfunction processSections(sections, outline, minSplitLength, maxSplitLength) {\n // 预处理:将相邻的小段落合并\n const preprocessedSections = [];\n let currentSection = null;\n\n for (const section of sections) {\n const contentLength = section.content.trim().length;\n\n if (contentLength < minSplitLength && currentSection) {\n // 如果当前段落小于最小长度且有累积段落,尝试合并\n const mergedContent = `${currentSection.content}\\n\\n${section.heading ? `${'#'.repeat(section.level)} ${section.heading}\\n` : ''}${section.content}`;\n\n if (mergedContent.length <= maxSplitLength) {\n // 如果合并后不超过最大长度,则合并\n currentSection.content = mergedContent;\n if (section.heading) {\n currentSection.headings = currentSection.headings || [];\n currentSection.headings.push({\n heading: section.heading,\n level: section.level,\n position: section.position\n });\n }\n continue;\n }\n }\n\n // 如果无法合并,则开始新的段落\n if (currentSection) {\n preprocessedSections.push(currentSection);\n }\n currentSection = {\n ...section,\n headings: section.heading ? [{ heading: section.heading, level: section.level, position: section.position }] : []\n };\n }\n\n // 添加最后一个段落\n if (currentSection) {\n preprocessedSections.push(currentSection);\n }\n\n const result = [];\n let accumulatedSection = null; // 用于累积小于最小分割字数的段落\n\n for (let i = 0; i < preprocessedSections.length; i++) {\n const section = preprocessedSections[i];\n const contentLength = section.content.trim().length;\n\n // 检查是否需要累积段落\n if (contentLength < minSplitLength) {\n // 如果还没有累积过段落,创建新的累积段落\n if (!accumulatedSection) {\n accumulatedSection = {\n heading: section.heading,\n level: section.level,\n content: section.content,\n position: section.position,\n headings: [{ heading: section.heading, level: section.level, position: section.position }]\n };\n } else {\n // 已经有累积段落,将当前段落添加到累积段落中\n accumulatedSection.content += `\\n\\n${section.heading ? `${'#'.repeat(section.level)} ${section.heading}\\n` : ''}${section.content}`;\n if (section.heading) {\n accumulatedSection.headings.push({\n heading: section.heading,\n level: section.level,\n position: section.position\n });\n }\n }\n\n // 只有当累积内容达到最小长度时才处理\n const accumulatedLength = accumulatedSection.content.trim().length;\n if (accumulatedLength >= minSplitLength) {\n const summary = require('./summary').generateEnhancedSummary(accumulatedSection, outline);\n\n if (accumulatedLength > maxSplitLength) {\n // 如果累积段落超过最大长度,进一步分割\n const subSections = splitLongSection(accumulatedSection, maxSplitLength);\n\n for (let j = 0; j < subSections.length; j++) {\n result.push({\n summary: `${summary} - Part ${j + 1}/${subSections.length}`,\n content: subSections[j]\n });\n }\n } else {\n // 添加到结果中\n result.push({\n summary,\n content: accumulatedSection.content\n });\n }\n\n accumulatedSection = null; // 重置累积段落\n }\n\n continue;\n }\n\n // 如果有累积的段落,先处理它\n if (accumulatedSection) {\n const summary = require('./summary').generateEnhancedSummary(accumulatedSection, outline);\n const accumulatedLength = accumulatedSection.content.trim().length;\n\n if (accumulatedLength > maxSplitLength) {\n // 如果累积段落超过最大长度,进一步分割\n const { result: subSections, lastChunk } = splitLongSection(accumulatedSection, maxSplitLength, minSplitLength);\n\n for (let j = 0; j < subSections.length; j++) {\n result.push({\n summary: `${summary} - Part ${j + 1}/${subSections.length}`,\n content: subSections[j]\n });\n }\n\n // 如果有未处理的小段落,保存下来等待下一次合并\n if (lastChunk) {\n accumulatedSection = {\n ...accumulatedSection,\n content: lastChunk\n };\n continue;\n }\n } else {\n // 添加到结果中\n result.push({\n summary,\n content: accumulatedSection.content\n });\n }\n\n accumulatedSection = null; // 重置累积段落\n }\n\n // 处理当前段落\n // 如果段落长度超过最大分割字数,需要进一步分割\n if (contentLength > maxSplitLength) {\n const subSections = splitLongSection(section, maxSplitLength);\n\n // 为当前段落创建一个标准的headings数组\n if (!section.headings && section.heading) {\n section.headings = [{ heading: section.heading, level: section.level, position: section.position }];\n }\n\n for (let i = 0; i < subSections.length; i++) {\n const subSection = subSections[i];\n const summary = require('./summary').generateEnhancedSummary(section, outline, i + 1, subSections.length);\n\n result.push({\n summary,\n content: subSection\n });\n }\n } else {\n // 为当前段落创建一个标准的headings数组\n if (!section.headings && section.heading) {\n section.headings = [{ heading: section.heading, level: section.level, position: section.position }];\n }\n\n // 生成增强的摘要并添加到结果\n const summary = require('./summary').generateEnhancedSummary(section, outline);\n\n const content = `${section.heading ? `${'#'.repeat(section.level)} ${section.heading}\\n` : ''}${section.content}`;\n\n result.push({\n summary,\n content\n });\n }\n }\n\n // 处理最后剩余的小段落\n if (accumulatedSection) {\n if (result.length > 0) {\n // 尝试将剩余的小段落与最后一个结果合并\n const lastResult = result[result.length - 1];\n const mergedContent = `${lastResult.content}\\n\\n${accumulatedSection.content}`;\n\n if (mergedContent.length <= maxSplitLength) {\n // 如果合并后不超过最大长度,则合并\n const summary = require('./summary').generateEnhancedSummary(\n {\n ...accumulatedSection,\n content: mergedContent\n },\n outline\n );\n\n result[result.length - 1] = {\n summary,\n content: mergedContent\n };\n } else {\n // 如果合并后超过最大长度,将accumulatedSection作为单独的段落添加,这里的contentLength一定小于maxSplitLength\n const summary = require('./summary').generateEnhancedSummary(accumulatedSection, outline);\n const content = `${accumulatedSection.heading ? `${'#'.repeat(accumulatedSection.level)} ${accumulatedSection.heading}\\n` : ''}${accumulatedSection.content}`;\n result.push({\n summary,\n content\n });\n }\n } else {\n // 如果result为空,直接添加accumulatedSection\n const summary = require('./summary').generateEnhancedSummary(accumulatedSection, outline);\n const content = `${accumulatedSection.heading ? `${'#'.repeat(accumulatedSection.level)} ${accumulatedSection.heading}\\n` : ''}${accumulatedSection.content}`;\n result.push({\n summary,\n content\n });\n }\n }\n\n return result;\n}\n\nmodule.exports = {\n splitLongSection,\n processSections\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/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/lib/services/tasks/index.js", "/**\n * 任务服务层入口文件\n * 根据任务类型分配处理函数\n */\n\nimport { PrismaClient } from '@prisma/client';\nimport { TASK } from '@/constant';\nimport { processQuestionGenerationTask } from './question-generation';\nimport { processAnswerGenerationTask } from './answer-generation';\nimport { processFileProcessingTask } from './file-processing';\nimport './recovery';\n\nconst prisma = new PrismaClient();\n\n/**\n * 处理异步任务\n * @param {string} taskId - 任务ID\n * @returns {Promise}\n */\nexport async function processTask(taskId) {\n try {\n // 获取任务信息\n const task = await prisma.task.findUnique({\n where: { id: taskId }\n });\n\n if (!task) {\n console.error(`任务不存在: ${taskId}`);\n return;\n }\n\n // 如果任务已经完成或失败,不再处理\n if (task.status === TASK.STATUS.COMPLETED || task.status === TASK.STATUS.FAILED) {\n console.log(`任务已处理完成,无需再次执行: ${taskId}`);\n return;\n }\n\n // 根据任务类型调用相应的处理函数\n switch (task.taskType) {\n case 'question-generation':\n await processQuestionGenerationTask(task);\n break;\n case 'file-processing':\n await processFileProcessingTask(task);\n break;\n case 'answer-generation':\n await processAnswerGenerationTask(task);\n break;\n case 'data-distillation':\n // 暂未实现\n console.log('数据蒸馏任务暂未实现');\n await updateTask(taskId, { status: 2, note: '数据蒸馏任务暂未实现' });\n break;\n default:\n console.error(`未知任务类型: ${task.taskType}`);\n await updateTask(taskId, { status: TASK.STATUS.FAILED, note: `未知任务类型: ${task.taskType}` });\n }\n } catch (error) {\n console.error(`处理任务失败: ${taskId}`, String(error));\n await updateTask(taskId, { status: TASK.STATUS.FAILED, note: `处理失败: ${error.message}` });\n }\n}\n\n/**\n * 更新任务状态\n * @param {string} taskId - 任务ID\n * @param {object} data - 更新数据\n * @returns {Promise} - 更新后的任务\n */\nexport async function updateTask(taskId, data) {\n try {\n // 如果更新状态为完成或失败,且未提供结束时间,则自动添加\n if ((data.status === TASK.STATUS.COMPLETED || data.status === TASK.STATUS.FAILED) && !data.endTime) {\n data.endTime = new Date();\n }\n\n // 更新任务\n const updatedTask = await prisma.task.update({\n where: { id: taskId },\n data\n });\n\n return updatedTask;\n } catch (error) {\n console.error(`更新任务状态失败: ${taskId}`, error);\n throw error;\n }\n}\n\n/**\n * 启动任务处理器\n * 轮询数据库中的待处理任务并执行\n */\nexport async function startTaskProcessor() {\n try {\n console.log('启动任务处理器...');\n\n // 查找所有处理中的任务\n const pendingTasks = await prisma.task.findMany({\n where: { status: TASK.STATUS.PROCESSING }\n });\n\n if (pendingTasks.length > 0) {\n console.log(`发现 ${pendingTasks.length} 个待处理任务`);\n\n // 处理所有待处理任务\n for (const task of pendingTasks) {\n console.log(`开始处理任务: ${task.id}`);\n processTask(task.id).catch(err => {\n console.error(`任务处理失败: ${task.id}`, err);\n });\n }\n } else {\n console.log('没有待处理的任务');\n }\n } catch (error) {\n console.error('启动任务处理器失败', error);\n }\n}\n"], ["/easy-dataset/app/api/projects/[projectId]/chunks/batch-edit/route.js", "import { NextRequest, NextResponse } from 'next/server';\nimport { PrismaClient } from '@prisma/client';\n\nconst prisma = new PrismaClient();\n\n/**\n * 批量编辑文本块内容\n * POST /api/projects/[projectId]/chunks/batch-edit\n */\nexport async function POST(request, { params }) {\n try {\n const { projectId } = params;\n const body = await request.json();\n const { position, content, chunkIds } = body;\n\n // 验证参数\n if (!position || !content || !chunkIds || !Array.isArray(chunkIds) || chunkIds.length === 0) {\n return NextResponse.json({ error: 'Missing required parameters: position, content, chunkIds' }, { status: 400 });\n }\n\n if (!['start', 'end'].includes(position)) {\n return NextResponse.json({ error: 'Position must be \"start\" or \"end\"' }, { status: 400 });\n }\n\n // 验证项目权限(获取要编辑的文本块)\n const chunksToUpdate = await prisma.chunks.findMany({\n where: {\n id: { in: chunkIds },\n projectId: projectId\n },\n select: {\n id: true,\n content: true,\n name: true\n }\n });\n\n if (chunksToUpdate.length === 0) {\n return NextResponse.json({ error: 'Not found' }, { status: 404 });\n }\n\n if (chunksToUpdate.length !== chunkIds.length) {\n return NextResponse.json({ error: 'Some chunks not found' }, { status: 400 });\n }\n\n // 准备更新数据\n const updates = chunksToUpdate.map(chunk => {\n let newContent;\n\n if (position === 'start') {\n // 在开头添加内容\n newContent = content + '\\n\\n' + chunk.content;\n } else {\n // 在结尾添加内容\n newContent = chunk.content + '\\n\\n' + content;\n }\n\n return {\n where: { id: chunk.id },\n data: {\n content: newContent,\n size: newContent.length,\n updateAt: new Date()\n }\n };\n });\n\n async function processBatches(items, batchSize, processFn) {\n const results = [];\n for (let i = 0; i < items.length; i += batchSize) {\n const batch = items.slice(i, i + batchSize);\n const batchResults = await Promise.all(batch.map(processFn));\n results.push(...batchResults);\n }\n return results;\n }\n\n const BATCH_SIZE = 50; // 每批处理 50 个\n await processBatches(updates, BATCH_SIZE, update => prisma.chunks.update(update));\n\n // 记录操作日志(可选)\n console.log(`Successfully updated ${chunksToUpdate.length} chunks`);\n\n return NextResponse.json({\n success: true,\n updatedCount: chunksToUpdate.length,\n message: `Successfully updated ${chunksToUpdate.length} chunks`\n });\n } catch (error) {\n console.error('批量编辑文本块失败:', error);\n\n return NextResponse.json(\n {\n error: 'Batch edit chunks failed',\n details: error.message\n },\n { status: 500 }\n );\n } finally {\n await prisma.$disconnect();\n }\n}\n"], ["/easy-dataset/lib/util/request.js", "/**\n * 封装的通用重试函数,用于在操作失败后自动重试\n * @param {Function} asyncOperation - 需要执行的异步操作函数\n * @param {Object} options - 配置选项\n * @param {number} options.retries - 重试次数,默认为1\n * @param {number} options.delay - 重试前的延迟时间(毫秒),默认为0\n * @param {Function} options.onRetry - 重试前的回调函数,接收错误和当前重试次数作为参数\n * @returns {Promise} - 返回异步操作的结果\n */\nexport const withRetry = async (asyncOperation, options = {}) => {\n const { retries = 1, delay = 0, onRetry = null } = options;\n let lastError;\n\n // 尝试执行操作,包括初次尝试和后续重试\n for (let attempt = 0; attempt <= retries; attempt++) {\n try {\n return await asyncOperation();\n } catch (error) {\n lastError = error;\n\n // 如果这是最后一次尝试,则不再重试\n if (attempt === retries) {\n break;\n }\n\n // 如果提供了重试回调,则执行\n if (onRetry && typeof onRetry === 'function') {\n onRetry(error, attempt + 1);\n }\n\n // 如果设置了延迟,则等待指定时间\n if (delay > 0) {\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n }\n }\n\n // 如果所有尝试都失败,则抛出最后一个错误\n throw lastError;\n};\n\n/**\n * 封装的fetch函数,支持自动重试\n * @param {string} url - 请求URL\n * @param {Object} options - fetch选项\n * @param {Object} retryOptions - 重试选项\n * @returns {Promise} - 返回fetch响应\n */\nexport const fetchWithRetry = async (url, options = {}, retryOptions = {}) => {\n return withRetry(() => fetch(url, options), retryOptions);\n};\n\n/**\n * 封装的 fetch 函数\n * @param {string} url - 请求URL\n * @param {Object} options - fetch选项\n * @returns {Promise} - 返回fetch响应\n */\nexport const request = async (url, options = {}) => {\n try {\n const result = await fetch(url, options);\n const data = await result.json();\n if (!result.ok) {\n throw new Error(`Fetch Error: ${url} ${String(data.error || 'Unknown error')}`);\n }\n return data;\n } catch (error) {\n throw new Error(`Fetch Error: ${url} ${String(error)} ${options.errMsg || ''}`);\n }\n};\n\nexport default fetchWithRetry;\n"], ["/easy-dataset/lib/db/datasets.js", "'use server';\nimport { db } from '@/lib/db/index';\n\n/**\n * 获取数据集列表(根据项目ID)\n * @param projectId 项目id\n * @param page\n * @param pageSize\n * @param confirmed\n * @param input\n * @param field 搜索字段,可选值:question, answer, cot, questionLabel\n * @param hasCot 思维链筛选,可选值:all, yes, no\n */\nexport async function getDatasetsByPagination(\n projectId,\n page = 1,\n pageSize = 10,\n confirmed,\n input,\n field = 'question',\n hasCot = 'all'\n) {\n try {\n // 根据搜索字段构建查询条件\n const searchCondition = {};\n if (input) {\n if (field === 'question') {\n searchCondition.question = { contains: input };\n } else if (field === 'answer') {\n searchCondition.answer = { contains: input };\n } else if (field === 'cot') {\n searchCondition.cot = { contains: input };\n } else if (field === 'questionLabel') {\n searchCondition.questionLabel = { contains: input };\n }\n }\n\n // 思维链筛选条件\n const cotCondition = {};\n if (hasCot === 'yes') {\n cotCondition.cot = { not: '' };\n } else if (hasCot === 'no') {\n cotCondition.cot = '';\n }\n\n const whereClause = {\n projectId,\n ...(confirmed !== undefined && { confirmed: confirmed }),\n ...searchCondition,\n ...cotCondition\n };\n\n console.log(111, whereClause);\n\n const [data, total, confirmedCount] = await Promise.all([\n db.datasets.findMany({\n where: whereClause,\n orderBy: {\n createAt: 'desc'\n },\n skip: (page - 1) * pageSize,\n take: pageSize\n }),\n db.datasets.count({\n where: whereClause\n }),\n db.datasets.count({\n where: { ...whereClause, confirmed: true }\n })\n ]);\n\n return { data, total, confirmedCount };\n } catch (error) {\n console.error('Failed to get datasets by pagination in database');\n throw error;\n }\n}\n\nexport async function getDatasets(projectId, confirmed) {\n try {\n const whereClause = {\n projectId,\n ...(confirmed !== undefined && { confirmed: confirmed })\n };\n return await db.datasets.findMany({\n where: whereClause,\n select: {\n question: true,\n answer: true,\n cot: true,\n questionLabel: true\n },\n orderBy: {\n createAt: 'desc'\n }\n });\n } catch (error) {\n console.error('Failed to get datasets in database');\n throw error;\n }\n}\n\nexport async function getDatasetsIds(projectId, confirmed, input, field = 'question', hasCot = 'all') {\n try {\n // 根据搜索字段构建查询条件\n const searchCondition = {};\n if (input) {\n if (field === 'question') {\n searchCondition.question = { contains: input };\n } else if (field === 'answer') {\n searchCondition.answer = { contains: input };\n } else if (field === 'cot') {\n searchCondition.cot = { contains: input };\n } else if (field === 'questionLabel') {\n searchCondition.questionLabel = { contains: input };\n }\n }\n\n // 思维链筛选条件\n const cotCondition = {};\n if (hasCot === 'yes') {\n cotCondition.cot = { not: null };\n cotCondition.cot = { not: '' };\n } else if (hasCot === 'no') {\n cotCondition.OR = [{ cot: null }, { cot: '' }];\n }\n\n const whereClause = {\n projectId,\n ...(confirmed !== undefined && { confirmed: confirmed }),\n ...searchCondition,\n ...cotCondition\n };\n return await db.datasets.findMany({\n where: whereClause,\n select: {\n id: true\n },\n orderBy: {\n createAt: 'desc'\n }\n });\n } catch (error) {\n console.error('Failed to get datasets ids in database');\n throw error;\n }\n}\n\n/**\n * 获取数据集数量(根据项目ID)\n * @param projectId 项目id\n */\nexport async function getDatasetsCount(projectId) {\n try {\n return await db.datasets.count({\n where: {\n projectId\n }\n });\n } catch (error) {\n console.error('Failed to get datasets count by projectId in database');\n throw error;\n }\n}\n\n/**\n * 获取数据集数量(根据问题Id)\n * @param questionId 问题Id\n */\nexport async function getDatasetsCountByQuestionId(questionId) {\n try {\n return await db.datasets.count({\n where: {\n questionId\n }\n });\n } catch (error) {\n console.error('Failed to get datasets count by projectId in database');\n throw error;\n }\n}\n\n/**\n * 获取数据集详情\n * @param id 数据集id\n */\nexport async function getDatasetsById(id) {\n try {\n return await db.datasets.findUnique({\n where: { id }\n });\n } catch (error) {\n console.error('Failed to get datasets by id in database');\n throw error;\n }\n}\n\n/**\n * 保存数据集列表\n * @param dataset\n */\nexport async function createDataset(dataset) {\n try {\n return await db.datasets.create({\n data: dataset\n });\n } catch (error) {\n console.error('Failed to save datasets in database');\n throw error;\n }\n}\n\nexport async function updateDataset(dataset) {\n try {\n return await db.datasets.update({\n data: dataset,\n where: {\n id: dataset.id\n }\n });\n } catch (error) {\n console.error('Failed to update datasets in database');\n throw error;\n }\n}\n\nexport async function deleteDataset(datasetId) {\n try {\n return await db.datasets.delete({\n where: {\n id: datasetId\n }\n });\n } catch (error) {\n console.error('Failed to delete datasets in database');\n throw error;\n }\n}\n\nexport async function getDatasetsCounts(projectId) {\n try {\n const [total, confirmedCount] = await Promise.all([\n db.datasets.count({\n where: { projectId }\n }),\n db.datasets.count({\n where: { projectId, confirmed: true }\n })\n ]);\n\n return { total, confirmedCount };\n } catch (error) {\n console.error('Failed to delete datasets in database');\n throw error;\n }\n}\n\nexport async function getNavigationItems(projectId, datasetId, operateType) {\n const currentItem = await db.datasets.findUnique({\n where: { id: datasetId }\n });\n if (!currentItem) {\n throw new Error('当前记录不存在');\n }\n if (operateType === 'prev') {\n return await db.datasets.findFirst({\n where: { createAt: { gt: currentItem.createAt }, projectId },\n orderBy: { createAt: 'asc' }\n });\n } else {\n return await db.datasets.findFirst({\n where: { createAt: { lt: currentItem.createAt }, projectId },\n orderBy: { createAt: 'desc' }\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/hooks/useGenerateDataset.js", "import { useCallback } from 'react';\nimport { toast } from 'sonner';\nimport i18n from '@/lib/i18n';\nimport axios from 'axios';\nimport { useAtomValue } from 'jotai/index';\nimport { selectedModelInfoAtom } from '@/lib/store';\nimport { useTranslation } from 'react-i18next';\n\nexport function useGenerateDataset() {\n const model = useAtomValue(selectedModelInfoAtom);\n const { t } = useTranslation();\n\n const generateSingleDataset = useCallback(\n async ({ projectId, questionId, questionInfo }) => {\n // 获取模型参数\n if (!model) {\n toast.error(t('models.configNotFound'));\n return null;\n }\n // 调用API生成数据集\n const currentLanguage = i18n.language === 'zh-CN' ? '中文' : 'en';\n toast.promise(\n axios.post(`/api/projects/${projectId}/datasets`, {\n questionId,\n model,\n language: currentLanguage\n }),\n {\n loading: t('datasets.generating'),\n description: `问题:【${questionInfo}】`,\n position: 'top-right',\n success: data => {\n return '生成数据集成功';\n },\n error: error => {\n return t('datasets.generateFailed', { error: error.response?.data?.error });\n }\n }\n );\n },\n [model, t]\n );\n\n const generateMultipleDataset = useCallback(\n async (projectId, questions) => {\n let completed = 0;\n const total = questions.length;\n // 显示带进度的Loading\n const loadingToastId = toast.loading(`正在处理请求 (${completed}/${total})...`, { position: 'top-right' });\n\n // 处理每个请求\n const processRequest = async question => {\n try {\n const response = await axios.post(`/api/projects/${projectId}/datasets`, {\n questionId: question.id,\n model,\n language: i18n.language === 'zh-CN' ? '中文' : 'en'\n });\n const data = response.data;\n completed++;\n toast.success(`${question.question} 完成`, { position: 'top-right' });\n toast.loading(`正在处理请求 (${completed}/${total})...`, { id: loadingToastId });\n return data;\n } catch (error) {\n completed++;\n toast.error(`${question.question} 失败`, {\n description: error.message,\n position: 'top-right'\n });\n toast.loading(`正在处理请求 (${completed}/${total})...`, { id: loadingToastId });\n throw error;\n }\n };\n\n try {\n const results = await Promise.allSettled(questions.map(req => processRequest(req)));\n // 全部完成后更新Loading为完成状态\n toast.success(`全部请求处理完成 (成功: ${results.filter(r => r.status === 'fulfilled').length}/${total})`, {\n id: loadingToastId,\n position: 'top-right'\n });\n return results;\n } catch {\n // Promise.allSettled不会进入catch,这里只是保险\n }\n },\n [model, t]\n );\n\n return { generateSingleDataset, generateMultipleDataset };\n}\n"], ["/easy-dataset/lib/services/tasks/question-generation.js", "/**\n * 问题生成任务处理服务\n */\n\nimport { PrismaClient } from '@prisma/client';\nimport { processInParallel } from '@/lib/util/async';\nimport { updateTask } from './index';\nimport { getTaskConfig } from '@/lib/db/projects';\nimport questionService from '@/lib/services/questions';\n\nconst prisma = new PrismaClient();\n\n/**\n * 处理问题生成任务\n * @param {object} task - 任务对象\n * @returns {Promise}\n */\nexport async function processQuestionGenerationTask(task) {\n try {\n console.log(`开始处理问题生成任务: ${task.id}`);\n\n // 解析模型信息\n let modelInfo;\n try {\n modelInfo = JSON.parse(task.modelInfo);\n } catch (error) {\n throw new Error(`模型信息解析失败: ${error.message}`);\n }\n\n // 获取项目配置\n const taskConfig = await getTaskConfig(task.projectId);\n const concurrencyLimit = taskConfig?.concurrencyLimit || 2;\n\n // 1. 查询所有未生成问题的文本块(过滤掉名出为 Distilled Content 的文本块)\n const chunks = await prisma.chunks.findMany({\n where: {\n projectId: task.projectId,\n // 过滤掉名称为 Distilled Content 的文本块\n NOT: {\n name: {\n contains: 'Distilled Content'\n }\n }\n },\n include: {\n Questions: true\n }\n });\n\n // 过滤出没有问题的文本块\n const chunksWithoutQuestions = chunks.filter(chunk => chunk.Questions.length === 0);\n\n if (chunksWithoutQuestions.length === 0) {\n console.log(`项目 ${task.projectId} 没有需要生成问题的文本块`);\n await updateTask(task.id, {\n status: 1,\n completedCount: 0,\n totalCount: 0,\n note: '没有需要生成问题的文本块'\n });\n return;\n }\n\n // 更新任务总数\n const totalCount = chunksWithoutQuestions.length;\n await updateTask(task.id, {\n totalCount,\n detail: `待处理文本块数量: ${totalCount}`\n });\n\n // 2. 批量处理每个文本块\n let successCount = 0;\n let errorCount = 0;\n let totalQuestions = 0;\n let latestTaskStatus = 0;\n\n // 单个文本块处理函数\n const processChunk = async chunk => {\n try {\n // 如果任务已经被标记为失败或已中断,不再继续处理\n const latestTask = await prisma.task.findUnique({ where: { id: task.id } });\n if (latestTask.status === 2 || latestTask.status === 3) {\n latestTaskStatus = latestTask.status;\n return;\n }\n\n const data = await questionService.generateQuestionsForChunkWithGA(task.projectId, chunk.id, {\n model: modelInfo,\n language: task.language === 'zh-CN' ? '中文' : 'en',\n enableGaExpansion: true // 启用GA扩展\n });\n console.log(`文本块 ${chunk.id} 已生成 ${data.total || 0} 个问题`);\n\n // 增加成功计数\n successCount++;\n totalQuestions += data.total || 0;\n\n // 更新任务进度\n await updateTask(task.id, {\n completedCount: successCount + errorCount,\n detail: `已处理: ${successCount + errorCount}/${totalCount}, 成功: ${successCount}, 失败: ${errorCount}, 共生成问题: ${totalQuestions}`\n });\n\n return { success: true, chunkId: chunk.id, total: data.total || 0 };\n } catch (error) {\n console.error(`处理文本块 ${chunk.id} 出错:`, error);\n errorCount++;\n\n // 更新任务进度\n await updateTask(task.id, {\n completedCount: successCount + errorCount,\n detail: `已处理: ${successCount + errorCount}/${totalCount}, 成功: ${successCount}, 失败: ${errorCount}, 共生成问题: ${totalQuestions}`\n });\n\n return { success: false, chunkId: chunk.id, error: error.message };\n }\n };\n\n // 并行处理所有文本块,使用任务设置中的并发限制\n await processInParallel(chunksWithoutQuestions, processChunk, concurrencyLimit, async (completed, total) => {\n console.log(`问题生成进度: ${completed}/${total}`);\n });\n\n if (!latestTaskStatus) {\n // 任务完成,更新状态\n const finalStatus = errorCount > 0 && successCount === 0 ? 2 : 1; // 如果全部失败,标记为失败;否则标记为完成\n await updateTask(task.id, {\n status: finalStatus,\n detail: '',\n note: '',\n endTime: new Date()\n });\n }\n\n console.log(`问题生成任务 ${task.id} 处理完成`);\n } catch (error) {\n console.error(`问题生成任务处理失败: ${task.id}`, error);\n await updateTask(task.id, {\n status: 2,\n detail: `处理失败: ${error.message}`,\n note: `处理失败: ${error.message}`\n });\n }\n}\n"], ["/easy-dataset/app/projects/[projectId]/distill/page.js", "'use client';\n\nimport React, { useState, useEffect, useRef } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { useParams } from 'next/navigation';\nimport { useAtomValue } from 'jotai';\nimport { selectedModelInfoAtom } from '@/lib/store';\nimport { Box, Typography, Paper, Container, Button, CircularProgress, Alert, IconButton, Tooltip } from '@mui/material';\nimport AddIcon from '@mui/icons-material/Add';\nimport AutoFixHighIcon from '@mui/icons-material/AutoFixHigh';\nimport DistillTreeView from '@/components/distill/DistillTreeView';\nimport TagGenerationDialog from '@/components/distill/TagGenerationDialog';\nimport QuestionGenerationDialog from '@/components/distill/QuestionGenerationDialog';\nimport AutoDistillDialog from '@/components/distill/AutoDistillDialog';\nimport AutoDistillProgress from '@/components/distill/AutoDistillProgress';\nimport HelpOutlineIcon from '@mui/icons-material/HelpOutline';\nimport { autoDistillService } from './autoDistillService';\nimport axios from 'axios';\n\nexport default function DistillPage() {\n const { t, i18n } = useTranslation();\n const { projectId } = useParams();\n const selectedModel = useAtomValue(selectedModelInfoAtom);\n\n const [project, setProject] = useState(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState('');\n const [tags, setTags] = useState([]);\n\n // 标签生成对话框相关状态\n const [tagDialogOpen, setTagDialogOpen] = useState(false);\n const [questionDialogOpen, setQuestionDialogOpen] = useState(false);\n const [selectedTag, setSelectedTag] = useState(null);\n const [selectedTagPath, setSelectedTagPath] = useState('');\n\n // 自动蒸馏相关状态\n const [autoDistillDialogOpen, setAutoDistillDialogOpen] = useState(false);\n const [autoDistillProgressOpen, setAutoDistillProgressOpen] = useState(false);\n const [autoDistillRunning, setAutoDistillRunning] = useState(false);\n const [distillStats, setDistillStats] = useState({\n tagsCount: 0,\n questionsCount: 0,\n datasetsCount: 0\n });\n const [distillProgress, setDistillProgress] = useState({\n stage: 'initializing',\n tagsTotal: 0,\n tagsBuilt: 0,\n questionsTotal: 0,\n questionsBuilt: 0,\n datasetsTotal: 0,\n datasetsBuilt: 0,\n logs: []\n });\n\n const treeViewRef = useRef(null);\n\n // 获取项目信息和标签列表\n useEffect(() => {\n if (projectId) {\n fetchProject();\n fetchTags();\n fetchDistillStats();\n }\n }, [projectId]);\n\n // 获取项目信息\n const fetchProject = async () => {\n try {\n setLoading(true);\n const response = await axios.get(`/api/projects/${projectId}`);\n setProject(response.data);\n } catch (error) {\n console.error('获取项目信息失败:', error);\n setError(t('common.fetchError'));\n } finally {\n setLoading(false);\n }\n };\n\n // 获取标签列表\n const fetchTags = async () => {\n try {\n setLoading(true);\n const response = await axios.get(`/api/projects/${projectId}/distill/tags/all`);\n setTags(response.data);\n } catch (error) {\n console.error('获取标签列表失败:', error);\n setError(t('common.fetchError'));\n } finally {\n setLoading(false);\n }\n };\n\n // 获取蒸馏统计信息\n const fetchDistillStats = async () => {\n try {\n // 获取标签数量\n const tagsResponse = await axios.get(`/api/projects/${projectId}/distill/tags/all`);\n const tagsCount = tagsResponse.data.length;\n\n // 获取问题数量\n const questionsResponse = await axios.get(`/api/projects/${projectId}/questions/tree?isDistill=true`);\n const questionsCount = questionsResponse.data.length;\n\n // TODO: 获取数据集数量,简化起见暂用问题数量代替\n const datasetsCount = questionsResponse.data.filter(q => q.answered).length;\n\n setDistillStats({\n tagsCount,\n questionsCount,\n datasetsCount\n });\n } catch (error) {\n console.error('获取蒸馏统计信息失败:', error);\n }\n };\n\n // 打开生成标签对话框\n const handleOpenTagDialog = (tag = null, tagPath = '') => {\n if (!selectedModel || Object.keys(selectedModel).length === 0) {\n setError(t('distill.selectModelFirst'));\n return;\n }\n setSelectedTag(tag);\n setSelectedTagPath(tagPath);\n setTagDialogOpen(true);\n };\n\n // 打开生成问题对话框\n const handleOpenQuestionDialog = (tag, tagPath) => {\n if (!selectedModel || Object.keys(selectedModel).length === 0) {\n setError(t('distill.selectModelFirst'));\n return;\n }\n setSelectedTag(tag);\n setSelectedTagPath(tagPath);\n setQuestionDialogOpen(true);\n };\n\n // 处理标签生成完成\n const handleTagGenerated = () => {\n fetchTags(); // 重新获取标签列表\n setTagDialogOpen(false);\n };\n\n // 处理问题生成完成\n const handleQuestionGenerated = () => {\n // 关闭对话框\n setQuestionDialogOpen(false);\n\n // 刷新标签数据\n fetchTags();\n fetchDistillStats();\n\n // 如果 treeViewRef 存在且有 fetchQuestionsStats 方法,则调用它刷新问题统计信息\n if (treeViewRef.current && typeof treeViewRef.current.fetchQuestionsStats === 'function') {\n treeViewRef.current.fetchQuestionsStats();\n }\n };\n\n // 打开自动蒸馏对话框\n const handleOpenAutoDistillDialog = () => {\n if (!selectedModel || Object.keys(selectedModel).length === 0) {\n setError(t('distill.selectModelFirst'));\n return;\n }\n setAutoDistillDialogOpen(true);\n };\n\n // 开始自动蒸馏任务\n const handleStartAutoDistill = async config => {\n setAutoDistillDialogOpen(false);\n setAutoDistillProgressOpen(true);\n setAutoDistillRunning(true);\n\n // 初始化进度信息\n setDistillProgress({\n stage: 'initializing',\n tagsTotal: config.estimatedTags,\n tagsBuilt: distillStats.tagsCount || 0,\n questionsTotal: config.estimatedQuestions,\n questionsBuilt: distillStats.questionsCount || 0,\n datasetsTotal: config.estimatedQuestions, // 初步设置数据集总数为问题数,后面会更新\n datasetsBuilt: distillStats.datasetsCount || 0, // 根据当前已生成的数据集数量初始化\n logs: [t('distill.autoDistillStarted', { time: new Date().toLocaleTimeString() })]\n });\n\n try {\n // 检查模型是否存在\n if (!selectedModel || Object.keys(selectedModel).length === 0) {\n addLog(t('distill.selectModelFirst'));\n setAutoDistillRunning(false);\n return;\n }\n\n // 使用 autoDistillService 执行蒸馏任务\n await autoDistillService.executeDistillTask({\n projectId,\n topic: config.topic,\n levels: config.levels,\n tagsPerLevel: config.tagsPerLevel,\n questionsPerTag: config.questionsPerTag,\n model: selectedModel,\n language: i18n.language,\n concurrencyLimit: project?.taskConfig?.concurrencyLimit || 5, // 从项目配置中获取并发限制\n onProgress: updateProgress,\n onLog: addLog\n });\n\n // 更新任务状态\n setAutoDistillRunning(false);\n } catch (error) {\n console.error('自动蒸馏任务执行失败:', error);\n addLog(`任务执行出错: ${error.message || '未知错误'}`);\n setAutoDistillRunning(false);\n }\n };\n\n // 更新进度\n const updateProgress = progressUpdate => {\n setDistillProgress(prev => {\n const newProgress = { ...prev };\n\n // 更新阶段\n if (progressUpdate.stage) {\n newProgress.stage = progressUpdate.stage;\n }\n\n // 更新标签总数\n if (progressUpdate.tagsTotal) {\n newProgress.tagsTotal = progressUpdate.tagsTotal;\n }\n\n // 更新已构建标签数\n if (progressUpdate.tagsBuilt) {\n if (progressUpdate.updateType === 'increment') {\n newProgress.tagsBuilt += progressUpdate.tagsBuilt;\n } else {\n newProgress.tagsBuilt = progressUpdate.tagsBuilt;\n }\n }\n\n // 更新问题总数\n if (progressUpdate.questionsTotal) {\n newProgress.questionsTotal = progressUpdate.questionsTotal;\n }\n\n // 更新已生成问题数\n if (progressUpdate.questionsBuilt) {\n if (progressUpdate.updateType === 'increment') {\n newProgress.questionsBuilt += progressUpdate.questionsBuilt;\n } else {\n newProgress.questionsBuilt = progressUpdate.questionsBuilt;\n }\n }\n\n // 更新数据集总数\n if (progressUpdate.datasetsTotal) {\n newProgress.datasetsTotal = progressUpdate.datasetsTotal;\n }\n\n // 更新已生成数据集数\n if (progressUpdate.datasetsBuilt) {\n if (progressUpdate.updateType === 'increment') {\n newProgress.datasetsBuilt += progressUpdate.datasetsBuilt;\n } else {\n newProgress.datasetsBuilt = progressUpdate.datasetsBuilt;\n }\n }\n\n return newProgress;\n });\n };\n\n // 添加日志,最多保留200条\n const addLog = message => {\n setDistillProgress(prev => {\n const newLogs = [...prev.logs, message];\n // 如果日志超过200条,只保留最新的200条\n const limitedLogs = newLogs.length > 200 ? newLogs.slice(-200) : newLogs;\n return {\n ...prev,\n logs: limitedLogs\n };\n });\n };\n\n // 关闭进度对话框\n const handleCloseProgressDialog = () => {\n if (!autoDistillRunning) {\n setAutoDistillProgressOpen(false);\n // 刷新数据\n fetchTags();\n fetchDistillStats();\n if (treeViewRef.current && typeof treeViewRef.current.fetchQuestionsStats === 'function') {\n treeViewRef.current.fetchQuestionsStats();\n }\n } else {\n // 如果任务还在运行,可以展示一个确认对话框\n // 这里简化处理,直接关闭\n setAutoDistillProgressOpen(false);\n }\n };\n\n if (!projectId) {\n return (\n \n {t('common.projectIdRequired')}\n \n );\n }\n\n return (\n \n \n \n \n \n {t('distill.title')}\n \n \n {\n const helpUrl =\n i18n.language === 'en'\n ? 'https://docs.easy-dataset.com/ed/en/advanced/images-and-media'\n : 'https://docs.easy-dataset.com/jin-jie-shi-yong/images-and-media';\n window.open(helpUrl, '_blank');\n }}\n sx={{ color: 'text.secondary' }}\n >\n \n \n \n \n \n }\n sx={{ px: 3, py: 1 }}\n >\n {t('distill.autoDistillButton')}\n \n handleOpenTagDialog(null)}\n disabled={!selectedModel}\n startIcon={}\n sx={{ px: 3, py: 1 }}\n >\n {t('distill.generateRootTags')}\n \n \n \n\n {error && (\n setError('')}>\n {error}\n \n )}\n\n {loading ? (\n \n \n \n ) : (\n \n \n \n )}\n \n\n {/* 生成标签对话框 */}\n {tagDialogOpen && (\n setTagDialogOpen(false)}\n onGenerated={handleTagGenerated}\n projectId={projectId}\n parentTag={selectedTag}\n tagPath={selectedTagPath}\n model={selectedModel}\n />\n )}\n\n {/* 生成问题对话框 */}\n {questionDialogOpen && (\n setQuestionDialogOpen(false)}\n onGenerated={handleQuestionGenerated}\n projectId={projectId}\n tag={selectedTag}\n tagPath={selectedTagPath}\n model={selectedModel}\n />\n )}\n\n {/* 全自动蒸馏数据集配置对话框 */}\n setAutoDistillDialogOpen(false)}\n onStart={handleStartAutoDistill}\n projectId={projectId}\n project={project}\n stats={distillStats}\n />\n\n {/* 全自动蒸馏进度对话框 */}\n \n \n );\n}\n"], ["/easy-dataset/app/api/projects/[projectId]/files/route.js", "import { NextResponse } from 'next/server';\nimport { getProject } from '@/lib/db/projects';\nimport path from 'path';\nimport { getProjectRoot, ensureDir } from '@/lib/db/base';\nimport { promises as fs } from 'fs';\nimport {\n checkUploadFileInfoByMD5,\n createUploadFileInfo,\n delUploadFileInfoById,\n getUploadFilesPagination\n} from '@/lib/db/upload-files';\nimport { getFileMD5 } from '@/lib/util/file';\nimport { batchSaveTags } from '@/lib/db/tags';\nimport { getProjectChunks, getProjectTocByName } from '@/lib/file/text-splitter';\nimport { handleDomainTree } from '@/lib/util/domain-tree';\n\n// Replace the deprecated config export with the new export syntax\nexport const dynamic = 'force-dynamic';\n// This tells Next.js not to parse the request body automatically\nexport const bodyParser = false;\n\n// 获取项目文件列表\nexport async function GET(request, { params }) {\n try {\n const { projectId } = params;\n\n // 验证项目ID\n if (!projectId) {\n return NextResponse.json({ error: 'The project ID cannot be empty' }, { status: 400 });\n }\n const { searchParams } = new URL(request.url);\n const page = parseInt(searchParams.get('page')) || 1;\n const pageSize = parseInt(searchParams.get('pageSize')) || 10; // 每页10个文件,支持分页\n const fileName = searchParams.get('fileName') || '';\n const getAllIds = searchParams.get('getAllIds') === 'true'; // 新增:获取所有文件ID的标志\n\n // 如果请求所有文件ID,直接返回ID列表\n if (getAllIds) {\n const allFiles = await getUploadFilesPagination(projectId, 1, 9999, fileName); // 获取所有文件\n const allFileIds = allFiles.data?.map(file => String(file.id)) || [];\n return NextResponse.json({ allFileIds });\n }\n // 获取文件列表\n const files = await getUploadFilesPagination(projectId, page, pageSize, fileName);\n\n return NextResponse.json(files);\n } catch (error) {\n console.error('Error obtaining file list:', String(error));\n return NextResponse.json({ error: error.message || 'Error obtaining file list' }, { status: 500 });\n }\n}\n\n// 删除文件\nexport async function DELETE(request, { params }) {\n try {\n const { projectId } = params;\n const { searchParams } = new URL(request.url);\n const fileId = searchParams.get('fileId');\n const domainTreeAction = searchParams.get('domainTreeAction') || 'keep';\n\n // 从请求体中获取模型信息和语言环境\n let model, language;\n try {\n const requestData = await request.json();\n model = requestData.model;\n language = requestData.language || '中文';\n } catch (error) {\n console.warn('解析请求体失败,使用默认值:', error);\n // 如果无法解析请求体,使用默认值\n model = {\n providerId: 'openai',\n modelName: 'gpt-3.5-turbo',\n apiKey: process.env.OPENAI_API_KEY || ''\n };\n language = '中文';\n }\n\n // 验证项目ID和文件名\n if (!projectId) {\n return NextResponse.json({ error: 'The project ID cannot be empty' }, { status: 400 });\n }\n\n if (!fileId) {\n return NextResponse.json({ error: 'The file name cannot be empty' }, { status: 400 });\n }\n\n // 获取项目信息\n const project = await getProject(projectId);\n if (!project) {\n return NextResponse.json({ error: 'The project does not exist' }, { status: 404 });\n }\n\n // 删除文件及其相关的文本块、问题和数据集\n const { stats, fileName, fileInfo } = await delUploadFileInfoById(fileId);\n\n try {\n const projectRoot = await getProjectRoot();\n const projectPath = path.join(projectRoot, projectId);\n const tocDir = path.join(projectPath, 'toc');\n const baseName = path.basename(fileInfo.fileName, path.extname(fileInfo.fileName));\n const tocPath = path.join(tocDir, `${baseName}-toc.json`);\n\n // 检查文件是否存在再删除\n await fs.unlink(tocPath);\n console.log(`成功删除 TOC 文件: ${tocPath}`);\n } catch (error) {\n console.error(`删除 TOC 文件失败:`, String(error));\n // 即使 TOC 文件删除失败,不影响整体结果\n }\n\n // 如果选择了保持领域树不变,直接返回删除结果\n if (domainTreeAction === 'keep') {\n return NextResponse.json({\n message: '文件删除成功',\n stats: stats,\n domainTreeAction: 'keep',\n cascadeDelete: true\n });\n }\n\n // 处理领域树更新\n try {\n // 获取项目的所有文件\n const { chunks, toc } = await getProjectChunks(projectId);\n\n // 如果不存在文本块,说明项目已经没有文件了\n if (!chunks || chunks.length === 0) {\n // 清空领域树\n await batchSaveTags(projectId, []);\n return NextResponse.json({\n message: '文件删除成功,领域树已清空',\n stats: stats,\n domainTreeAction,\n cascadeDelete: true\n });\n }\n\n const deleteToc = await getProjectTocByName(projectId, fileName);\n\n // 调用领域树处理模块\n await handleDomainTree({\n projectId,\n action: domainTreeAction,\n allToc: toc,\n model,\n language,\n deleteToc,\n project\n });\n } catch (error) {\n console.error('Error updating domain tree after file deletion:', String(error));\n // 即使领域树更新失败,也不影响文件删除的结果\n }\n\n return NextResponse.json({\n message: '文件删除成功',\n stats: stats,\n domainTreeAction,\n cascadeDelete: true\n });\n } catch (error) {\n console.error('Error deleting file:', String(error));\n return NextResponse.json({ error: error.message || 'Error deleting file' }, { status: 500 });\n }\n}\n\n// 上传文件\nexport async function POST(request, { params }) {\n console.log('File upload request processing, parameters:', params);\n const { projectId } = params;\n\n // 验证项目ID\n if (!projectId) {\n console.log('The project ID cannot be empty, returning 400 error');\n return NextResponse.json({ error: 'The project ID cannot be empty' }, { status: 400 });\n }\n\n // 获取项目信息\n const project = await getProject(projectId);\n if (!project) {\n console.log('The project does not exist, returning 404 error');\n return NextResponse.json({ error: 'The project does not exist' }, { status: 404 });\n }\n console.log('Project information retrieved successfully:', project.name || project.id);\n\n try {\n console.log('Try using alternate methods for file upload...');\n\n // 检查请求头中是否包含文件名\n const encodedFileName = request.headers.get('x-file-name');\n const fileName = encodedFileName ? decodeURIComponent(encodedFileName) : null;\n console.log('Get file name from request header:', fileName);\n\n if (!fileName) {\n console.log('The request header does not contain a file name');\n return NextResponse.json(\n { error: 'The request header does not contain a file name (x-file-name)' },\n { status: 400 }\n );\n }\n\n // 检查文件类型\n if (!fileName.endsWith('.md') && !fileName.endsWith('.pdf')) {\n return NextResponse.json({ error: 'Only Markdown files are supported' }, { status: 400 });\n }\n\n // 直接从请求体中读取二进制数据\n const fileBuffer = Buffer.from(await request.arrayBuffer());\n\n // 保存文件\n const projectRoot = await getProjectRoot();\n const projectPath = path.join(projectRoot, projectId);\n const filesDir = path.join(projectPath, 'files');\n\n await ensureDir(filesDir);\n\n const filePath = path.join(filesDir, fileName);\n await fs.writeFile(filePath, fileBuffer);\n //获取文件大小\n const stats = await fs.stat(filePath);\n //获取文件md5\n const md5 = await getFileMD5(filePath);\n //获取文件扩展名\n const ext = path.extname(filePath);\n\n // let res = await checkUploadFileInfoByMD5(projectId, md5);\n // if (res) {\n // return NextResponse.json({ error: `【${fileName}】该文件已在此项目中存在` }, { status: 400 });\n // }\n\n let fileInfo = await createUploadFileInfo({\n projectId,\n fileName,\n size: stats.size,\n md5,\n fileExt: ext,\n path: filesDir\n });\n\n console.log('The file upload process is complete, and a successful response is returned');\n return NextResponse.json({\n message: 'File uploaded successfully',\n fileName,\n filePath,\n fileId: fileInfo.id\n });\n } catch (error) {\n console.error('Error processing file upload:', String(error));\n console.error('Error stack:', error.stack);\n return NextResponse.json(\n {\n error: 'File upload failed: ' + (error.message || 'Unknown error')\n },\n { status: 500 }\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/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/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/app/api/llm/model/route.js", "import { NextResponse } from 'next/server';\nimport { createLlmModels, getLlmModelsByProviderId } from '@/lib/db/llm-models'; // 导入db实例\n\n// 获取LLM模型\nexport async function GET(request) {\n try {\n const searchParams = request.nextUrl.searchParams;\n let providerId = searchParams.get('providerId');\n if (!providerId) {\n return NextResponse.json({ error: '参数错误' }, { status: 400 });\n }\n const models = await getLlmModelsByProviderId(providerId);\n if (!models) {\n return NextResponse.json({ error: 'LLM provider not found' }, { status: 404 });\n }\n return NextResponse.json(models);\n } catch (error) {\n console.error('Database query error:', String(error));\n return NextResponse.json({ error: 'Database query failed' }, { status: 500 });\n }\n}\n\n//同步最新模型列表\nexport async function POST(request) {\n try {\n const { newModels, providerId } = await request.json();\n const models = await getLlmModelsByProviderId(providerId);\n const existingModelIds = models.map(model => model.modelId);\n const diffModels = newModels.filter(item => !existingModelIds.includes(item.modelId));\n if (diffModels.length > 0) {\n // return NextResponse.json(await createLlmModels(diffModels));\n return NextResponse.json({ message: 'No new models to insert' }, { status: 200 });\n } else {\n return NextResponse.json({ message: 'No new models to insert' }, { status: 200 });\n }\n } catch (error) {\n return NextResponse.json({ error: 'Database insert failed' }, { status: 500 });\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/lib/services/tasks/answer-generation.js", "/**\n * 答案生成任务处理器\n * 负责异步处理答案生成任务,获取所有未生成答案的问题并批量处理\n */\n\nimport { PrismaClient } from '@prisma/client';\nimport { processInParallel } from '@/lib/util/async';\nimport { updateTask } from './index';\nimport datasetService from '@/lib/services/datasets';\nimport { getTaskConfig } from '@/lib/db/projects';\n\nconst prisma = new PrismaClient();\n\n/**\n * 处理答案生成任务\n * 查询未生成答案的问题并批量处理\n * @param {Object} task 任务对象\n * @returns {Promise}\n */\nexport async function processAnswerGenerationTask(task) {\n try {\n console.log(`开始处理答案生成任务: ${task.id}`);\n\n // 解析模型信息\n let modelInfo;\n try {\n modelInfo = JSON.parse(task.modelInfo);\n } catch (error) {\n throw new Error(`模型信息解析失败: ${error.message}`);\n }\n\n // 从任务对象直接获取项目 ID\n const projectId = task.projectId;\n\n // 1. 查询未生成答案的问题\n console.log(`开始处理项目 ${projectId} 的答案生成任务`);\n const questionsWithoutAnswers = await prisma.questions.findMany({\n where: {\n projectId,\n answered: false // 未生成答案的问题\n }\n });\n\n // 如果没有需要处理的问题,直接完成任务\n if (questionsWithoutAnswers.length === 0) {\n await updateTask(task.id, {\n status: 1, // 1 表示完成\n detail: '没有需要处理的问题',\n note: '',\n endTime: new Date()\n });\n return;\n }\n\n // 获取任务配置,包括并发限制\n const taskConfig = await getTaskConfig(projectId);\n const concurrencyLimit = taskConfig.concurrencyLimit || 3;\n\n // 更新任务总数\n const totalCount = questionsWithoutAnswers.length;\n await updateTask(task.id, {\n totalCount,\n detail: `待处理问题数量: ${totalCount}`,\n note: ''\n });\n\n // 2. 批量处理每个问题\n let successCount = 0;\n let errorCount = 0;\n let totalDatasets = 0;\n let latestTaskStatus = 0;\n\n // 单个问题处理函数\n const processQuestion = async question => {\n try {\n // 如果任务已经被标记为失败或已中断,不再继续处理\n const latestTask = await prisma.task.findUnique({ where: { id: task.id } });\n if (latestTask.status === 2 || latestTask.status === 3) {\n latestTaskStatus = latestTask.status;\n return;\n }\n\n // 调用数据集生成服务生成答案\n const result = await datasetService.generateDatasetForQuestion(task.projectId, question.id, {\n model: modelInfo,\n language: task.language === 'zh-CN' ? '中文' : 'en'\n });\n console.log(`问题 ${question.id} 已生成答案,数据集 ID: ${result.dataset.id}`);\n\n // 增加成功计数\n successCount++;\n totalDatasets++;\n\n // 更新任务进度\n const progressNote = `已处理: ${successCount + errorCount}/${totalCount}, 成功: ${successCount}, 失败: ${errorCount}, 共生成数据集: ${totalDatasets}`;\n await updateTask(task.id, {\n completedCount: successCount + errorCount,\n detail: progressNote,\n note: progressNote\n });\n\n return { success: true, questionId: question.id, datasetId: result.dataset.id };\n } catch (error) {\n console.error(`处理问题 ${question.id} 出错:`, error);\n errorCount++;\n\n // 更新任务进度\n const progressNote = `已处理: ${successCount + errorCount}/${totalCount}, 成功: ${successCount}, 失败: ${errorCount}, 共生成数据集: ${totalDatasets}`;\n await updateTask(task.id, {\n completedCount: successCount + errorCount,\n detail: progressNote,\n note: progressNote\n });\n\n return { success: false, questionId: question.id, error: error.message };\n }\n };\n\n // 并行处理所有问题,使用任务设置中的并发限制\n await processInParallel(questionsWithoutAnswers, processQuestion, concurrencyLimit, async (completed, total) => {\n console.log(`答案生成进度: ${completed}/${total}`);\n });\n\n if (!latestTaskStatus) {\n // 任务完成,更新状态\n const finalStatus = errorCount > 0 && successCount === 0 ? 2 : 1; // 如果全部失败,标记为失败;否则标记为完成\n await updateTask(task.id, {\n status: finalStatus,\n completedCount: successCount + errorCount,\n detail: '',\n note: '',\n endTime: new Date()\n });\n }\n\n console.log(`任务 ${task.id} 已完成`);\n } catch (error) {\n console.error('处理答案生成任务出错:', error);\n await updateTask(task.id, {\n status: 2, // 2 表示失败\n detail: `处理失败: ${error.message}`,\n note: `处理失败: ${error.message}`,\n endTime: new Date()\n });\n }\n}\n\nexport default {\n processAnswerGenerationTask\n};\n"], ["/easy-dataset/lib/services/tasks/file-processing.js", "/**\n * 文件处理任务\n */\nimport { splitProjectFile } from '@/lib/file/text-splitter';\nimport { handleDomainTree } from '@/lib/util/domain-tree';\nimport { processPdf, getFilePageCount } from '@/lib/file/file-process/pdf';\nimport { getProject, updateProject } from '@/lib/db/projects';\nimport { TASK } from '@/constant';\nimport { updateTask } from './index';\n\n/**\n * 处理文件处理任务\n * @param {Object} task 任务对象\n */\nexport async function processFileProcessingTask(task) {\n const taskMessage = {\n current: {\n fileName: '',\n processedPage: 0,\n totalPage: 0\n },\n stepInfo: '',\n processedFiles: 0,\n totalFiles: 0,\n errorList: [],\n finishedList: []\n };\n try {\n console.log(`start processing file processing task: ${task.id}`);\n\n const params = JSON.parse(task.note);\n const { projectId, fileList, strategy = 'default', vsionModel, domainTreeAction } = params;\n\n // 记录文件总数\n taskMessage.totalFiles = fileList.length;\n\n // 计算转换总页数\n const totalPages = await getFilePageCount(projectId, fileList);\n\n // 更新任务信息\n taskMessage.stepInfo = `Total ${taskMessage.totalFiles} files to process, total ${totalPages} pages`;\n\n // 更新任务状态\n await updateTask(task.id, {\n status: TASK.STATUS.PROCESSING,\n totalCount: totalPages + 1, // 总页数 + 领域树处理\n detail: JSON.stringify(taskMessage),\n startTime: new Date()\n });\n\n //进行文本分割\n let fileResult = {\n totalChunks: 0,\n chunks: [],\n toc: ''\n };\n\n const project = await getProject(projectId);\n\n // 循环处理文件\n for (const file of fileList) {\n try {\n taskMessage.current.fileName = file.fileName;\n taskMessage.current.processedPage = 1; // 重置当前处理页数\n taskMessage.current.totalPage = file.pageCount || 1; // 设置当前文件总页数\n\n await updateTask(task.id, {\n status: TASK.STATUS.PROCESSING,\n totalCount: totalPages + 1, // 总页数 + 领域树处理\n detail: JSON.stringify(taskMessage),\n startTime: new Date()\n });\n\n if (file.fileName.endsWith('.pdf')) {\n task.vsionModel = vsionModel; // 仅用于视觉模型处理\n const result = await processPdf(strategy, projectId, file.fileName, {\n ...params.options,\n updateTask: updateTask,\n task: task,\n message: taskMessage\n });\n //确认文件处理状态\n if (!result.success) {\n throw new Error(result.error || `File processing failed`);\n }\n }\n\n // 文本分割\n const { toc, chunks, totalChunks } = await splitProjectFile(projectId, file);\n fileResult.toc += toc;\n fileResult.chunks.push(...chunks);\n fileResult.totalChunks += totalChunks;\n console.log(projectId, file.fileName, `${file.fileName} Text split completed`);\n\n // 更新任务信息\n taskMessage.finishedList.push(file);\n taskMessage.processedFiles++;\n await updateTask(task.id, {\n completedCount: task.completedCount + file.pageCount, // 已处理页数\n detail: JSON.stringify(taskMessage), // 更新任务信息\n updateAt: new Date()\n });\n task.completedCount += file.pageCount; // 更新任务已完成页数\n } catch (error) {\n const errorMessage = `Processing file ${file.fileName} failed: ${error.message}`;\n taskMessage.errorList.push(errorMessage);\n console.error(errorMessage);\n //将文件粒度的任务信息存储到任务详情中\n await updateTask(task.id, {\n detail: JSON.stringify(taskMessage)\n });\n }\n }\n\n console.log('domainTreeAction', domainTreeAction);\n try {\n // 调用领域树处理模块\n const tags = await handleDomainTree({\n projectId,\n newToc: fileResult.toc,\n model: JSON.parse(task.modelInfo),\n language: task.language,\n action: domainTreeAction,\n fileList,\n project\n });\n\n if (!tags && domainTreeAction !== 'keep') {\n await updateProject(projectId, { ...project });\n return NextResponse.json(\n { error: 'AI analysis failed, please check model configuration, delete file and retry!' },\n { status: 400 }\n );\n }\n\n //整个转换任务=》文本分割=》领域树构造结束后 转换完成\n console.log(`File processing completed successfully`);\n // 更新任务进度\n taskMessage.stepInfo = `File processing completed successfully`;\n await updateTask(task.id, {\n completedCount: task.totalCount,\n status: TASK.STATUS.COMPLETED,\n detail: JSON.stringify(taskMessage)\n });\n } catch (error) {\n console.error(`processing failed:`, error);\n taskMessage.stepInfo = `File processing failed: ${error.message}`;\n // 更新任务状态为失败\n await updateTask(task.id, {\n status: TASK.STATUS.FAILED,\n completedCount: 0,\n detail: JSON.stringify(taskMessage),\n endTime: new Date()\n });\n return;\n }\n console.log(`task ${task.id} finished`);\n } catch (error) {\n console.error('pdf processing failed:', error);\n taskMessage.stepInfo = `File processing failed: ${String(error)}`;\n await updateTask(task.id, {\n status: TASK.STATUS.FAILED,\n detail: JSON.stringify(taskMessage),\n endTime: new Date()\n });\n }\n}\n\nexport default {\n processFileProcessingTask\n};\n"], ["/easy-dataset/lib/services/ga/ga-pairs.js", "import { generateGaPairs } from './ga-generation';\nimport { getModelById } from '../models';\nimport { saveGaPairs, getGaPairsByFileId } from '@/lib/db/ga-pairs';\nimport { getProjectFileContentById } from '@/lib/db/files';\nimport logger from '@/lib/util/logger';\n\n/**\n * Batch generate GA pairs for multiple files\n * @param {string} projectId - Project ID\n * @param {Array} files - Array of file objects\n * @param {string} modelConfigId - Model configuration ID\n * @param {string} language - Language for generation (default: '中文')\n * @param {boolean} appendMode - Whether to append to existing GA pairs (default: false)\n * @returns {Promise} - Array of generation results\n */\nexport async function batchGenerateGaPairs(projectId, files, modelConfigId, language = '中文', appendMode = false) {\n try {\n logger.info(`Starting batch GA pairs generation for ${files.length} files`);\n\n // Get model configuration\n const modelConfig = await getModelById(modelConfigId);\n if (!modelConfig) {\n throw new Error('Model configuration not found');\n }\n\n const results = [];\n\n // Process each file\n for (const file of files) {\n try {\n logger.info(`Processing file: ${file.fileName}`);\n\n // Check if GA pairs already exist for this file\n const existingPairs = await getGaPairsByFileId(file.id);\n\n // 在非追加模式下,如果已存在GA对则跳过\n if (!appendMode && existingPairs && existingPairs.length > 0) {\n logger.info(`GA pairs already exist for file ${file.fileName}, skipping`);\n results.push({\n fileId: file.id,\n fileName: file.fileName,\n success: true,\n skipped: true,\n message: 'GA pairs already exist',\n gaPairs: existingPairs\n });\n continue;\n }\n // Get file content\n const fileContent = await getProjectFileContentById(projectId, file.id);\n if (!fileContent) {\n throw new Error('File content not found');\n }\n // Limit content length for processing (max 50,000 characters)\n const maxLength = 50000;\n const content = fileContent.length > maxLength ? fileContent.substring(0, maxLength) + '...' : fileContent;\n\n // Generate GA pairs\n const gaPairs = await generateGaPairs(content, projectId, language);\n\n // Save GA pairs to database\n const savedPairs = await saveGaPairsForFile(projectId, file.id, gaPairs, appendMode, existingPairs);\n\n results.push({\n fileId: file.id,\n fileName: file.fileName,\n success: true,\n skipped: false,\n message: `Generated ${gaPairs.length} GA pairs`,\n gaPairs: savedPairs\n });\n\n logger.info(`Successfully generated GA pairs for file: ${file.fileName}`);\n } catch (error) {\n logger.error(`Failed to generate GA pairs for file ${file.fileName}:`, error);\n results.push({\n fileId: file.id,\n fileName: file.fileName,\n success: false,\n skipped: false,\n error: error.message,\n message: `Failed: ${error.message}`\n });\n }\n }\n\n logger.info(\n `Batch GA pairs generation completed. Success: ${results.filter(r => r.success).length}, Failed: ${results.filter(r => !r.success).length}`\n );\n return results;\n } catch (error) {\n logger.error('Batch GA pairs generation failed:', error);\n throw error;\n }\n}\n\n/**\n * Save GA pairs for a file\n * @param {string} projectId - Project ID\n * @param {string} fileId - File ID\n * @param {Array} gaPairs - Generated GA pairs\n * @param {boolean} appendMode - Whether to append to existing GA pairs\n * @param {Array} existingPairs - Existing GA pairs (for append mode)\n * @returns {Promise} - Saved GA pairs\n */\nasync function saveGaPairsForFile(projectId, fileId, gaPairs, appendMode = false, existingPairs = []) {\n try {\n if (appendMode && existingPairs.length > 0) {\n // 追加模式:使用与单文件生成相同的逻辑\n const { createGaPairs } = await import('@/lib/db/ga-pairs');\n\n const startPairNumber = existingPairs.length + 1;\n const newGaPairData = gaPairs.map((pair, index) => ({\n projectId,\n fileId,\n pairNumber: startPairNumber + index,\n genreTitle: pair.genre?.title || pair.genreTitle || '',\n genreDesc: pair.genre?.description || pair.genreDesc || '',\n audienceTitle: pair.audience?.title || pair.audienceTitle || '',\n audienceDesc: pair.audience?.description || pair.audienceDesc || '',\n isActive: true\n }));\n\n // 只创建新的GA对,不删除现有的\n await createGaPairs(newGaPairData);\n\n // 返回所有GA对(现有的+新增的)\n const allPairs = await getGaPairsByFileId(fileId);\n return allPairs;\n } else {\n // Use the database function to save GA pairs\n const result = await saveGaPairs(projectId, fileId, gaPairs);\n\n // Get the saved pairs to return\n const savedPairs = await getGaPairsByFileId(fileId);\n return savedPairs;\n }\n } catch (error) {\n logger.error('Failed to save GA pairs:', error);\n throw error;\n }\n}\n"], ["/easy-dataset/components/ExportDatasetDialog.js", "// ExportDatasetDialog.js 组件\nimport React, { useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { Dialog, DialogTitle, DialogContent, DialogActions, Button, Box, Tabs, Tab } from '@mui/material';\n\n// 导入拆分后的组件\nimport LocalExportTab from './export/LocalExportTab';\nimport LlamaFactoryTab from './export/LlamaFactoryTab';\nimport HuggingFaceTab from './export/HuggingFaceTab';\n\nconst ExportDatasetDialog = ({ open, onClose, onExport, projectId }) => {\n const { t } = useTranslation();\n const [formatType, setFormatType] = useState('alpaca');\n const [systemPrompt, setSystemPrompt] = useState('');\n const [confirmedOnly, setConfirmedOnly] = useState(false);\n const [fileFormat, setFileFormat] = useState('json');\n const [includeCOT, setIncludeCOT] = useState(true);\n const [currentTab, setCurrentTab] = useState(0);\n // alpaca 格式特有的设置\n const [alpacaFieldType, setAlpacaFieldType] = useState('instruction'); // 'instruction' 或 'input'\n const [customInstruction, setCustomInstruction] = useState(''); // 当选择 input 时使用的自定义 instruction\n const [customFields, setCustomFields] = useState({\n questionField: 'instruction',\n answerField: 'output',\n cotField: 'complexCOT', // 添加思维链字段名\n includeLabels: false,\n includeChunk: false // 添加是否包含chunk字段\n });\n\n const handleFileFormatChange = event => {\n setFileFormat(event.target.value);\n };\n\n const handleFormatChange = event => {\n setFormatType(event.target.value);\n // 根据格式类型设置默认字段名\n if (event.target.value === 'alpaca') {\n setCustomFields({\n ...customFields,\n questionField: 'instruction',\n answerField: 'output'\n });\n } else if (event.target.value === 'sharegpt') {\n setCustomFields({\n ...customFields,\n questionField: 'content',\n answerField: 'content'\n });\n } else if (event.target.value === 'custom') {\n // 自定义格式保持当前值\n }\n };\n\n const handleSystemPromptChange = event => {\n setSystemPrompt(event.target.value);\n };\n\n const handleConfirmedOnlyChange = event => {\n setConfirmedOnly(event.target.checked);\n };\n\n // 新增处理函数\n const handleIncludeCOTChange = event => {\n setIncludeCOT(event.target.checked);\n };\n\n const handleCustomFieldChange = field => event => {\n setCustomFields({\n ...customFields,\n [field]: event.target.value\n });\n };\n\n const handleIncludeLabelsChange = event => {\n setCustomFields({\n ...customFields,\n includeLabels: event.target.checked\n });\n };\n\n const handleIncludeChunkChange = event => {\n setCustomFields({\n ...customFields,\n includeChunk: event.target.checked\n });\n };\n\n // 处理 Alpaca 字段类型变更\n const handleAlpacaFieldTypeChange = event => {\n setAlpacaFieldType(event.target.value);\n };\n\n // 处理自定义 instruction 变更\n const handleCustomInstructionChange = event => {\n setCustomInstruction(event.target.value);\n };\n\n const handleExport = () => {\n onExport({\n formatType,\n systemPrompt,\n confirmedOnly,\n fileFormat,\n includeCOT,\n alpacaFieldType, // 添加 alpaca 字段类型\n customInstruction, // 添加自定义 instruction\n customFields: formatType === 'custom' ? customFields : undefined\n });\n };\n\n return (\n \n {t('export.title')}\n \n \n setCurrentTab(newValue)} aria-label=\"export tabs\">\n \n \n \n \n \n\n {/* 第一个标签页:本地导出 */}\n {currentTab === 0 && (\n \n )}\n\n {/* 第二个标签页:Llama Factory */}\n {currentTab === 1 && (\n \n )}\n\n {/* 第三个标签页:HuggingFace */}\n {currentTab === 2 && (\n \n )}\n \n \n );\n};\n\nexport default ExportDatasetDialog;\n"], ["/easy-dataset/electron/modules/db-updater.js", "const fs = require('fs');\nconst path = require('path');\nconst { PrismaClient } = require('@prisma/client');\n\n/**\n * 执行SQL命令\n * @param {string} dbUrl 数据库连接 URL\n * @param {string} sql SQL命令\n * @returns {Promise}\n */\nasync function executeSql(dbUrl, sql) {\n // 允许多条SQL语句分开执行,支持分号和空行分隔\n const statements = sql\n .split(';')\n .map(stmt => stmt.trim())\n .filter(stmt => stmt.length > 0);\n\n if (statements.length === 0) {\n return;\n }\n\n // 设置环境变量\n process.env.DATABASE_URL = dbUrl;\n\n // 创建Prisma实例\n const prisma = new PrismaClient();\n\n try {\n // 执行每条SQL语句\n for (const statement of statements) {\n await prisma.$executeRawUnsafe(statement);\n }\n } finally {\n // 关闭连接\n await prisma.$disconnect();\n }\n}\n\n/**\n * 获取本地和应用的SQL配置文件\n * @param {string} userDataPath 用户数据目录\n * @param {string} resourcesPath 应用资源目录\n * @param {boolean} isDev 是否开发环境\n * @returns {Promise<{userSqlConfig: Array, appSqlConfig: Array}>}\n */\nasync function getSqlConfigs(userDataPath, resourcesPath, isDev) {\n // 用户SQL配置文件路径\n const userSqlPath = path.join(userDataPath, 'sql.json');\n\n // 应用SQL配置文件路径\n const appSqlPath = isDev\n ? path.join(__dirname, '..', 'prisma', 'sql.json')\n : path.join(resourcesPath, 'prisma', 'sql.json');\n\n let userSqlConfig = [];\n let appSqlConfig = [];\n\n // 读取应用SQL配置\n try {\n if (fs.existsSync(appSqlPath)) {\n const appSqlContent = fs.readFileSync(appSqlPath, 'utf8');\n appSqlConfig = JSON.parse(appSqlContent);\n }\n } catch (error) {\n throw new Error(`读取应用SQL配置文件失败: ${error.message}`);\n }\n\n // 读取用户SQL配置(如果存在)\n try {\n if (fs.existsSync(userSqlPath)) {\n const userSqlContent = fs.readFileSync(userSqlPath, 'utf8');\n userSqlConfig = JSON.parse(userSqlContent);\n }\n } catch (error) {\n // 如果用户SQL配置不存在或无法解析,使用空数组\n userSqlConfig = [];\n }\n\n return { userSqlConfig, appSqlConfig };\n}\n\n/**\n * 更新用户SQL配置文件\n * @param {string} userDataPath 用户数据目录\n * @param {Array} sqlConfig 新的SQL配置\n */\nfunction updateUserSqlConfig(userDataPath, sqlConfig) {\n const userSqlPath = path.join(userDataPath, 'sql.json');\n fs.writeFileSync(userSqlPath, JSON.stringify(sqlConfig, null, 4), 'utf8');\n}\n\n// 不再需要版本比较功能\n\n/**\n * 获取需要执行的SQL命令\n * @param {Array} userSqlConfig 用户SQL配置\n * @param {Array} appSqlConfig 应用SQL配置\n * @returns {Array} 需要执行的SQL命令\n */\nfunction getSqlsToExecute(userSqlConfig, appSqlConfig) {\n // 创建用户已执行的SQL集合 (使用 version + sql 的组合作为唯一标识)\n const userExecutedSqlSet = new Set();\n userSqlConfig.forEach(item => {\n const key = `${item.version}:${item.sql}`;\n userExecutedSqlSet.add(key);\n });\n\n // 过滤出用户需要执行的SQL (即应用SQL配置中存在但用户尚未执行的SQL)\n return appSqlConfig.filter(item => {\n const key = `${item.version}:${item.sql}`;\n return !userExecutedSqlSet.has(key);\n });\n}\n\n/**\n * 更新数据库\n * @param {string} userDataPath 用户数据目录\n * @param {string} resourcesPath 应用资源目录\n * @param {boolean} isDev 是否开发环境\n * @param {function} logger 日志函数\n */\nasync function updateDatabase(userDataPath, resourcesPath, isDev, logger = console.log) {\n const dbPath = path.join(userDataPath, 'local-db', 'db.sqlite');\n\n try {\n // 获取SQL配置\n const { userSqlConfig, appSqlConfig } = await getSqlConfigs(userDataPath, resourcesPath, isDev);\n\n // 获取需要执行的SQL\n const sqlsToExecute = getSqlsToExecute(userSqlConfig, appSqlConfig);\n\n if (sqlsToExecute.length === 0) {\n logger('数据库已是最新版本,无需更新');\n return { updated: false, message: '数据库已是最新版本' };\n }\n\n // 设置数据库URL\n const dbUrl = `file:${dbPath}`;\n\n // 执行SQL更新\n logger(`发现 ${sqlsToExecute.length} 个数据库更新,开始执行...`);\n for (const item of sqlsToExecute) {\n try {\n logger(`执行版本 ${item.version} 的SQL更新: ${item.sql.substring(0, 100)}...`);\n await executeSql(dbUrl, item.sql);\n // 添加到用户SQL配置\n userSqlConfig.push(item);\n } catch (error) {\n logger(`执行版本 ${item.version} 的SQL更新失败: ${error.message}`);\n }\n }\n\n // 更新用户SQL配置文件\n updateUserSqlConfig(userDataPath, userSqlConfig);\n\n logger('数据库更新完成');\n return {\n updated: true,\n message: `成功执行了 ${sqlsToExecute.length} 个数据库更新`,\n executedVersions: sqlsToExecute.map(item => item.version)\n };\n } catch (error) {\n logger(`数据库更新失败: ${error.message}`);\n return { updated: false, error: error.message };\n }\n}\n\nmodule.exports = {\n updateDatabase,\n executeSql,\n getSqlConfigs,\n updateUserSqlConfig,\n getSqlsToExecute\n};\n"], ["/easy-dataset/components/home/StatsCard.js", "'use client';\n\nimport { Paper, Grid, Box, Typography, useMediaQuery, Avatar } from '@mui/material';\nimport { styles } from '@/styles/home';\nimport { useTheme } from '@mui/material';\nimport { motion } from 'framer-motion';\nimport FolderOpenIcon from '@mui/icons-material/FolderOpen';\nimport QuestionAnswerIcon from '@mui/icons-material/QuestionAnswer';\nimport StorageIcon from '@mui/icons-material/Storage';\nimport MemoryIcon from '@mui/icons-material/Memory';\n\n// 默认模型列表\nconst mockModels = [\n { id: 'deepseek-r1', provider: 'Ollama', name: 'DeepSeek-R1' },\n { id: 'gpt-3.5-turbo-openai', provider: 'OpenAI', name: 'gpt-3.5-turbo' },\n { id: 'gpt-3.5-turbo-guiji', provider: 'Guiji', name: 'gpt-3.5-turbo' },\n { id: 'glm-4-flash', provider: 'Zhipu AI', name: 'GLM-4-Flash' }\n];\n\nexport default function StatsCard({ projects }) {\n const theme = useTheme();\n const isMobile = useMediaQuery(theme.breakpoints.down('sm'));\n\n // 统计卡片数据\n const statsItems = [\n {\n value: projects.length,\n label: t('stats.ongoingProjects'),\n color: 'primary',\n icon: \n },\n {\n value: projects.reduce((sum, project) => sum + (project.questionsCount || 0), 0),\n label: t('stats.questionCount'),\n color: 'secondary',\n icon: \n },\n {\n value: projects.reduce((sum, project) => sum + (project.datasetsCount || 0), 0),\n label: t('stats.generatedDatasets'),\n color: 'success',\n icon: \n },\n {\n value: mockModels.length,\n label: t('stats.supportedModels'),\n color: 'warning',\n icon: \n }\n ];\n\n return (\n \n \n {statsItems.map((item, index) => (\n \n \n \n {item.icon}\n \n \n {item.value}\n \n \n {item.label}\n \n \n \n ))}\n \n \n );\n}\n"], ["/easy-dataset/app/page.js", "'use client';\n\nimport { useState, useEffect } from 'react';\nimport { Container, Box, Typography, CircularProgress, Stack, useTheme } from '@mui/material';\nimport ErrorOutlineIcon from '@mui/icons-material/ErrorOutline';\nimport Navbar from '@/components/Navbar';\nimport HeroSection from '@/components/home/HeroSection';\nimport StatsCard from '@/components/home/StatsCard';\nimport ProjectList from '@/components/home/ProjectList';\nimport CreateProjectDialog from '@/components/home/CreateProjectDialog';\nimport MigrationDialog from '@/components/home/MigrationDialog';\nimport { motion } from 'framer-motion';\nimport { useTranslation } from 'react-i18next';\n\nexport default function Home() {\n const { t } = useTranslation();\n const [projects, setProjects] = useState([]);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n const [createDialogOpen, setCreateDialogOpen] = useState(false);\n const [unmigratedProjects, setUnmigratedProjects] = useState([]);\n const [migrationDialogOpen, setMigrationDialogOpen] = useState(false);\n\n useEffect(() => {\n async function fetchProjects() {\n try {\n setLoading(true);\n // 获取用户创建的项目详情\n const response = await fetch(`/api/projects`);\n\n if (!response.ok) {\n throw new Error(t('projects.fetchFailed'));\n }\n\n const data = await response.json();\n setProjects(data);\n\n // 检查是否有未迁移的项目\n await checkUnmigratedProjects();\n } catch (error) {\n console.error(t('projects.fetchError'), String(error));\n setError(String(error));\n } finally {\n setLoading(false);\n }\n }\n\n // 检查未迁移的项目\n async function checkUnmigratedProjects() {\n try {\n const response = await fetch('/api/projects/unmigrated');\n\n if (!response.ok) {\n console.error('检查未迁移项目失败');\n return;\n }\n\n const { success, data } = await response.json();\n\n if (success && Array.isArray(data) && data.length > 0) {\n setUnmigratedProjects(data);\n setMigrationDialogOpen(true);\n }\n } catch (error) {\n console.error('检查未迁移项目出错', error);\n }\n }\n\n fetchProjects();\n }, []);\n\n const theme = useTheme();\n\n return (\n
\n \n\n setCreateDialogOpen(true)} />\n\n \n {/* */}\n\n {loading && (\n \n \n \n {t('projects.loading')}\n \n \n )}\n\n {error && !loading && (\n \n \n \n \n {t('projects.fetchFailed')}: {error}\n \n \n \n )}\n\n {!loading && (\n \n setCreateDialogOpen(true)} />\n \n )}\n \n\n setCreateDialogOpen(false)} />\n\n {/* 项目迁移对话框 */}\n setMigrationDialogOpen(false)}\n projectIds={unmigratedProjects}\n />\n
\n );\n}\n"], ["/easy-dataset/app/projects/[projectId]/tasks/page.js", "'use client';\n\nimport React, { useState, useEffect } from 'react';\nimport { Box, Typography, Container, IconButton } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\nimport axios from 'axios';\nimport TaskIcon from '@mui/icons-material/Task';\nimport { toast } from 'sonner';\n\n// 导入任务管理组件\nimport TaskFilters from '@/components/tasks/TaskFilters';\nimport TasksTable from '@/components/tasks/TasksTable';\n\n/**\n * 任务管理页面\n * 支持任务列表查看、筛选、中断和删除操作\n * 分页展示、国际化支持\n */\n\n// 任务状态映射\nconst TASK_STATUS = {\n 0: { label: '处理中', color: 'warning' },\n 1: { label: '已完成', color: 'success' },\n 2: { label: '失败', color: 'error' },\n 3: { label: '已中断', color: 'default' }\n};\n\n// 任务类型映射\nconst TASK_TYPES = {\n 'text-processing': '文献处理',\n 'question-generation': '问题生成',\n 'answer-generation': '答案生成',\n 'data-distillation': '数据蒸馏',\n 'pdf-processing': 'PDF解析'\n};\n\nexport default function TasksPage({ params }) {\n const { projectId } = params;\n const { t } = useTranslation();\n\n // 状态管理\n const [loading, setLoading] = useState(false);\n const [tasks, setTasks] = useState([]);\n const [statusFilter, setStatusFilter] = useState('all');\n const [typeFilter, setTypeFilter] = useState('all');\n\n // 分页相关状态\n const [page, setPage] = useState(0);\n const [rowsPerPage, setRowsPerPage] = useState(10);\n const [totalCount, setTotalCount] = useState(0);\n\n // 获取任务列表\n const fetchTasks = async () => {\n if (!projectId) return;\n\n try {\n setLoading(true);\n // 构建查询参数\n let url = `/api/projects/${projectId}/tasks/list`;\n const queryParams = [];\n\n if (statusFilter !== 'all') {\n queryParams.push(`status=${statusFilter}`);\n }\n\n if (typeFilter !== 'all') {\n queryParams.push(`taskType=${typeFilter}`);\n }\n\n // 添加分页参数\n queryParams.push(`page=${page}`);\n queryParams.push(`limit=${rowsPerPage}`);\n\n if (queryParams.length > 0) {\n url += '?' + queryParams.join('&');\n }\n\n const response = await axios.get(url);\n if (response.data?.code === 0) {\n setTasks(response.data.data || []);\n // 设置总记录数\n setTotalCount(response.data.total || response.data.data?.length || 0);\n }\n } catch (error) {\n console.error('获取任务列表失败:', error);\n toast.error(t('tasks.fetchFailed'));\n } finally {\n setLoading(false);\n }\n };\n\n // 初始化和过滤器变更时获取任务列表\n useEffect(() => {\n fetchTasks();\n\n // 定时刷新处理中的任务\n const intervalId = setInterval(() => {\n if (statusFilter === 'all' || statusFilter === '0') {\n fetchTasks();\n }\n }, 5000); // 每5秒更新一次处理中的任务\n\n return () => clearInterval(intervalId);\n }, [projectId, statusFilter, typeFilter, page, rowsPerPage]);\n\n // 删除任务\n const handleDeleteTask = async taskId => {\n if (!confirm(t('tasks.confirmDelete'))) return;\n\n try {\n const response = await axios.delete(`/api/projects/${projectId}/tasks/${taskId}`);\n if (response.data?.code === 0) {\n toast.success(t('tasks.deleteSuccess'));\n fetchTasks();\n } else {\n toast.error(t('tasks.deleteFailed'));\n }\n } catch (error) {\n console.error('删除任务失败:', error);\n toast.error(t('tasks.deleteFailed'));\n }\n };\n\n // 中断任务\n const handleAbortTask = async taskId => {\n if (!confirm(t('tasks.confirmAbort'))) return;\n\n try {\n const response = await axios.patch(`/api/projects/${projectId}/tasks/${taskId}`, {\n status: 3, // 3 表示已中断\n detail: t('tasks.status.aborted'),\n note: t('tasks.status.aborted')\n });\n\n if (response.data?.code === 0) {\n toast.success(t('tasks.abortSuccess'));\n fetchTasks();\n } else {\n toast.error(t('tasks.abortFailed'));\n }\n } catch (error) {\n console.error('中断任务失败:', error);\n toast.error(t('tasks.abortFailed'));\n }\n };\n\n // 分页参数更改处理\n const handleChangePage = (event, newPage) => {\n setPage(newPage);\n };\n\n const handleChangeRowsPerPage = event => {\n setRowsPerPage(parseInt(event.target.value, 10));\n setPage(0);\n };\n\n return (\n \n \n \n \n {t('tasks.title')}\n \n\n {/* 任务筛选器组件 */}\n \n \n\n {/* 任务表格组件 */}\n \n \n );\n}\n"], ["/easy-dataset/app/projects/[projectId]/text-split/useQuestionGeneration.js", "'use client';\n\nimport { useState, useCallback } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport i18n from '@/lib/i18n';\nimport request from '@/lib/util/request';\nimport { processInParallel } from '@/lib/util/async';\nimport { toast } from 'sonner';\n\n/**\n * 问题生成的自定义Hook\n * @param {string} projectId - 项目ID\n * @param {Function} onError - 错误处理回调\n * @param {Object} taskSettings - 任务设置\n * @returns {Object} - 问题生成状态和操作方法\n */\nexport default function useQuestionGeneration(projectId, taskSettings) {\n const { t } = useTranslation();\n const [processing, setProcessing] = useState(false);\n const [progress, setProgress] = useState({\n total: 0,\n completed: 0,\n percentage: 0,\n questionCount: 0\n });\n\n /**\n * 重置进度状态\n */\n const resetProgress = useCallback(() => {\n setTimeout(() => {\n setProgress({\n total: 0,\n completed: 0,\n percentage: 0,\n questionCount: 0\n });\n }, 1000); // 延迟重置,让用户看到完成的进度\n }, []);\n\n /**\n * 处理生成问题\n * @param {Array} chunkIds - 文本块ID列表\n * @param {Object} selectedModelInfo - 选定的模型信息\n * @param {Function} fetchChunks - 刷新文本块列表的函数\n */\n const handleGenerateQuestions = useCallback(\n async (chunkIds, selectedModelInfo, fetchChunks) => {\n try {\n setProcessing(true);\n // 重置进度状态\n setProgress({\n total: chunkIds.length,\n completed: 0,\n percentage: 0,\n questionCount: 0\n });\n\n let model = selectedModelInfo;\n\n // 如果仍然没有模型信息,抛出错误\n if (!model) {\n throw new Error(t('textSplit.selectModelFirst'));\n }\n\n // 如果是单个文本块,直接调用单个生成接口\n if (chunkIds.length === 1) {\n const chunkId = chunkIds[0];\n // 获取当前语言环境\n const currentLanguage = i18n.language === 'zh-CN' ? '中文' : 'en';\n\n const response = await request(`/api/projects/${projectId}/chunks/${chunkId}/questions`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n model,\n language: currentLanguage,\n enableGaExpansion: true // 默认启用GA扩展\n })\n });\n\n if (!response.ok) {\n const errorData = await response.json();\n throw new Error(errorData.error || t('textSplit.generateQuestionsFailed', { chunkId }));\n }\n\n const data = await response.json();\n toast.success(\n t('textSplit.questionsGeneratedSuccess', {\n total: data.total\n }),\n {\n duration: 3000\n }\n );\n } else {\n // 如果是多个文本块,循环调用单个文本块的问题生成接口\n let totalQuestions = 0;\n let successCount = 0;\n let errorCount = 0;\n\n // 单个文本块处理函数\n const processChunk = async chunkId => {\n try {\n // 获取当前语言环境\n const currentLanguage = i18n.language === 'zh-CN' ? '中文' : 'en';\n\n const response = await request(\n `/api/projects/${projectId}/chunks/${encodeURIComponent(chunkId)}/questions`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n model,\n language: currentLanguage,\n enableGaExpansion: true // 默认启用GA扩展\n })\n }\n );\n\n if (!response.ok) {\n const errorData = await response.json();\n console.error(t('textSplit.generateQuestionsForChunkFailed', { chunkId }), errorData.error);\n errorCount++;\n return { success: false, chunkId, error: errorData.error };\n }\n\n const data = await response.json();\n console.log(t('textSplit.questionsGenerated', { chunkId, total: data.total }));\n\n // 更新进度状态\n setProgress(prev => {\n const completed = prev.completed + 1;\n const percentage = Math.round((completed / prev.total) * 100);\n const questionCount = prev.questionCount + (data.total || 0);\n\n return {\n ...prev,\n completed,\n percentage,\n questionCount\n };\n });\n\n totalQuestions += data.total || 0;\n successCount++;\n return { success: true, chunkId, total: data.total };\n } catch (error) {\n console.error(t('textSplit.generateQuestionsForChunkError', { chunkId }), error);\n errorCount++;\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, chunkId, error: error.message };\n }\n };\n\n // 并行处理所有文本块,使用任务设置中的并发限制\n await processInParallel(chunkIds, processChunk, taskSettings?.concurrencyLimit || 2);\n\n // 处理完成后设置结果消息\n if (errorCount > 0) {\n toast.warning(\n t('textSplit.partialSuccess', {\n successCount,\n total: chunkIds.length,\n errorCount\n })\n );\n } else {\n toast.success(\n t('textSplit.allSuccess', {\n successCount,\n totalQuestions\n })\n );\n }\n }\n\n // 刷新文本块列表\n if (fetchChunks) {\n fetchChunks();\n }\n } catch (error) {\n toast.error(error.message);\n } finally {\n setProcessing(false);\n // 重置进度状态\n resetProgress();\n }\n },\n [projectId, t, resetProgress, taskSettings]\n );\n\n return {\n processing,\n progress,\n setProgress,\n setProcessing,\n handleGenerateQuestions,\n resetProgress\n };\n}\n"], ["/easy-dataset/lib/db/questions.js", "'use server';\nimport { db } from '@/lib/db/index';\n\n/**\n * 获取项目的所有问题\n * @param {string} projectId - 项目ID\n * @param {number} page - 页码\n * @param {number} pageSize - 每页大小\n * @param answered\n * @param input\n * @returns {Promise<{data: Array, total: number}>} - 问题列表和总条数\n */\nexport async function getQuestions(projectId, page = 1, pageSize = 10, answered, input) {\n try {\n const whereClause = {\n projectId,\n ...(answered !== undefined && { answered: answered }), // 确保 answered 是布尔值\n OR: [{ question: { contains: input } }, { label: { contains: input } }]\n };\n\n const [data, total] = await Promise.all([\n db.questions.findMany({\n where: whereClause,\n orderBy: {\n createAt: 'desc'\n },\n include: {\n chunk: {\n select: {\n name: true,\n content: true\n }\n }\n },\n skip: (page - 1) * pageSize,\n take: pageSize\n }),\n db.questions.count({\n where: whereClause\n })\n ]);\n\n // 批量查询 datasetCount\n const datasetCounts = await getDatasetCountsForQuestions(data.map(item => item.id));\n\n // 合并 datasetCount 到问题项中\n const questionsWithDatasetCount = data.map((item, index) => ({\n ...item,\n datasetCount: datasetCounts[index]\n }));\n\n return { data: questionsWithDatasetCount, total };\n } catch (error) {\n console.error('Failed to get questions by projectId in database');\n throw error;\n }\n}\n\n/**\n * 获取项目的所有问题(仅ID和标签),用于树形视图\n * @param {string} projectId - 项目ID\n * @param {string} input - 搜索关键词\n * @param {boolean} isDistill - 是否只查询蒸馏问题\n * @returns {Promise} - 问题列表(仅包含ID和标签)\n */\nexport async function getQuestionsForTree(projectId, input, isDistill = false) {\n try {\n console.log('[getQuestionsForTree] 参数:', { projectId, input, isDistill });\n\n // 如果是蒸馏问题,需要先获取蒸馏文本块\n let whereClause = {\n projectId,\n question: { contains: input || '' }\n };\n\n if (isDistill) {\n // 获取蒸馏文本块\n const distillChunk = await db.chunks.findFirst({\n where: {\n projectId,\n name: 'Distilled Content'\n }\n });\n\n if (distillChunk) {\n whereClause.chunkId = distillChunk.id;\n }\n }\n\n const data = await db.questions.findMany({\n where: whereClause,\n select: {\n id: true,\n label: true,\n answered: true\n },\n orderBy: {\n createAt: 'desc'\n }\n });\n\n return data;\n } catch (error) {\n console.error('获取树形视图问题失败:', error);\n throw error;\n }\n}\n\n/**\n * 根据标签获取项目的问题\n * @param {string} projectId - 项目ID\n * @param {string} tag - 标签名称\n * @param {string} input - 搜索关键词\n * @param {boolean} isDistill - 是否只查询蒸馏问题\n * @returns {Promise} - 问题列表\n */\nexport async function getQuestionsByTag(projectId, tag, input, isDistill = false) {\n try {\n const whereClause = {\n projectId\n };\n\n if (input) {\n whereClause.question = { contains: input };\n }\n\n if (tag === 'uncategorized') {\n whereClause.label = {\n in: [tag, '其他', 'Other', 'other']\n };\n } else {\n whereClause.label = { in: [tag] };\n }\n\n // 如果是蒸馏问题,需要先获取蒸馏文本块\n if (isDistill) {\n // 获取蒸馏文本块\n const distillChunk = await db.chunks.findFirst({\n where: {\n projectId,\n name: 'Distilled Content'\n }\n });\n\n if (distillChunk) {\n whereClause.chunkId = distillChunk.id;\n }\n }\n\n const data = await db.questions.findMany({\n where: whereClause,\n include: {\n chunk: {\n select: {\n name: true,\n content: true\n }\n }\n },\n orderBy: {\n createAt: 'desc'\n }\n });\n\n // 批量查询 datasetCount\n const datasetCounts = await getDatasetCountsForQuestions(data.map(item => item.id));\n\n // 合并 datasetCount 到问题项中\n const questionsWithDatasetCount = data.map((item, index) => ({\n ...item,\n datasetCount: datasetCounts[index]\n }));\n\n return questionsWithDatasetCount;\n } catch (error) {\n console.error(`根据标签获取问题失败 (${tag}):`, error);\n throw error;\n }\n}\n\nexport async function getAllQuestionsByProjectId(projectId) {\n try {\n return await db.questions.findMany({\n where: { projectId },\n include: {\n chunk: {\n select: {\n name: true,\n content: true\n }\n }\n },\n orderBy: {\n createAt: 'desc'\n }\n });\n } catch (error) {\n console.error('Failed to get datasets ids in database');\n throw error;\n }\n}\n\nexport async function getQuestionsIds(projectId, answered, input) {\n try {\n const whereClause = {\n projectId,\n ...(answered !== undefined && { answered: answered }), // 确保 answered 是布尔值\n OR: [{ question: { contains: input } }, { label: { contains: input } }]\n };\n return await db.questions.findMany({\n where: whereClause,\n select: {\n id: true\n },\n orderBy: {\n createAt: 'desc'\n }\n });\n } catch (error) {\n console.error('Failed to get datasets ids in database');\n throw error;\n }\n}\n\nexport async function getQuestionsByTagName(projectId, tagName) {\n try {\n return await db.questions.findMany({\n where: {\n projectId,\n label: tagName\n },\n include: {\n chunk: {\n select: {\n name: true\n }\n }\n },\n orderBy: {\n createAt: 'desc'\n }\n });\n } catch (error) {\n console.error('Failed to get datasets ids in database');\n throw error;\n }\n}\n\n/**\n * 批量获取问题的 datasetCount\n * @param {Array} questionIds - 问题ID列表\n * @returns {Promise>} - 每个问题的 datasetCount 列表\n */\nasync function getDatasetCountsForQuestions(questionIds) {\n const datasetCounts = await db.datasets.groupBy({\n by: ['questionId'],\n _count: {\n questionId: true\n },\n where: {\n questionId: {\n in: questionIds\n }\n }\n });\n\n // 将结果转换为 questionId 到 datasetCount 的映射\n const datasetCountMap = datasetCounts.reduce((map, item) => {\n map[item.questionId] = item._count.questionId;\n return map;\n }, {});\n\n // 返回与 questionIds 顺序对应的 datasetCount 列表\n return questionIds.map(id => datasetCountMap[id] || 0);\n}\n\nexport async function getQuestionById(id) {\n try {\n return await db.questions.findUnique({\n where: { id }\n });\n } catch (error) {\n console.error('Failed to get questions by name in database');\n throw error;\n }\n}\n\nexport async function isExistByQuestion(question) {\n try {\n const count = await db.questions.count({\n where: { question }\n });\n return count > 0;\n } catch (error) {\n console.error('Failed to get questions by name in database');\n throw error;\n }\n}\n\nexport async function getQuestionsCount(projectId) {\n try {\n return await db.questions.count({\n where: {\n projectId\n }\n });\n } catch (error) {\n console.error('Failed to get questions count in database');\n throw error;\n }\n}\n\n/**\n * 保存项目的问题列表\n * @param {string} projectId - 项目ID\n * @param {Array} questions - 问题列表\n * @param chunkId\n * @returns {Promise} - 保存后的问题列表\n */\nexport async function saveQuestions(projectId, questions, chunkId) {\n try {\n let data = questions.map(item => {\n return {\n projectId,\n chunkId: chunkId ? chunkId : item.chunkId,\n question: item.question,\n label: item.label\n };\n });\n return await db.questions.createMany({ data: data });\n } catch (error) {\n console.error('Failed to create questions in database');\n throw error;\n }\n}\n\nexport async function updateQuestion(question) {\n try {\n return await db.questions.update({ where: { id: question.id }, data: question });\n } catch (error) {\n console.error('Failed to update questions in database');\n throw error;\n }\n}\n\n/**\n * 保存项目的问题列表(支持GA配对)\n * @param {string} projectId - 项目ID\n * @param {Array} questions - 问题列表\n * @param {string} chunkId - 文本块ID\n * @param {string} gaPairId - GA配对ID(可选)\n * @returns {Promise} - 保存后的问题列表\n */\nexport async function saveQuestionsWithGaPair(projectId, questions, chunkId, gaPairId = null) {\n try {\n let data = questions.map(item => {\n return {\n projectId,\n chunkId: chunkId ? chunkId : item.chunkId,\n question: item.question,\n label: item.label,\n gaPairId: gaPairId // 添加GA配对ID\n };\n });\n return await db.questions.createMany({ data: data });\n } catch (error) {\n console.error('Failed to create questions with GA pair in database');\n throw error;\n }\n}\n\n/**\n * 获取指定文本块的问题\n * @param {string} projectId - 项目ID\n * @param {string} chunkId - 文本块ID\n * @returns {Promise} - 问题列表\n */\nexport async function getQuestionsForChunk(projectId, chunkId) {\n return await db.questions.findMany({ where: { projectId, chunkId } });\n}\n\n/**\n * 删除单个问题\n * @param {string} questionId - 问题ID\n */\nexport async function deleteQuestion(questionId) {\n try {\n console.log(questionId);\n return await db.questions.delete({\n where: {\n id: questionId\n }\n });\n } catch (error) {\n console.error('Failed to delete questions by id in database');\n throw error;\n }\n}\n\n/**\n * 批量删除问题\n * @param {Array} questionIds\n */\nexport async function batchDeleteQuestions(questionIds) {\n try {\n return await db.questions.deleteMany({\n where: {\n id: {\n in: questionIds\n }\n }\n });\n } catch (error) {\n console.error('Failed to delete batch questions in database');\n throw error;\n }\n}\n"], ["/easy-dataset/electron/modules/server.js", "const http = require('http');\nconst path = require('path');\nconst fs = require('fs');\nconst { dialog } = require('electron');\n\n/**\n * 检查端口是否被占用\n * @param {number} port 端口号\n * @returns {Promise} 端口是否被占用\n */\nfunction checkPort(port) {\n return new Promise(resolve => {\n const server = http.createServer();\n server.once('error', () => {\n resolve(true); // 端口被占用\n });\n server.once('listening', () => {\n server.close();\n resolve(false); // 端口未被占用\n });\n server.listen(port);\n });\n}\n\n/**\n * 启动 Next.js 服务\n * @param {number} port 端口号\n * @param {Object} app Electron app 对象\n * @returns {Promise} 服务URL\n */\nasync function startNextServer(port, app) {\n console.log(`Easy Dataset 客户端启动中,当前版本: ${require('../util').getAppVersion()}`);\n\n // 设置日志文件路径\n const logDir = path.join(app.getPath('userData'), 'logs');\n if (!fs.existsSync(logDir)) {\n fs.mkdirSync(logDir, { recursive: true });\n }\n const logFile = path.join(logDir, `nextjs-${new Date().toISOString().replace(/:/g, '-')}.log`);\n const logStream = fs.createWriteStream(logFile, { flags: 'a' });\n\n // 重定向 console.log 和 console.error\n const originalConsoleLog = console.log;\n const originalConsoleError = console.error;\n\n console.log = function () {\n const args = Array.from(arguments);\n const logMessage = args.map(arg => (typeof arg === 'object' ? JSON.stringify(arg, null, 2) : arg)).join(' ');\n\n logStream.write(`[${new Date().toISOString()}] [LOG] ${logMessage}\\n`);\n originalConsoleLog.apply(console, args);\n };\n\n console.error = function () {\n const args = Array.from(arguments);\n const logMessage = args.map(arg => (typeof arg === 'object' ? JSON.stringify(arg, null, 2) : arg)).join(' ');\n\n logStream.write(`[${new Date().toISOString()}] [ERROR] ${logMessage}\\n`);\n originalConsoleError.apply(console, args);\n };\n\n // 检查端口是否被占用\n const isPortBusy = await checkPort(port);\n if (isPortBusy) {\n console.log(`端口 ${port} 已被占用,尝试直接连接...`);\n return `http://localhost:${port}`;\n }\n\n console.log(`启动 Next.js 服务,端口: ${port}`);\n\n try {\n // 动态导入 Next.js\n const next = require('next');\n const nextApp = next({\n dev: false,\n dir: path.join(__dirname, '../..'),\n conf: {\n // 配置 Next.js 的日志输出\n onInfo: info => {\n console.log(`[Next.js Info] ${info}`);\n },\n onError: error => {\n console.error(`[Next.js Error] ${error}`);\n },\n onWarn: warn => {\n console.log(`[Next.js Warning] ${warn}`);\n }\n }\n });\n const handle = nextApp.getRequestHandler();\n\n await nextApp.prepare();\n\n const server = http.createServer((req, res) => {\n // 记录请求日志\n console.log(`[Request] ${req.method} ${req.url}`);\n handle(req, res);\n });\n\n return new Promise(resolve => {\n server.listen(port, err => {\n if (err) throw err;\n console.log(`服务已启动,正在打开应用...`);\n resolve(`http://localhost:${port}`);\n });\n });\n } catch (error) {\n console.error('启动服务失败:', error);\n dialog.showErrorBox('启动失败', `无法启动 Next.js 服务: ${error.message}`);\n app.quit();\n return '';\n }\n}\n\nmodule.exports = {\n checkPort,\n startNextServer\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/app/api/projects/[projectId]/batch-generateGA/route.js", "import { NextResponse } from 'next/server';\nimport { batchGenerateGaPairs } from '@/lib/services/ga/ga-pairs';\nimport { getUploadFileInfoById } from '@/lib/db/upload-files'; // 导入单个文件查询函数\n\n/**\n * 批量生成多个文件的 GA 对\n */\nexport async function POST(request, { params }) {\n try {\n const { projectId } = params;\n const body = await request.json();\n\n if (!projectId) {\n return NextResponse.json({ error: 'Project ID is required' }, { status: 400 });\n }\n\n const { fileIds, modelConfigId, language = '中文', appendMode = false } = body;\n\n if (!fileIds || !Array.isArray(fileIds) || fileIds.length === 0) {\n return NextResponse.json({ error: 'File IDs array is required' }, { status: 400 });\n }\n\n if (!modelConfigId) {\n return NextResponse.json({ error: 'Model configuration ID is required' }, { status: 400 });\n }\n\n console.log('开始处理批量生成GA对请求');\n console.log('项目ID:', projectId);\n console.log('请求的文件IDs:', fileIds);\n\n // 使用 getUploadFileInfoById 逐个验证文件\n const validFiles = [];\n const invalidFileIds = [];\n\n for (const fileId of fileIds) {\n try {\n console.log(`正在验证文件: ${fileId}`);\n const fileInfo = await getUploadFileInfoById(fileId);\n\n if (fileInfo && fileInfo.projectId === projectId) {\n console.log(`文件验证成功: ${fileInfo.fileName}`);\n validFiles.push(fileInfo);\n } else if (fileInfo) {\n console.log(`文件属于其他项目: ${fileInfo.projectId} != ${projectId}`);\n invalidFileIds.push(fileId);\n } else {\n console.log(`文件不存在: ${fileId}`);\n invalidFileIds.push(fileId);\n }\n } catch (error) {\n console.error(`验证文件 ${fileId} 时出错:`, String(error));\n invalidFileIds.push(fileId);\n }\n }\n\n console.log(`文件验证完成: 有效${validFiles.length}个, 无效${invalidFileIds.length}个`);\n\n if (validFiles.length === 0) {\n return NextResponse.json(\n {\n error: 'No valid files found',\n debug: {\n projectId,\n requestedIds: fileIds,\n invalidIds: invalidFileIds,\n message: 'None of the requested files belong to this project or exist in the database'\n }\n },\n { status: 404 }\n );\n }\n\n // 批量生成 GA 对\n console.log('开始批量生成GA对...');\n console.log('追加模式:', appendMode);\n const results = await batchGenerateGaPairs(\n projectId,\n validFiles,\n modelConfigId,\n language,\n appendMode // 传递追加模式参数\n );\n\n // 统计结果\n const successCount = results.filter(r => r.success).length;\n const failureCount = results.filter(r => !r.success).length;\n\n console.log(`批量生成完成: 成功${successCount}个, 失败${failureCount}个`);\n\n return NextResponse.json({\n success: true,\n data: results,\n summary: {\n total: results.length,\n success: successCount,\n failure: failureCount,\n processed: validFiles.length,\n skipped: invalidFileIds.length\n },\n message: `Generated GA pairs for ${successCount} files, ${failureCount} failed, ${invalidFileIds.length} files not found`\n });\n } catch (error) {\n console.error('Error batch generating GA pairs:', String(error));\n return NextResponse.json({ error: String(error) || 'Failed to batch generate GA pairs' }, { status: 500 });\n }\n}\n"], ["/easy-dataset/app/api/projects/[projectId]/datasets/route.js", "import { NextResponse } from 'next/server';\nimport {\n deleteDataset,\n getDatasetsByPagination,\n getDatasetsIds,\n getDatasetsById,\n updateDataset\n} from '@/lib/db/datasets';\nimport datasetService from '@/lib/services/datasets';\n\n// 优化思维链函数已移至服务层\n\n/**\n * 生成数据集(为单个问题生成答案)\n */\nexport async function POST(request, { params }) {\n try {\n const { projectId } = params;\n const { questionId, model, language } = await request.json();\n\n // 使用数据集生成服务\n const result = await datasetService.generateDatasetForQuestion(projectId, questionId, {\n model,\n language\n });\n\n return NextResponse.json(result);\n } catch (error) {\n console.error('Failed to generate dataset:', String(error));\n return NextResponse.json(\n {\n error: error.message || 'Failed to generate dataset'\n },\n { status: 500 }\n );\n }\n}\n\n/**\n * 获取项目的所有数据集\n */\nexport async function GET(request, { params }) {\n try {\n const { projectId } = params;\n const { searchParams } = new URL(request.url);\n // 验证项目ID\n if (!projectId) {\n return NextResponse.json({ error: '项目ID不能为空' }, { status: 400 });\n }\n let status = searchParams.get('status');\n let confirmed = undefined;\n if (status === 'confirmed') confirmed = true;\n if (status === 'unconfirmed') confirmed = false;\n\n let selectedAll = searchParams.get('selectedAll');\n // 获取搜索字段参数\n const field = searchParams.get('field') || 'question';\n // 获取思维链筛选参数\n const hasCot = searchParams.get('hasCot') || 'all';\n if (selectedAll) {\n let data = await getDatasetsIds(projectId, confirmed, searchParams.get('input'), field, hasCot);\n return NextResponse.json(data);\n }\n\n // 获取数据集\n const datasets = await getDatasetsByPagination(\n projectId,\n parseInt(searchParams.get('page')),\n parseInt(searchParams.get('size')),\n confirmed,\n searchParams.get('input'),\n field, // 传递搜索字段参数\n hasCot // 传递思维链筛选参数\n );\n\n return NextResponse.json(datasets);\n } catch (error) {\n console.error('获取数据集失败:', String(error));\n return NextResponse.json(\n {\n error: error.message || '获取数据集失败'\n },\n { status: 500 }\n );\n }\n}\n\n/**\n * 删除数据集\n */\nexport async function DELETE(request) {\n try {\n const { searchParams } = new URL(request.url);\n const datasetId = searchParams.get('id');\n if (!datasetId) {\n return NextResponse.json(\n {\n error: 'Dataset ID cannot be empty'\n },\n { status: 400 }\n );\n }\n\n await deleteDataset(datasetId);\n\n return NextResponse.json({\n success: true,\n message: 'Dataset deleted successfully'\n });\n } catch (error) {\n console.error('Failed to delete dataset:', error);\n return NextResponse.json(\n {\n error: error.message || 'Failed to delete dataset'\n },\n { status: 500 }\n );\n }\n}\n\n/**\n * 编辑数据集\n */\nexport async function PATCH(request) {\n try {\n const { searchParams } = new URL(request.url);\n const datasetId = searchParams.get('id');\n const { answer, cot, confirmed } = await request.json();\n if (!datasetId) {\n return NextResponse.json(\n {\n error: 'Dataset ID cannot be empty'\n },\n { status: 400 }\n );\n }\n // 获取所有数据集\n let dataset = await getDatasetsById(datasetId);\n if (!dataset) {\n return NextResponse.json(\n {\n error: 'Dataset does not exist'\n },\n { status: 404 }\n );\n }\n let data = { id: datasetId };\n if (confirmed) data.confirmed = confirmed;\n if (answer) data.answer = answer;\n if (cot) data.cot = cot;\n\n // 保存更新后的数据集列表\n await updateDataset(data);\n\n return NextResponse.json({\n success: true,\n message: 'Dataset updated successfully',\n dataset: dataset\n });\n } catch (error) {\n console.error('Failed to update dataset:', String(error));\n return NextResponse.json(\n {\n error: error.message || 'Failed to update dataset'\n },\n { status: 500 }\n );\n }\n}\n"], ["/easy-dataset/app/api/check-update/route.js", "import { NextResponse } from 'next/server';\nimport path from 'path';\nimport fs from 'fs';\n\n// 获取当前版本\nfunction getCurrentVersion() {\n try {\n const packageJsonPath = path.join(process.cwd(), 'package.json');\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));\n return packageJson.version;\n } catch (error) {\n console.error('读取版本信息失败:', String(error));\n return '1.0.0';\n }\n}\n\n// 从 GitHub 获取最新版本\nasync function getLatestVersion() {\n try {\n const owner = 'ConardLi';\n const repo = 'easy-dataset';\n const response = await fetch(`https://api.github.com/repos/${owner}/${repo}/releases/latest`);\n\n if (!response.ok) {\n throw new Error(`GitHub API 请求失败: ${response.status}`);\n }\n\n const data = await response.json();\n return data.tag_name.replace('v', '');\n } catch (error) {\n console.error('获取最新版本失败:', String(error));\n return null;\n }\n}\n\n// 检查是否有更新\nexport async function GET() {\n try {\n const currentVersion = getCurrentVersion();\n const latestVersion = await getLatestVersion();\n\n if (!latestVersion) {\n return NextResponse.json({\n hasUpdate: false,\n currentVersion,\n latestVersion: null,\n error: '获取最新版本失败'\n });\n }\n\n // 简单的版本比较\n const hasUpdate = compareVersions(latestVersion, currentVersion) > 0;\n\n return NextResponse.json({\n hasUpdate,\n currentVersion,\n latestVersion,\n releaseUrl: hasUpdate ? `https://github.com/ConardLi/easy-dataset/releases/tag/v${latestVersion}` : null\n });\n } catch (error) {\n console.error('检查更新失败:', String(error));\n }\n}\n\n// 简单的版本比较函数\nfunction compareVersions(a, b) {\n const partsA = a.split('.').map(Number);\n const partsB = b.split('.').map(Number);\n\n for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) {\n const numA = i < partsA.length ? partsA[i] : 0;\n const numB = i < partsB.length ? partsB[i] : 0;\n\n if (numA > numB) return 1;\n if (numA < numB) return -1;\n }\n\n return 0;\n}\n"], ["/easy-dataset/components/text-split/ChunkListHeader.js", "'use client';\n\nimport { Box, Typography, Checkbox, Button, Select, MenuItem, Tooltip, Menu, IconButton } from '@mui/material';\nimport QuizIcon from '@mui/icons-material/Quiz';\nimport DownloadIcon from '@mui/icons-material/Download';\nimport AutoFixHighIcon from '@mui/icons-material/AutoFixHigh';\nimport MoreVertIcon from '@mui/icons-material/MoreVert';\nimport EditIcon from '@mui/icons-material/Edit';\nimport axios from 'axios';\nimport { toast } from 'sonner';\nimport { useTranslation } from 'react-i18next';\nimport { useState } from 'react';\n\nexport default function ChunkListHeader({\n projectId,\n totalChunks,\n selectedChunks,\n onSelectAll,\n onBatchGenerateQuestions,\n onBatchEditChunks,\n questionFilter,\n setQuestionFilter,\n chunks = [], // 添加chunks参数,用于导出文本块\n selectedModel = {}\n}) {\n const { t, i18n } = useTranslation();\n\n // 添加更多菜单的状态和锚点\n const [moreMenuAnchorEl, setMoreMenuAnchorEl] = useState(null);\n const isMoreMenuOpen = Boolean(moreMenuAnchorEl);\n\n // 打开更多菜单\n const handleMoreMenuClick = event => {\n setMoreMenuAnchorEl(event.currentTarget);\n };\n\n // 关闭更多菜单\n const handleMoreMenuClose = () => {\n setMoreMenuAnchorEl(null);\n };\n\n // 处理批量编辑,关闭菜单并调用原有函数\n const handleBatchEdit = () => {\n handleMoreMenuClose();\n onBatchEditChunks();\n };\n\n // 处理导出文本块,关闭菜单并调用原有函数\n const handleExport = () => {\n handleMoreMenuClose();\n handleExportChunks();\n };\n\n // 创建自动提取问题任务\n const handleCreateAutoQuestionTask = async () => {\n if (!projectId || !selectedModel?.id) {\n toast.error(t('textSplit.selectModelFirst', { defaultValue: '请先选择模型' }));\n return;\n }\n\n try {\n // 调用创建任务接口\n const response = await axios.post(`/api/projects/${projectId}/tasks`, {\n taskType: 'question-generation',\n modelInfo: selectedModel,\n language: i18n.language,\n detail: '批量生成问题任务'\n });\n\n if (response.data?.code === 0) {\n toast.success(t('tasks.createSuccess', { defaultValue: '后台任务已创建,系统将自动处理未生成问题的文本块' }));\n } else {\n toast.error(t('tasks.createFailed', { defaultValue: '创建任务失败' }) + ': ' + response.data?.message);\n }\n } catch (error) {\n console.error('创建自动提取问题任务失败:', error);\n toast.error(t('tasks.createFailed', { defaultValue: '创建任务失败' }) + ': ' + error.message);\n }\n };\n\n // 导出文本块为JSON文件的函数\n const handleExportChunks = () => {\n if (!chunks || chunks.length === 0) return;\n\n // 创建要导出的数据对象\n const exportData = chunks.map(chunk => ({\n name: chunk.name,\n projectId: chunk.projectId,\n fileName: chunk.fileName,\n content: chunk.content,\n summary: chunk.summary,\n size: chunk.size\n }));\n\n // 将数据转换为JSON字符串\n const jsonString = JSON.stringify(exportData, null, 2);\n\n // 创建Blob对象\n const blob = new Blob([jsonString], { type: 'application/json' });\n\n // 创建下载链接\n const url = URL.createObjectURL(blob);\n const a = document.createElement('a');\n a.href = url;\n a.download = `text-chunks-export-${new Date().toISOString().split('T')[0]}.json`;\n\n // 触发下载\n document.body.appendChild(a);\n a.click();\n\n // 清理\n document.body.removeChild(a);\n URL.revokeObjectURL(url);\n };\n\n return (\n \n \n 0 && selectedChunks.length < totalChunks}\n onChange={onSelectAll}\n />\n \n {t('textSplit.selectedCount', { count: selectedChunks.length })} ,\n {t('textSplit.totalCount', { count: totalChunks })}\n \n \n\n \n \n\n \n }\n disabled={selectedChunks.length === 0}\n onClick={onBatchGenerateQuestions}\n size=\"medium\"\n sx={{ minWidth: { xs: '48%', sm: 'auto' } }}\n >\n {t('textSplit.batchGenerateQuestions')}\n \n\n \n }\n onClick={() => handleCreateAutoQuestionTask()}\n disabled={!projectId || !selectedModel?.id}\n size=\"medium\"\n sx={{ minWidth: { xs: '48%', sm: 'auto' } }}\n >\n {t('textSplit.autoGenerateQuestions')}\n \n \n\n {/* 更多菜单按钮 */}\n \n \n \n \n \n\n {/* 更多操作下拉菜单 */}\n \n \n \n {t('batchEdit.batchEdit', { defaultValue: '批量编辑' })}\n \n \n \n {t('textSplit.exportChunks', { defaultValue: '导出文本块' })}\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/questions/QuestionListView.js", "'use client';\n\nimport { useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport {\n Box,\n Typography,\n Checkbox,\n IconButton,\n Chip,\n Tooltip,\n Pagination,\n Divider,\n Paper,\n CircularProgress,\n Button,\n TextField\n} from '@mui/material';\nimport DeleteIcon from '@mui/icons-material/Delete';\nimport AutoFixHighIcon from '@mui/icons-material/AutoFixHigh';\nimport EditIcon from '@mui/icons-material/Edit';\nimport { useGenerateDataset } from '@/hooks/useGenerateDataset';\n\nexport default function QuestionListView({\n questions = [],\n currentPage,\n totalQuestions = 0,\n handlePageChange,\n selectedQuestions = [],\n onSelectQuestion,\n onDeleteQuestion,\n projectId,\n onEditQuestion,\n refreshQuestions\n}) {\n const { t } = useTranslation();\n // 处理状态\n const [processingQuestions, setProcessingQuestions] = useState({});\n const { generateSingleDataset } = useGenerateDataset();\n\n // 获取文本块的标题\n const getChunkTitle = content => {\n const firstLine = content.split('\\n')[0].trim();\n if (firstLine.startsWith('# ')) {\n return firstLine.substring(2);\n } else if (firstLine.length > 0) {\n return firstLine.length > 200 ? firstLine.substring(0, 200) + '...' : firstLine;\n }\n return t('chunks.defaultTitle');\n };\n\n // 检查问题是否被选中\n const isQuestionSelected = questionId => {\n return selectedQuestions.includes(questionId);\n };\n\n // 处理生成数据集\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 refreshQuestions();\n };\n\n return (\n \n {/* 问题列表 */}\n \n \n \n {t('datasets.question')}\n \n \n \n {t('common.label')}\n \n \n {t('chunks.title')}\n \n \n {t('common.actions')}\n \n \n \n\n \n\n {questions.map((question, index) => {\n const isSelected = isQuestionSelected(question.id);\n const questionKey = question.id;\n return (\n \n \n {\n onSelectQuestion(questionKey);\n }}\n size=\"small\"\n />\n\n \n \n {question.question}\n {question.datasetCount > 0 ? (\n \n ) : null}\n \n \n {question.label || t('datasets.noTag')} • ID: {(question.question || '').substring(0, 8)}\n \n \n\n \n {question.label ? (\n \n ) : (\n \n {t('datasets.noTag')}\n \n )}\n \n\n \n \n \n \n \n\n \n \n \n onEditQuestion({\n id: question.id,\n question: question.question,\n chunkId: question.chunkId,\n label: question.label || 'other'\n })\n }\n disabled={processingQuestions[questionKey]}\n >\n \n \n \n \n handleGenerateDataset(question.id, question.question)}\n disabled={processingQuestions[questionKey]}\n >\n {processingQuestions[questionKey] ? (\n \n ) : (\n \n )}\n \n \n \n onDeleteQuestion(question.id)}\n disabled={processingQuestions[questionKey]}\n >\n \n \n \n \n \n {index < questions.length - 1 && }\n \n );\n })}\n \n\n {/* 分页 */}\n {totalQuestions > 1 && (\n \n \n \n {t('common.jumpTo')}:\n {\n if (e.key === 'Enter') {\n const pageNum = parseInt(e.target.value, 10);\n if (pageNum >= 1 && pageNum <= totalQuestions) {\n handlePageChange(null, pageNum);\n e.target.value = '';\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/playground/ChatArea.js", "'use client';\n\nimport React, { useRef, useEffect } from 'react';\nimport { Box, Typography, Paper, Grid, CircularProgress } from '@mui/material';\nimport { useTheme } from '@mui/material/styles';\nimport ChatMessage from './ChatMessage';\nimport { playgroundStyles } from '@/styles/playground';\nimport { useTranslation } from 'react-i18next';\n\nconst ChatArea = ({ selectedModels, conversations, loading, getModelName }) => {\n const theme = useTheme();\n const styles = playgroundStyles(theme);\n const { t } = useTranslation();\n\n // 为每个模型创建独立的引用\n const chatContainerRefs = {\n model1: useRef(null),\n model2: useRef(null),\n model3: useRef(null)\n };\n\n // 为每个模型的聊天容器自动滚动到底部\n useEffect(() => {\n Object.values(chatContainerRefs).forEach(ref => {\n if (ref.current) {\n ref.current.scrollTop = ref.current.scrollHeight;\n }\n });\n }, [conversations]);\n\n if (selectedModels.length === 0) {\n return (\n \n {t('playground.selectModelFirst')}\n \n );\n }\n\n return (\n \n {selectedModels.map((modelId, index) => {\n const modelConversation = conversations[modelId] || [];\n const isLoading = loading[modelId];\n const refKey = `model${index + 1}`;\n\n return (\n 1 ? 12 / selectedModels.length : 12}\n key={modelId}\n style={{ maxHeight: 'calc(100vh - 300px)' }}\n >\n \n \n {getModelName(modelId)}\n {isLoading && }\n \n\n \n {modelConversation.length === 0 ? (\n \n \n {t('playground.sendFirstMessage')}\n \n \n ) : (\n modelConversation.map((message, msgIndex) => (\n \n \n \n ))\n )}\n \n \n \n );\n })}\n \n );\n};\n\nexport default ChatArea;\n"], ["/easy-dataset/app/api/projects/[projectId]/datasets/[datasetId]/token-count/route.js", "import { NextResponse } from 'next/server';\nimport { getDatasetsById } from '@/lib/db/datasets';\nimport { getEncoding } from '@langchain/core/utils/tiktoken';\n\n/**\n * 异步计算数据集文本的Token数量\n */\nexport async function GET(request, { params }) {\n try {\n const { projectId, datasetId } = params;\n\n if (!datasetId) {\n return NextResponse.json({ error: '数据集ID不能为空' }, { status: 400 });\n }\n\n const datasets = await getDatasetsById(datasetId);\n const tokenCounts = {\n answerTokens: 0,\n cotTokens: 0\n };\n\n try {\n if (datasets.answer || datasets.cot) {\n // 使用 cl100k_base 编码,适用于 gpt-3.5-turbo 和 gpt-4\n const encoding = await getEncoding('cl100k_base');\n\n if (datasets.answer) {\n const tokens = encoding.encode(datasets.answer);\n tokenCounts.answerTokens = tokens.length;\n }\n\n if (datasets.cot) {\n const tokens = encoding.encode(datasets.cot);\n tokenCounts.cotTokens = tokens.length;\n }\n }\n } catch (error) {\n console.error('计算Token数量失败:', String(error));\n return NextResponse.json({ error: '计算Token数量失败' }, { status: 500 });\n }\n\n return NextResponse.json(tokenCounts);\n } catch (error) {\n console.error('获取Token计数失败:', String(error));\n return NextResponse.json(\n {\n error: error.message || '获取Token计数失败'\n },\n { status: 500 }\n );\n }\n}\n"], ["/easy-dataset/electron/modules/window-manager.js", "const { BrowserWindow, shell } = require('electron');\nconst path = require('path');\nconst url = require('url');\nconst { getAppVersion } = require('../util');\n\nlet mainWindow;\n\n/**\n * 创建主窗口\n * @param {boolean} isDev 是否为开发环境\n * @param {number} port 服务端口\n * @returns {BrowserWindow} 创建的主窗口\n */\nfunction createWindow(isDev, port) {\n mainWindow = new BrowserWindow({\n width: 1200,\n height: 800,\n show: false,\n frame: true,\n webPreferences: {\n nodeIntegration: false,\n contextIsolation: true,\n preload: path.join(__dirname, '..', 'preload.js')\n },\n icon: path.join(__dirname, '../../public/imgs/logo.ico')\n });\n\n // 设置窗口标题\n mainWindow.setTitle(`Easy Dataset v${getAppVersion()}`);\n const loadingPath = url.format({\n pathname: path.join(__dirname, '..', 'loading.html'),\n protocol: 'file:',\n slashes: true\n });\n\n // 加载 loading 页面时使用专门的 preload 脚本\n mainWindow.webContents.on('did-finish-load', () => {\n mainWindow.show();\n });\n\n mainWindow.loadURL(loadingPath);\n\n // 处理窗口导航事件,将外部链接在浏览器中打开\n mainWindow.webContents.on('will-navigate', (event, navigationUrl) => {\n // 解析当前 URL 和导航 URL\n const parsedUrl = new URL(navigationUrl);\n const currentHostname = isDev ? 'localhost' : 'localhost';\n const currentPort = port.toString();\n\n // 检查是否是外部链接\n if (parsedUrl.hostname !== currentHostname || (parsedUrl.port !== currentPort && parsedUrl.port !== '')) {\n event.preventDefault();\n shell.openExternal(navigationUrl);\n }\n });\n\n // 处理新窗口打开请求,将外部链接在浏览器中打开\n mainWindow.webContents.setWindowOpenHandler(({ url: navigationUrl }) => {\n // 解析导航 URL\n const parsedUrl = new URL(navigationUrl);\n const currentHostname = isDev ? 'localhost' : 'localhost';\n const currentPort = port.toString();\n\n // 检查是否是外部链接\n if (parsedUrl.hostname !== currentHostname || (parsedUrl.port !== currentPort && parsedUrl.port !== '')) {\n shell.openExternal(navigationUrl);\n return { action: 'deny' };\n }\n return { action: 'allow' };\n });\n\n mainWindow.on('closed', () => {\n mainWindow = null;\n });\n\n mainWindow.maximize();\n\n return mainWindow;\n}\n\n/**\n * 加载应用URL\n * @param {string} appUrl 应用URL\n */\nfunction loadAppUrl(appUrl) {\n if (mainWindow) {\n mainWindow.loadURL(appUrl);\n }\n}\n\n/**\n * 在开发环境中打开开发者工具\n */\nfunction openDevTools() {\n if (mainWindow) {\n mainWindow.webContents.openDevTools();\n }\n}\n\n/**\n * 获取主窗口\n * @returns {BrowserWindow} 主窗口\n */\nfunction getMainWindow() {\n return mainWindow;\n}\n\nmodule.exports = {\n createWindow,\n loadAppUrl,\n openDevTools,\n getMainWindow\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/lib/llm/prompts/enhancedAnswerEn.js", "/**\n * Enhanced answer generation prompt template - based on GA pairs\n * @param {Object} params - Parameter object\n * @param {string} params.text - Reference text content\n * @param {string} params.question - Question content\n * @param {string} params.language - Language\n * @param {string} params.globalPrompt - Global prompt\n * @param {string} params.answerPrompt - Answer prompt\n * @param {Array} params.gaPairs - GA pairs array containing genre and audience information\n * @param {Object} params.activeGaPair - Currently active GA pair\n */\nexport default function getEnhancedAnswerEnPrompt({\n text,\n question,\n globalPrompt = '',\n answerPrompt = '',\n activeGaPair = null\n}) {\n if (globalPrompt) {\n globalPrompt = `In subsequent tasks, you must strictly follow these rules: ${globalPrompt}`;\n }\n if (answerPrompt) {\n answerPrompt = `In generating answers, you must strictly follow these rules: ${answerPrompt}`;\n }\n\n // Build GA pairs related prompts\n let gaPrompt = '';\n if (activeGaPair && activeGaPair.active) {\n gaPrompt = `\n## Special Requirements - Genre & Audience Adaptation (MGA):\nAdjust your response style and depth according to the following genre and audience combination:\n\n**Current Genre**: ${activeGaPair.genre}\n**Target Audience**: ${activeGaPair.audience}\n\nPlease ensure:\n1. The organization, style, level of detail, and language of the answer should fully comply with the requirements of \"${activeGaPair.genre}\".\n2. The answer should consider the comprehension ability and knowledge background of \"${activeGaPair.audience}\", striving for clarity and ease of understanding.\n3. Word choice and explanation detail match the target audience's knowledge background.\n4. Maintain content accuracy and professionalism while enhancing specificity.\n5. If \"${activeGaPair.genre}\" or \"${activeGaPair.audience}\" suggests the need, the answer can appropriately include explanations, examples, or steps.\n6. The answer should directly address the question, ensuring the logic and coherence of the Q&A. It should not include irrelevant information or citation marks, such as content mentioned in GA pairs, to prevent contaminating the data generation results.\n`;\n } else {\n gaPrompt = '';\n }\n\n return `\n# Role: Fine-tuning Dataset Generation Expert (MGA Enhanced)\n## Profile:\n- Description: You are an expert in generating fine-tuning datasets, skilled at generating accurate answers to questions from the given content, and capable of adjusting response style according to Genre-Audience combinations to ensure accuracy, relevance, and specificity of answers.\n${globalPrompt}\n\n## Skills:\n1. The answer must be based on the given content.\n2. The answer must be accurate and not fabricated.\n3. The answer must be relevant to the question.\n4. The answer must be logical.\n5. Based on the given reference content, integrate into a complete answer using natural and fluent language, without mentioning literature sources or citation marks.\n6. Ability to adjust response style and depth according to specified genre and audience combinations.\n7. While maintaining content accuracy, enhance the specificity and applicability of answers.\n\n${gaPrompt}\n\n## Workflow:\n1. Take a deep breath and work on this problem step-by-step.\n2. First, analyze the given file content and question type.\n3. Then, extract key information from the content.\n4. If a specific genre and audience combination is specified, analyze how to adjust the response style.\n5. Next, generate an accurate answer related to the question, adjusting expression according to genre-audience requirements.\n6. Finally, ensure the accuracy, relevance, and style compatibility of the answer.\n\n## Reference Content:\n${text}\n\n## Question\n${question}\n\n## Constraints:\n1. The answer must be based on the given content.\n2. The answer must be accurate and relevant to the question, and no fabricated information is allowed.\n3. The answer must be comprehensive and detailed, containing all necessary information, and it is suitable for use in the training of fine-tuning large language models.\n4. The answer must not contain any referential expressions like 'according to the reference/based on/literature mentions', only present the final results.\n5. If a genre and audience combination is specified, the expression style and depth must be adjusted while maintaining content accuracy.\n6. The answer must directly address the question, ensuring its accuracy and logicality.\n${answerPrompt}\n`;\n}\n"], ["/easy-dataset/lib/file/file-process/pdf/index.js", "import { defaultProcessing } from './default';\nimport { minerUProcessing } from './mineru';\nimport { visionProcessing } from './vision';\n\n/**\n * PDF处理服务入口\n * @param {string} projectId 项目ID\n * @param {string} fileName 文件名\n * @param {Object} options 处理选项\n * @param {string} strategy 处理策略,可选值: 'default', 'mineru', 'vision'\n * @returns {Promise} 处理结果\n */\nexport async function processPdf(strategy = 'default', projectId, fileName, options = {}) {\n switch (strategy.toLowerCase()) {\n case 'default':\n return await defaultProcessing(projectId, fileName, options);\n case 'mineru':\n return await minerUProcessing(projectId, fileName, options);\n case 'vision':\n return await visionProcessing(projectId, fileName, options);\n default:\n throw new Error(`unsupported PDF processing strategy: ${strategy}`);\n }\n}\n\nexport default {\n processPdf\n};\n\nexport * from './util';\n"], ["/easy-dataset/app/api/projects/[projectId]/generate-questions/route.js", "import { NextResponse } from 'next/server';\nimport { getProjectChunks } from '@/lib/file/text-splitter';\nimport { getTaskConfig } from '@/lib/db/projects';\nimport { getChunkById } from '@/lib/db/chunks';\nimport { generateQuestionsForChunk, generateQuestionsForChunkWithGA } from '@/lib/services/questions';\n\n// 批量生成问题\nexport async function POST(request, { params }) {\n try {\n const { projectId } = params;\n\n // 验证项目ID\n if (!projectId) {\n return NextResponse.json({ error: 'The project ID cannot be empty' }, { status: 400 });\n }\n\n // 获取请求体\n const { model, chunkIds, language = '中文', enableGaExpansion = false } = await request.json();\n\n if (!model) {\n return NextResponse.json({ error: 'The model cannot be empty' }, { status: 400 });\n }\n\n // 如果没有指定文本块ID,则获取所有文本块\n let chunks = [];\n if (!chunkIds || chunkIds.length === 0) {\n const result = await getProjectChunks(projectId);\n chunks = result.chunks || [];\n } else {\n // 获取指定的文本块\n chunks = await Promise.all(\n chunkIds.map(async chunkId => {\n const chunk = await getChunkById(chunkId);\n if (chunk) {\n return {\n id: chunk.id,\n content: chunk.content,\n length: chunk.content.length\n };\n }\n return null;\n })\n );\n chunks = chunks.filter(Boolean); // 过滤掉不存在的文本块\n }\n if (chunks.length === 0) {\n return NextResponse.json({ error: 'No valid text blocks found' }, { status: 404 });\n }\n\n const results = [];\n const errors = [];\n\n // 获取项目 task-config 信息\n const taskConfig = await getTaskConfig(projectId);\n const { questionGenerationLength } = taskConfig;\n for (const chunk of chunks) {\n try {\n // 根据文本长度自动计算问题数量\n const questionNumber = Math.floor(chunk.length / questionGenerationLength);\n\n let result;\n if (enableGaExpansion) {\n // 使用GA增强的问题生成\n result = await generateQuestionsForChunkWithGA(projectId, chunk.id, {\n model,\n language,\n number: questionNumber\n });\n } else {\n // 使用标准问题生成\n result = await generateQuestionsForChunk(projectId, chunk.id, {\n model,\n language,\n number: questionNumber\n });\n }\n\n // 统一处理返回结果格式\n if (result && result.questions && Array.isArray(result.questions)) {\n // GA增强模式的结果格式\n results.push({\n chunkId: chunk.id,\n success: true,\n questions: result.questions,\n total: result.total,\n gaExpansionUsed: result.gaExpansionUsed,\n gaPairsCount: result.gaPairsCount\n });\n } else if (result && result.labelQuestions && Array.isArray(result.labelQuestions)) {\n // 标准模式的结果格式\n results.push({\n chunkId: chunk.id,\n success: true,\n questions: result.labelQuestions,\n total: result.total,\n gaExpansionUsed: false,\n gaPairsCount: 0\n });\n } else {\n errors.push({\n chunkId: chunk.id,\n error: 'Failed to parse questions'\n });\n }\n } catch (error) {\n console.error(`Failed to generate questions for text block ${chunk.id}:`, String(error));\n errors.push({\n chunkId: chunk.id,\n error: error.message || 'Failed to generate questions'\n });\n }\n }\n\n // 返回生成结果\n return NextResponse.json({\n results,\n errors,\n totalSuccess: results.length,\n totalErrors: errors.length,\n totalChunks: chunks.length\n });\n } catch (error) {\n console.error('Failed to generate questions:', String(error));\n return NextResponse.json({ error: error.message || 'Failed to generate questions' }, { status: 500 });\n }\n}\n"], ["/easy-dataset/lib/file/split-markdown/core/summary.js", "/**\n * 摘要生成模块\n */\n\n/**\n * 生成段落增强摘要,包含该段落中的所有标题\n * @param {Object} section - 段落对象\n * @param {Array} outline - 目录大纲\n * @param {number} partIndex - 子段落索引(可选)\n * @param {number} totalParts - 子段落总数(可选)\n * @returns {string} - 生成的增强摘要\n */\nfunction generateEnhancedSummary(section, outline, partIndex = null, totalParts = null) {\n // 如果是文档前言\n if ((!section.heading && section.level === 0) || (!section.headings && !section.heading)) {\n // 获取文档标题(如果存在)\n const docTitle = outline.length > 0 && outline[0].level === 1 ? outline[0].title : '文档';\n return `${docTitle} 前言`;\n }\n\n // 如果有headings数组,使用它\n if (section.headings && section.headings.length > 0) {\n // 按照级别和位置排序标题\n const sortedHeadings = [...section.headings].sort((a, b) => {\n if (a.level !== b.level) return a.level - b.level;\n return a.position - b.position;\n });\n\n // 构建所有标题包含的摘要\n const headingsMap = new Map(); // 用于去重\n\n // 首先处理每个标题,找到其完整路径\n for (const heading of sortedHeadings) {\n // 跳过空标题\n if (!heading.heading) continue;\n\n // 查找当前标题在大纲中的位置\n const headingIndex = outline.findIndex(item => item.title === heading.heading && item.level === heading.level);\n\n if (headingIndex === -1) {\n // 如果在大纲中找不到,直接使用当前标题\n headingsMap.set(heading.heading, heading.heading);\n continue;\n }\n\n // 查找所有上级标题\n const pathParts = [];\n let parentLevel = heading.level - 1;\n\n for (let i = headingIndex - 1; i >= 0 && parentLevel > 0; i--) {\n if (outline[i].level === parentLevel) {\n pathParts.unshift(outline[i].title);\n parentLevel--;\n }\n }\n\n // 添加当前标题\n pathParts.push(heading.heading);\n\n // 生成完整路径并存储到Map中\n const fullPath = pathParts.join(' > ');\n headingsMap.set(fullPath, fullPath);\n }\n\n // 将所有标题路径转换为数组并按间隔符数量排序(表示层级深度)\n const paths = Array.from(headingsMap.values()).sort((a, b) => {\n const aDepth = (a.match(/>/g) || []).length;\n const bDepth = (b.match(/>/g) || []).length;\n return aDepth - bDepth || a.localeCompare(b);\n });\n\n // 如果没有有效的标题,返回默认摘要\n if (paths.length === 0) {\n return section.heading ? section.heading : '未命名段落';\n }\n\n // 如果是单个标题,直接返回\n if (paths.length === 1) {\n let summary = paths[0];\n // 如果是分段的部分,添加Part信息\n if (partIndex !== null && totalParts > 1) {\n summary += ` - Part ${partIndex}/${totalParts}`;\n }\n return summary;\n }\n\n // 如果有多个标题,生成多标题摘要\n let summary = '';\n\n // 尝试找到公共前缀\n const firstPath = paths[0];\n const segments = firstPath.split(' > ');\n\n for (let i = 0; i < segments.length - 1; i++) {\n const prefix = segments.slice(0, i + 1).join(' > ');\n let isCommonPrefix = true;\n\n for (let j = 1; j < paths.length; j++) {\n if (!paths[j].startsWith(prefix + ' > ')) {\n isCommonPrefix = false;\n break;\n }\n }\n\n if (isCommonPrefix) {\n summary = prefix + ' > [';\n // 添加非公共部分\n for (let j = 0; j < paths.length; j++) {\n const uniquePart = paths[j].substring(prefix.length + 3); // +3 为 ' > ' 的长度\n summary += (j > 0 ? ', ' : '') + uniquePart;\n }\n summary += ']';\n break;\n }\n }\n\n // 如果没有公共前缀,使用完整列表\n if (!summary) {\n summary = paths.join(', ');\n }\n\n // 如果是分段的部分,添加Part信息\n if (partIndex !== null && totalParts > 1) {\n summary += ` - Part ${partIndex}/${totalParts}`;\n }\n\n return summary;\n }\n\n // 兼容旧逻辑,当没有headings数组时\n if (!section.heading && section.level === 0) {\n return '文档前言';\n }\n\n // 查找当前段落在大纲中的位置\n const currentHeadingIndex = outline.findIndex(item => item.title === section.heading && item.level === section.level);\n\n if (currentHeadingIndex === -1) {\n return section.heading ? section.heading : '未命名段落';\n }\n\n // 查找所有上级标题\n const parentHeadings = [];\n let parentLevel = section.level - 1;\n\n for (let i = currentHeadingIndex - 1; i >= 0 && parentLevel > 0; i--) {\n if (outline[i].level === parentLevel) {\n parentHeadings.unshift(outline[i].title);\n parentLevel--;\n }\n }\n\n // 构建摘要\n let summary = '';\n\n if (parentHeadings.length > 0) {\n summary = parentHeadings.join(' > ') + ' > ';\n }\n\n summary += section.heading;\n\n // 如果是分段的部分,添加Part信息\n if (partIndex !== null && totalParts > 1) {\n summary += ` - Part ${partIndex}/${totalParts}`;\n }\n\n return summary;\n}\n\n/**\n * 旧的摘要生成函数,保留供兼容性使用\n * @param {Object} section - 段落对象\n * @param {Array} outline - 目录大纲\n * @param {number} partIndex - 子段落索引(可选)\n * @param {number} totalParts - 子段落总数(可选)\n * @returns {string} - 生成的摘要\n */\nfunction generateSummary(section, outline, partIndex = null, totalParts = null) {\n return generateEnhancedSummary(section, outline, partIndex, totalParts);\n}\n\nmodule.exports = {\n generateEnhancedSummary,\n generateSummary\n};\n"], ["/easy-dataset/lib/db/ga-pairs.js", "'use server';\nimport { db } from '@/lib/db/index';\n\n/**\n * 获取文件的所有 GA 对\n * @param {string} fileId - 文件 ID\n * @returns {Promise} GA 对列表\n */\nexport async function getGaPairsByFileId(fileId) {\n try {\n return await db.gaPairs.findMany({\n where: { fileId },\n orderBy: { pairNumber: 'asc' }\n });\n } catch (error) {\n console.error('Failed to get GA pairs by fileId in database:', error);\n throw error;\n }\n}\n\n/**\n * 获取项目的所有 GA 对\n * @param {string} projectId - 项目 ID\n * @returns {Promise} GA 对列表\n */\nexport async function getGaPairsByProjectId(projectId) {\n try {\n return await db.gaPairs.findMany({\n where: { projectId },\n include: {\n uploadFile: {\n select: {\n fileName: true\n }\n }\n },\n orderBy: [{ fileId: 'asc' }, { pairNumber: 'asc' }]\n });\n } catch (error) {\n console.error('Failed to get GA pairs by projectId in database:', error);\n throw error;\n }\n}\n\n/**\n * 创建 GA 对\n * @param {Array} gaPairs - GA 对数据数组\n * @returns {Promise} 创建的 GA 对\n */\nexport async function createGaPairs(gaPairs) {\n try {\n return await db.gaPairs.createManyAndReturn({ data: gaPairs });\n } catch (error) {\n console.error('Failed to create GA pairs in database:', error);\n throw error;\n }\n}\n\n/**\n * 更新单个 GA 对\n * @param {string} id - GA 对 ID\n * @param {Object} data - 更新数据\n * @returns {Promise} 更新后的 GA 对\n */\nexport async function updateGaPair(id, data) {\n try {\n return await db.gaPairs.update({\n where: { id },\n data\n });\n } catch (error) {\n console.error('Failed to update GA pair in database:', error);\n throw error;\n }\n}\n\n/**\n * 删除文件的所有 GA 对\n * @param {string} fileId - 文件 ID\n * @returns {Promise} 删除结果\n */\nexport async function deleteGaPairsByFileId(fileId) {\n try {\n return await db.gaPairs.deleteMany({\n where: { fileId }\n });\n } catch (error) {\n console.error('Failed to delete GA pairs by fileId in database:', error);\n throw error;\n }\n}\n\n/**\n * 切换 GA 对的激活状态\n * @param {string} id - GA 对 ID\n * @param {boolean} isActive - 激活状态\n * @returns {Promise} 更新后的 GA 对\n */\nexport async function toggleGaPairActive(id, isActive) {\n try {\n return await db.gaPairs.update({\n where: { id },\n data: { isActive }\n });\n } catch (error) {\n console.error('Failed to toggle GA pair active status in database:', error);\n throw error;\n }\n}\n\n/**\n * 获取文件的激活 GA 对\n * @param {string} fileId - 文件 ID\n * @returns {Promise} 激活的 GA 对列表\n */\nexport async function getActiveGaPairsByFileId(fileId) {\n try {\n return await db.gaPairs.findMany({\n where: {\n fileId,\n isActive: true\n },\n orderBy: { pairNumber: 'asc' }\n });\n } catch (error) {\n console.error('Failed to get active GA pairs by fileId in database:', error);\n throw error;\n }\n}\n\n/**\n * 批量更新 GA 对\n * @param {Array} updates - 更新数据数组,每个包含 id 和其他字段\n * @returns {Promise} 更新结果\n */\nexport async function batchUpdateGaPairs(updates) {\n try {\n const results = await Promise.all(\n updates.map(({ id, ...updateData }) => {\n // 过滤掉不应该更新的字段\n const { createAt, updateAt, projectId, fileId, pairNumber, ...data } = updateData;\n\n // 确保有数据需要更新\n if (Object.keys(data).length === 0) {\n console.warn(`No data to update for GA pair ${id}`);\n return Promise.resolve(null);\n }\n\n return db.gaPairs.update({\n where: { id },\n data\n });\n })\n );\n\n // 过滤掉null结果\n return results.filter(result => result !== null);\n } catch (error) {\n console.error('Failed to batch update GA pairs in database:', error);\n throw error;\n }\n}\n\n/**\n * Generate and save GA pairs for a specific file using LLM\n * @param {string} projectId - Project ID\n * @param {string} fileId - File ID\n * @param {Array} gaPairs - Array of GA pair objects from LLM\n * @returns {Promise} - Created GA pairs\n */\nexport async function saveGaPairs(projectId, fileId, gaPairs) {\n try {\n // First, delete existing GA pairs for this file to avoid conflicts\n await db.gaPairs.deleteMany({\n where: { projectId, fileId }\n });\n\n // Map the GA pairs to database format\n const gaPairData = gaPairs.map((pair, index) => ({\n projectId,\n fileId,\n pairNumber: index + 1, // 1-5\n genreTitle: pair.genre.title,\n genreDesc: pair.genre.description,\n audienceTitle: pair.audience.title,\n audienceDesc: pair.audience.description,\n isActive: true\n }));\n\n return await db.gaPairs.createMany({ data: gaPairData });\n } catch (error) {\n console.error('Failed to save GA pairs in database:', error);\n throw error;\n }\n}\n\n/**\n * Check if GA pairs exist for a file\n * @param {string} projectId - Project ID\n * @param {string} fileId - File ID\n * @returns {Promise} - Whether GA pairs exist\n */\nexport async function hasGaPairs(projectId, fileId) {\n try {\n const count = await db.gaPairs.count({\n where: { projectId, fileId }\n });\n return count > 0;\n } catch (error) {\n console.error('Failed to check GA pairs existence:', error);\n throw error;\n }\n}\n\n/**\n * Get GA pair statistics for a project\n * @param {string} projectId - Project ID\n * @returns {Promise} - GA pair statistics\n */\nexport async function getGaPairStats(projectId) {\n try {\n const totalCount = await db.gaPairs.count({\n where: { projectId }\n });\n\n const activeCount = await db.gaPairs.count({\n where: { projectId, isActive: true }\n });\n\n const filesWithGaPairs = await db.gaPairs.groupBy({\n by: ['fileId'],\n where: { projectId }\n });\n\n return {\n totalPairs: totalCount,\n activePairs: activeCount,\n filesWithPairs: filesWithGaPairs.length\n };\n } catch (error) {\n console.error('Failed to get GA pair statistics:', error);\n throw error;\n }\n}\n"], ["/easy-dataset/electron/modules/logger.js", "const fs = require('fs');\nconst path = require('path');\n\n/**\n * 设置应用日志系统\n * @param {Object} app Electron app 对象\n * @returns {string} 日志文件路径\n */\nfunction setupLogging(app) {\n const logDir = path.join(app.getPath('userData'), 'logs');\n if (!fs.existsSync(logDir)) {\n fs.mkdirSync(logDir, { recursive: true });\n }\n\n const logFilePath = path.join(logDir, `app-${new Date().toISOString().slice(0, 10)}.log`);\n\n // 创建自定义日志函数\n global.appLog = (message, level = 'info') => {\n const timestamp = new Date().toISOString();\n const logEntry = `[${timestamp}] [${level.toUpperCase()}] ${message}\\n`;\n\n // 同时输出到控制台和日志文件\n console.log(message);\n fs.appendFileSync(logFilePath, logEntry);\n };\n\n // 捕获全局未处理异常并记录\n process.on('uncaughtException', error => {\n global.appLog(`未捕获的异常: ${error.stack || error}`, 'error');\n });\n\n return logFilePath;\n}\n\n/**\n * 设置 IPC 日志处理程序\n * @param {Object} ipcMain IPC 主进程对象\n * @param {Object} app Electron app 对象\n * @param {boolean} isDev 是否为开发环境\n */\nfunction setupIpcLogging(ipcMain, app, isDev) {\n ipcMain.on('log', (event, { level, message }) => {\n const timestamp = new Date().toISOString();\n const logEntry = `[${timestamp}] [${level.toUpperCase()}] ${message}\\n`;\n\n // 只在客户端环境下写入文件\n if (!isDev || true) {\n const logsDir = path.join(app.getPath('userData'), 'logs');\n if (!fs.existsSync(logsDir)) {\n fs.mkdirSync(logsDir, { recursive: true });\n }\n const logFile = path.join(logsDir, `${new Date().toISOString().split('T')[0]}.log`);\n fs.appendFileSync(logFile, logEntry);\n }\n\n // 同时输出到控制台\n console[level](message);\n });\n}\n\n/**\n * 清理日志文件\n * @param {Object} app Electron app 对象\n * @returns {Promise}\n */\nasync function clearLogs(app) {\n const logsDir = path.join(app.getPath('userData'), 'logs');\n if (fs.existsSync(logsDir)) {\n // 读取目录下所有文件\n const files = await fs.promises.readdir(logsDir);\n // 删除所有文件\n for (const file of files) {\n const filePath = path.join(logsDir, file);\n await fs.promises.unlink(filePath);\n global.appLog(`已删除日志文件: ${filePath}`);\n }\n }\n}\n\nmodule.exports = {\n setupLogging,\n setupIpcLogging,\n clearLogs\n};\n"], ["/easy-dataset/app/api/projects/[projectId]/config/route.js", "import { NextResponse } from 'next/server';\nimport { getProject, updateProject, getTaskConfig } from '@/lib/db/projects';\n\n// 获取项目配置\nexport async function GET(request, { params }) {\n try {\n const projectId = params.projectId;\n const config = await getProject(projectId);\n const taskConfig = await getTaskConfig(projectId);\n return NextResponse.json({ ...config, ...taskConfig });\n } catch (error) {\n console.error('获取项目配置失败:', String(error));\n return NextResponse.json({ error: error.message }, { status: 500 });\n }\n}\n\n// 更新项目配置\nexport async function PUT(request, { params }) {\n try {\n const projectId = params.projectId;\n const newConfig = await request.json();\n const currentConfig = await getProject(projectId);\n\n // 只更新 prompts 部分\n const updatedConfig = {\n ...currentConfig,\n ...newConfig.prompts\n };\n\n const config = await updateProject(projectId, updatedConfig);\n return NextResponse.json(config);\n } catch (error) {\n console.error('更新项目配置失败:', String(error));\n return NextResponse.json({ error: error.message }, { status: 500 });\n }\n}\n"], ["/easy-dataset/components/UpdateChecker.js", "import React, { useState, useEffect } from 'react';\nimport { Box, Button, Snackbar, Alert, Typography, Link, CircularProgress, LinearProgress } from '@mui/material';\nimport UpdateIcon from '@mui/icons-material/Update';\nimport { useTranslation } from 'react-i18next';\n\nconst UpdateChecker = () => {\n const { t } = useTranslation();\n const [updateAvailable, setUpdateAvailable] = useState(false);\n const [updateInfo, setUpdateInfo] = useState(null);\n const [open, setOpen] = useState(false);\n const [checking, setChecking] = useState(false);\n const [downloading, setDownloading] = useState(false);\n const [downloadProgress, setDownloadProgress] = useState(0);\n const [updateDownloaded, setUpdateDownloaded] = useState(false);\n const [updateError, setUpdateError] = useState(null);\n\n // 检查更新\n const checkForUpdates = async () => {\n if (!window.electron?.updater) {\n console.warn('Update feature is not available, possibly running in browser environment');\n return;\n }\n\n try {\n setChecking(true);\n setUpdateError(null);\n\n const result = await window.electron.updater.checkForUpdates();\n console.log('Update check result:', result);\n\n // 返回当前版本信息\n if (result) {\n setUpdateInfo(prev => ({\n ...prev,\n currentVersion: result.currentVersion\n }));\n }\n } catch (error) {\n console.error('Failed to check for updates:', error);\n // setUpdateError(error.message || 'Failed to check for updates');\n } finally {\n setChecking(false);\n }\n };\n\n // 下载更新\n const downloadUpdate = async () => {\n if (!window.electron?.updater) return;\n\n try {\n setDownloading(true);\n setUpdateError(null);\n await window.electron.updater.downloadUpdate();\n } catch (error) {\n console.error('下载更新失败:', error);\n setUpdateError(error.message || '下载更新失败');\n setDownloading(false);\n }\n };\n\n // 安装更新\n const installUpdate = async () => {\n if (!window.electron?.updater) return;\n\n try {\n await window.electron.updater.installUpdate();\n } catch (error) {\n console.error('Failed to install update:', error);\n // setUpdateError(error.message || 'Failed to install update');\n }\n };\n\n // 设置更新事件监听\n useEffect(() => {\n if (!window.electron?.updater) return;\n\n // 有可用更新\n const removeUpdateAvailable = window.electron.updater.onUpdateAvailable(info => {\n console.log('发现新版本:', info);\n setUpdateAvailable(true);\n setUpdateInfo(prev => ({\n ...prev,\n ...info,\n releaseUrl: `https://github.com/ConardLi/easy-dataset/releases`\n }));\n setOpen(true);\n });\n\n // 没有可用更新\n const removeUpdateNotAvailable = window.electron.updater.onUpdateNotAvailable(() => {\n console.log('没有可用更新');\n setUpdateAvailable(false);\n });\n\n // 更新错误\n const removeUpdateError = window.electron.updater.onUpdateError(error => {\n console.error('更新错误:', error);\n // setUpdateError(error);\n });\n\n // 下载进度\n const removeDownloadProgress = window.electron.updater.onDownloadProgress(progress => {\n console.log('下载进度:', progress);\n setDownloadProgress(progress.percent || 0);\n });\n\n // 更新下载完成\n const removeUpdateDownloaded = window.electron.updater.onUpdateDownloaded(info => {\n console.log('更新下载完成:', info);\n setDownloading(false);\n setUpdateDownloaded(true);\n });\n\n // 组件挂载时检查更新\n const timer = setTimeout(() => {\n checkForUpdates();\n }, 5000);\n\n // 清理函数\n return () => {\n clearTimeout(timer);\n removeUpdateAvailable();\n removeUpdateNotAvailable();\n removeUpdateError();\n removeDownloadProgress();\n removeUpdateDownloaded();\n };\n }, []);\n\n // 定期检查更新(每小时一次)\n useEffect(() => {\n if (!window.electron?.updater) return;\n\n const interval = setInterval(\n () => {\n checkForUpdates();\n },\n 60 * 60 * 1000\n );\n\n return () => clearInterval(interval);\n }, []);\n\n const handleClose = () => {\n setOpen(false);\n };\n\n // 如果没有更新或者不在 Electron 环境中,不显示任何内容\n if (!updateAvailable && !open) return null;\n\n return (\n <>\n {updateAvailable && (\n \n )}\n\n \n \n \n {t('update.newVersionAvailable')}\n\n {updateInfo && (\n <>\n \n {t('update.currentVersion')}: {updateInfo.currentVersion}\n \n \n {t('update.latestVersion')}: {updateInfo.version}\n \n \n )}\n\n {checking && (\n \n \n {t('update.checking')}\n \n )}\n\n {updateError && (\n \n {updateError}\n \n )}\n\n {downloading && (\n \n \n {t('update.downloading')}: {Math.round(downloadProgress)}%\n \n \n \n )}\n\n \n {/* {!downloading && !updateDownloaded ? (\n \n {t('update.downloadNow')}\n \n ) : updateDownloaded ? (\n \n {t('update.installNow')}\n \n ) : null} */}\n\n {updateInfo?.releaseUrl && (\n \n \n \n )}\n \n \n \n \n \n );\n};\n\nexport default UpdateChecker;\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/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/app/api/projects/[projectId]/tasks/list/route.js", "import { NextResponse } from 'next/server';\nimport { PrismaClient } from '@prisma/client';\n\nconst prisma = new PrismaClient();\n\n// 获取项目的所有任务列表\nexport async function GET(request, { params }) {\n try {\n const { projectId } = params;\n const { searchParams } = new URL(request.url);\n\n // 可选参数: 任务类型和任务状态\n const taskType = searchParams.get('taskType');\n const statusStr = searchParams.get('status');\n\n // 分页参数\n const page = parseInt(searchParams.get('page') || '0');\n const limit = parseInt(searchParams.get('limit') || '10');\n\n // 构建查询条件\n const where = { projectId };\n\n if (taskType) {\n where.taskType = taskType;\n }\n\n if (statusStr && !isNaN(parseInt(statusStr))) {\n where.status = parseInt(statusStr);\n }\n\n // 获取任务总数\n const total = await prisma.task.count({ where });\n\n // 获取任务列表,按创建时间降序排序,并应用分页\n const tasks = await prisma.task.findMany({\n where,\n orderBy: {\n createAt: 'desc'\n },\n skip: page * limit,\n take: limit\n });\n\n return NextResponse.json({\n code: 0,\n data: tasks,\n total,\n page,\n limit,\n message: '任务列表获取成功'\n });\n } catch (error) {\n console.error('获取任务列表失败:', String(error));\n return NextResponse.json(\n {\n code: 500,\n error: '获取任务列表失败',\n message: error.message\n },\n { status: 500 }\n );\n }\n}\n"], ["/easy-dataset/lib/services/tasks/recovery.js", "/**\n * 任务恢复服务\n * 用于在服务启动时检查并恢复未完成的任务\n */\nimport { PrismaClient } from '@prisma/client';\nimport { processAnswerGenerationTask } from './answer-generation';\nimport { processQuestionGenerationTask } from './question-generation';\n\nconst prisma = new PrismaClient();\n\n// 服务初始化标志,确保只执行一次\nlet initialized = false;\n\n/**\n * 恢复未完成的任务\n * 在应用启动时自动执行一次\n */\nexport async function recoverPendingTasks() {\n // 如果已经初始化过,直接返回\n if (process.env.INITED) {\n return;\n }\n\n process.env.INITED = true;\n\n try {\n console.log('开始检查未完成任务...');\n\n // 查找所有处理中的任务\n const pendingTasks = await prisma.task.findMany({\n where: {\n status: 0 // 处理中的任务\n }\n });\n\n if (pendingTasks.length === 0) {\n console.log('没有需要恢复的任务');\n initialized = true;\n return;\n }\n\n console.log(`找到 ${pendingTasks.length} 个未完成任务,开始恢复...`);\n\n // 遍历处理每个任务\n for (const task of pendingTasks) {\n try {\n // 根据任务类型调用对应的处理函数\n switch (task.taskType) {\n case 'question-generation':\n // 异步处理,不等待完成\n processQuestionGenerationTask(task).catch(error => {\n console.error(`恢复问题生成任务 ${task.id} 失败:`, error);\n });\n break;\n case 'answer-generation':\n // 异步处理,不等待完成\n processAnswerGenerationTask(task).catch(error => {\n console.error(`恢复答案生成任务 ${task.id} 失败:`, error);\n });\n break;\n default:\n console.warn(`Other Task: ${task.taskType}`);\n await prisma.task.update({\n where: { id: task.id },\n data: {\n status: 2,\n detail: `${task.taskType} Error`,\n note: `${task.taskType} Error`,\n endTime: new Date()\n }\n });\n }\n } catch (error) {\n console.error(`恢复任务 ${task.id} 失败:`, error);\n }\n }\n\n console.log('任务恢复服务已启动,未完成任务将在后台继续处理');\n initialized = true;\n } catch (error) {\n console.error('任务恢复服务出错:', error);\n // 即使出错也标记为已初始化,避免反复尝试\n initialized = true;\n }\n}\n\n// 在模块加载时自动执行恢复\nrecoverPendingTasks().catch(error => {\n console.error('执行任务恢复失败:', error);\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/ParticleBackground.js", "'use client';\n\nimport { useEffect, useRef } from 'react';\nimport { useTheme } from '@mui/material';\n\nexport default function ParticleBackground() {\n const canvasRef = useRef(null);\n const theme = useTheme();\n\n useEffect(() => {\n const canvas = canvasRef.current;\n const ctx = canvas.getContext('2d');\n let animationFrameId;\n let particles = [];\n let mousePosition = { x: 0, y: 0 };\n let hoverRadius = 150; // 增加鼠标影响范围\n let mouseSpeed = { x: 0, y: 0 }; // 跟踪鼠标速度\n let lastMousePosition = { x: 0, y: 0 }; // 上一帧鼠标位置\n\n // 设置画布大小为窗口大小\n const handleResize = () => {\n canvas.width = window.innerWidth;\n canvas.height = window.innerHeight;\n initParticles();\n };\n\n // 跟踪鼠标位置和速度\n const handleMouseMove = event => {\n // 计算鼠标速度\n mouseSpeed.x = event.clientX - mousePosition.x;\n mouseSpeed.y = event.clientY - mousePosition.y;\n\n // 更新鼠标位置\n lastMousePosition.x = mousePosition.x;\n lastMousePosition.y = mousePosition.y;\n mousePosition.x = event.clientX;\n mousePosition.y = event.clientY;\n };\n\n // 触摸设备支持\n const handleTouchMove = event => {\n if (event.touches.length > 0) {\n // 计算触摸速度\n mouseSpeed.x = event.touches[0].clientX - mousePosition.x;\n mouseSpeed.y = event.touches[0].clientY - mousePosition.y;\n\n // 更新触摸位置\n lastMousePosition.x = mousePosition.x;\n lastMousePosition.y = mousePosition.y;\n mousePosition.x = event.touches[0].clientX;\n mousePosition.y = event.touches[0].clientY;\n }\n };\n\n // 生成随机颜色\n const getRandomColor = () => {\n // 主题色调\n const colors =\n theme.palette.mode === 'dark'\n ? [\n 'rgba(255, 255, 255, 0.5)', // 白色\n 'rgba(100, 181, 246, 0.5)', // 蓝色\n 'rgba(156, 39, 176, 0.4)', // 紫色\n 'rgba(121, 134, 203, 0.5)' // 靛蓝色\n ]\n : [\n 'rgba(42, 92, 170, 0.5)', // 主蓝色\n 'rgba(66, 165, 245, 0.4)', // 浅蓝色\n 'rgba(94, 53, 177, 0.3)', // 深紫色\n 'rgba(3, 169, 244, 0.4)' // 天蓝色\n ];\n\n return colors[Math.floor(Math.random() * colors.length)];\n };\n\n // 初始化粒子\n const initParticles = () => {\n particles = [];\n // 增加粒子数量,但保持性能平衡\n const particleCount = Math.min(Math.floor(window.innerWidth / 8), 150);\n\n for (let i = 0; i < particleCount; i++) {\n // 创建不同大小和速度的粒子\n const size = Math.random();\n const speedFactor = Math.max(0.1, size); // 较大的粒子移动较慢\n\n particles.push({\n x: Math.random() * canvas.width,\n y: Math.random() * canvas.height,\n // 粒子大小更加多样化\n radius: size * 3 + 0.5,\n // 使用随机颜色\n color: getRandomColor(),\n // 添加发光效果\n glow: Math.random() * 10 + 5,\n // 调整速度范围,使运动更加自然\n speedX: (Math.random() * 0.6 - 0.3) * speedFactor,\n speedY: (Math.random() * 0.6 - 0.3) * speedFactor,\n originalSpeedX: (Math.random() * 0.6 - 0.3) * speedFactor,\n originalSpeedY: (Math.random() * 0.6 - 0.3) * speedFactor,\n // 添加脉动效果\n pulseSpeed: Math.random() * 0.02 + 0.01,\n pulseDirection: Math.random() > 0.5 ? 1 : -1,\n pulseAmount: 0,\n // 粒子透明度\n opacity: Math.random() * 0.5 + 0.5\n });\n }\n };\n\n // 绘制粒子\n const drawParticles = () => {\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n\n // 计算鼠标速度衰减\n mouseSpeed.x *= 0.95;\n mouseSpeed.y *= 0.95;\n\n // 绘制粒子之间的连线\n drawLines();\n\n particles.forEach(particle => {\n // 计算粒子与鼠标的距离\n const dx = mousePosition.x - particle.x;\n const dy = mousePosition.y - particle.y;\n const distance = Math.sqrt(dx * dx + dy * dy);\n\n // 脉动效果\n particle.pulseAmount += particle.pulseSpeed * particle.pulseDirection;\n if (Math.abs(particle.pulseAmount) > 0.5) {\n particle.pulseDirection *= -1;\n }\n\n // 如果粒子在鼠标影响范围内,调整其速度\n if (distance < hoverRadius) {\n const angle = Math.atan2(dy, dx);\n const force = (hoverRadius - distance) / hoverRadius;\n const mouseFactor = 3; // 增强鼠标影响力度\n\n // 粒子远离鼠标,并受鼠标速度影响\n particle.speedX = -Math.cos(angle) * force * mouseFactor + particle.originalSpeedX + mouseSpeed.x * 0.05;\n particle.speedY = -Math.sin(angle) * force * mouseFactor + particle.originalSpeedY + mouseSpeed.y * 0.05;\n } else {\n // 逐渐恢复原始速度\n particle.speedX = particle.speedX * 0.95 + particle.originalSpeedX * 0.05;\n particle.speedY = particle.speedY * 0.95 + particle.originalSpeedY * 0.05;\n }\n\n // 更新粒子位置\n particle.x += particle.speedX;\n particle.y += particle.speedY;\n\n // 边界检查\n if (particle.x < 0) particle.x = canvas.width;\n if (particle.x > canvas.width) particle.x = 0;\n if (particle.y < 0) particle.y = canvas.height;\n if (particle.y > canvas.height) particle.y = 0;\n\n // 应用脉动效果到粒子大小\n const currentRadius = particle.radius * (1 + particle.pulseAmount * 0.2);\n\n // 绘制发光效果\n const gradient = ctx.createRadialGradient(particle.x, particle.y, 0, particle.x, particle.y, particle.glow);\n gradient.addColorStop(0, particle.color);\n gradient.addColorStop(1, 'rgba(0, 0, 0, 0)');\n\n // 绘制粒子\n ctx.beginPath();\n ctx.arc(particle.x, particle.y, currentRadius, 0, Math.PI * 2);\n ctx.fillStyle = particle.color;\n ctx.fill();\n\n // 添加发光效果\n ctx.beginPath();\n ctx.arc(particle.x, particle.y, particle.glow, 0, Math.PI * 2);\n ctx.fillStyle = gradient;\n ctx.globalAlpha = 0.3 * particle.opacity;\n ctx.fill();\n ctx.globalAlpha = 1.0;\n });\n\n animationFrameId = requestAnimationFrame(drawParticles);\n };\n\n // 绘制粒子之间的连线\n const drawLines = () => {\n for (let i = 0; i < particles.length; i++) {\n for (let j = i + 1; j < particles.length; j++) {\n const dx = particles[i].x - particles[j].x;\n const dy = particles[i].y - particles[j].y;\n const distance = Math.sqrt(dx * dx + dy * dy);\n\n // 增加连线的最大距离\n const maxDistance = 120;\n\n if (distance < maxDistance) {\n // 只在粒子距离小于maxDistance时绘制连线\n ctx.beginPath();\n ctx.moveTo(particles[i].x, particles[i].y);\n ctx.lineTo(particles[j].x, particles[j].y);\n\n // 根据距离设置线条透明度\n const opacity = 1 - distance / maxDistance;\n\n // 根据主题设置线条颜色\n const lineColor =\n theme.palette.mode === 'dark'\n ? `rgba(255, 255, 255, ${opacity * 0.2})`\n : `rgba(42, 92, 170, ${opacity * 0.2})`;\n\n ctx.strokeStyle = lineColor;\n ctx.lineWidth = opacity * 1.5; // 根据距离调整线宽\n ctx.stroke();\n }\n }\n }\n };\n\n // 初始化\n handleResize();\n window.addEventListener('resize', handleResize);\n window.addEventListener('mousemove', handleMouseMove);\n window.addEventListener('touchmove', handleTouchMove);\n\n // 开始动画\n drawParticles();\n\n // 清理函数\n return () => {\n window.removeEventListener('resize', handleResize);\n window.removeEventListener('mousemove', handleMouseMove);\n window.removeEventListener('touchmove', handleTouchMove);\n cancelAnimationFrame(animationFrameId);\n };\n }, [theme.palette.mode]);\n\n return (\n \n );\n}\n"], ["/easy-dataset/lib/file/split-markdown/index.js", "/**\n * Markdown文本分割工具主模块\n */\n\nconst parser = require('./core/parser');\nconst splitter = require('./core/splitter');\nconst summary = require('./core/summary');\nconst formatter = require('./output/formatter');\nconst fileWriter = require('./output/fileWriter');\nconst toc = require('./core/toc');\n\n/**\n * 拆分Markdown文档\n * @param {string} markdownText - Markdown文本\n * @param {number} minSplitLength - 最小分割字数\n * @param {number} maxSplitLength - 最大分割字数\n * @returns {Array} - 分割结果数组\n */\nfunction splitMarkdown(markdownText, minSplitLength, maxSplitLength) {\n // 解析文档结构\n const outline = parser.extractOutline(markdownText);\n\n // 按标题分割文档\n const sections = parser.splitByHeadings(markdownText, outline);\n\n // 处理段落,确保满足分割条件\n const res = splitter.processSections(sections, outline, minSplitLength, maxSplitLength);\n\n return res.map(r => ({\n result: `> **📑 Summarization:** *${r.summary}*\\n\\n---\\n\\n${r.content}`,\n ...r\n }));\n}\n\n// 导出模块功能\nmodule.exports = {\n // 核心功能\n splitMarkdown,\n combineMarkdown: formatter.combineMarkdown,\n saveToSeparateFiles: fileWriter.saveToSeparateFiles,\n\n // 目录提取功能\n extractTableOfContents: toc.extractTableOfContents,\n tocToMarkdown: toc.tocToMarkdown,\n\n // 其他导出的子功能\n parser,\n splitter,\n summary,\n formatter,\n fileWriter,\n toc\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/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/lib/db/projects.js", "'use server';\n\nimport fs from 'fs';\nimport path from 'path';\nimport { getProjectRoot, readJsonFile } from './base';\nimport { DEFAULT_SETTINGS } from '@/constant/setting';\nimport { db } from '@/lib/db/index';\nimport { nanoid } from 'nanoid';\n\n// 创建新项目\nexport async function createProject(projectData) {\n try {\n let projectId = nanoid(12);\n const projectRoot = await getProjectRoot();\n const projectDir = path.join(projectRoot, projectId);\n // 创建项目目录\n await fs.promises.mkdir(projectDir, { recursive: true });\n // 创建子目录\n await fs.promises.mkdir(path.join(projectDir, 'files'), { recursive: true }); // 原始文件\n return await db.projects.create({\n data: {\n id: projectId,\n name: projectData.name,\n description: projectData.description\n }\n });\n } catch (error) {\n console.error('Failed to create project in database');\n throw error;\n }\n}\n\nexport async function isExistByName(name) {\n try {\n const count = await db.projects.count({\n where: {\n name: name\n }\n });\n return count > 0;\n } catch (error) {\n console.error('Failed to get project by name in database');\n throw error;\n }\n}\n\n// 获取所有项目\nexport async function getProjects() {\n try {\n return await db.projects.findMany({\n include: {\n _count: {\n select: {\n Datasets: true,\n Questions: true\n }\n }\n },\n orderBy: {\n createAt: 'desc'\n }\n });\n } catch (error) {\n console.error('Failed to get projects in database');\n throw error;\n }\n}\n\n// 获取项目详情\nexport async function getProject(projectId) {\n try {\n return await db.projects.findUnique({ where: { id: projectId } });\n } catch (error) {\n console.error('Failed to get project by id in database');\n throw error;\n }\n}\n\n// 更新项目配置\nexport async function updateProject(projectId, projectData) {\n try {\n delete projectData.projectId;\n return await db.projects.update({\n where: { id: projectId },\n data: { ...projectData }\n });\n } catch (error) {\n console.error('Failed to update project in database');\n throw error;\n }\n}\n\n// 删除项目\nexport async function deleteProject(projectId) {\n try {\n const projectRoot = await getProjectRoot();\n const projectPath = path.join(projectRoot, projectId);\n await db.projects.delete({ where: { id: projectId } });\n if (fs.existsSync(projectPath)) {\n await fs.promises.rm(projectPath, { recursive: true });\n }\n return true;\n } catch (error) {\n return false;\n }\n}\n\n// 获取任务配置\nexport async function getTaskConfig(projectId) {\n const projectRoot = await getProjectRoot();\n const projectPath = path.join(projectRoot, projectId);\n const taskConfigPath = path.join(projectPath, 'task-config.json');\n const taskData = await readJsonFile(taskConfigPath);\n if (!taskData) {\n return DEFAULT_SETTINGS;\n }\n return taskData;\n}\n"], ["/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/lib/db/llm-models.js", "'use server';\nimport { db } from '@/lib/db/index';\n\nexport async function getLlmModelsByProviderId(providerId) {\n try {\n return await db.llmModels.findMany({ where: { providerId } });\n } catch (error) {\n console.error('Failed to get llmModels by providerId in database');\n throw error;\n }\n}\n\nexport async function createLlmModels(models) {\n try {\n return await db.llmModels.createMany({ data: models });\n } catch (error) {\n console.error('Failed to create llmModels in database');\n throw error;\n }\n}\n"], ["/easy-dataset/components/tasks/TasksTable.js", "'use client';\n\nimport React from 'react';\nimport {\n Table,\n TableBody,\n TableCell,\n TableContainer,\n TableHead,\n TableRow,\n Paper,\n Typography,\n CircularProgress,\n Box,\n TablePagination\n} from '@mui/material';\nimport { useTranslation } from 'react-i18next';\nimport { formatDistanceToNow } from 'date-fns';\nimport { zhCN, enUS } from 'date-fns/locale';\n\n// 导入子组件\nimport TaskStatusChip from './TaskStatusChip';\nimport TaskProgress from './TaskProgress';\nimport TaskActions from './TaskActions';\n\nexport default function TasksTable({\n tasks,\n loading,\n handleAbortTask,\n handleDeleteTask,\n page,\n rowsPerPage,\n handleChangePage,\n handleChangeRowsPerPage,\n totalCount\n}) {\n const { t, i18n } = useTranslation();\n\n // 格式化日期\n const formatDate = dateString => {\n if (!dateString) return '-';\n const date = new Date(dateString);\n return formatDistanceToNow(date, {\n addSuffix: true,\n locale: i18n.language === 'zh-CN' ? zhCN : enUS\n });\n };\n\n // 计算任务运行时间\n const calculateDuration = (startTimeStr, endTimeStr) => {\n if (!startTimeStr || !endTimeStr) return '-';\n\n try {\n const startTime = new Date(startTimeStr);\n const endTime = new Date(endTimeStr);\n\n // 计算时间差(毫秒)\n const duration = endTime - startTime;\n\n // 将毫秒转换为人类可读格式\n const seconds = Math.floor(duration / 1000);\n\n if (seconds < 60) {\n return t('tasks.duration.seconds', { seconds });\n } else if (seconds < 3600) {\n const minutes = Math.floor(seconds / 60);\n const remainingSeconds = seconds % 60;\n return t('tasks.duration.minutes', { minutes, seconds: remainingSeconds });\n } else {\n const hours = Math.floor(seconds / 3600);\n const remainingMinutes = Math.floor((seconds % 3600) / 60);\n return t('tasks.duration.hours', { hours, minutes: remainingMinutes });\n }\n } catch (error) {\n console.error('计算运行时间出错:', error);\n return '-';\n }\n };\n\n // 解析模型信息\n const parseModelInfo = modelInfoString => {\n let modelInfo = '';\n try {\n const parsedModel = JSON.parse(modelInfoString);\n modelInfo = parsedModel.modelName || parsedModel.name || '-';\n } catch (error) {\n modelInfo = modelInfoString || '-';\n }\n return modelInfo;\n };\n\n // 任务类型本地化\n const getLocalizedTaskType = taskType => {\n return t(`tasks.types.${taskType}`, { defaultValue: taskType });\n };\n\n return (\n \n \n \n \n \n {t('tasks.table.type')}\n {t('tasks.table.status')}\n {t('tasks.table.progress')}\n {t('tasks.table.success')}\n {t('tasks.table.failed')}\n {t('tasks.table.createTime')}\n {t('tasks.table.duration')}\n {t('tasks.table.model')}\n {t('tasks.table.actions')}\n \n \n \n {loading && tasks.length === 0 ? (\n \n \n \n \n \n {t('tasks.loading')}\n \n \n \n \n ) : tasks.length === 0 ? (\n \n \n {t('tasks.empty')}\n \n \n ) : (\n tasks.map(task => (\n \n {getLocalizedTaskType(task.taskType)}\n \n \n \n \n \n \n {task.completedCount ? task.completedCount - (task.errorCount || 0) : 0}\n {task.errorCount || 0}\n {formatDate(task.createAt)}\n {task.endTime ? calculateDuration(task.startTime, task.endTime) : '-'}\n {parseModelInfo(task.modelInfo)}\n \n \n \n \n ))\n )}\n \n
\n
\n\n {tasks.length > 0 && (\n {\n // 根据实际分页操作计算正确的from和to\n const calculatedFrom = page * rowsPerPage + 1;\n const calculatedTo = Math.min((page + 1) * rowsPerPage, count);\n return t('datasets.pagination', {\n from: calculatedFrom,\n to: calculatedTo,\n count\n });\n }}\n />\n )}\n
\n );\n}\n"], ["/easy-dataset/lib/file/split-markdown/core/parser.js", "/**\n * Markdown文档解析模块\n */\n\n/**\n * 提取文档大纲\n * @param {string} text - Markdown文本\n * @returns {Array} - 提取的大纲数组\n */\nfunction extractOutline(text) {\n const outlineRegex = /^(#{1,6})\\s+(.+?)(?:\\s*\\{#[\\w-]+\\})?\\s*$/gm;\n const outline = [];\n let match;\n\n while ((match = outlineRegex.exec(text)) !== null) {\n const level = match[1].length;\n const title = match[2].trim();\n\n outline.push({\n level,\n title,\n position: match.index\n });\n }\n\n return outline;\n}\n\n/**\n * 根据标题分割文档\n * @param {string} text - Markdown文本\n * @param {Array} outline - 文档大纲\n * @returns {Array} - 按标题分割的段落数组\n */\nfunction splitByHeadings(text, outline) {\n if (outline.length === 0) {\n return [\n {\n heading: null,\n level: 0,\n content: text,\n position: 0\n }\n ];\n }\n\n const sections = [];\n\n // 添加第一个标题前的内容(如果有)\n if (outline[0].position > 0) {\n const frontMatter = text.substring(0, outline[0].position).trim();\n if (frontMatter.length > 0) {\n sections.push({\n heading: null,\n level: 0,\n content: frontMatter,\n position: 0\n });\n }\n }\n\n // 分割每个标题的内容\n for (let i = 0; i < outline.length; i++) {\n const current = outline[i];\n const next = i < outline.length - 1 ? outline[i + 1] : null;\n\n const headingLine = text.substring(current.position).split('\\n')[0];\n const startPos = current.position + headingLine.length + 1;\n const endPos = next ? next.position : text.length;\n\n let content = text.substring(startPos, endPos).trim();\n\n sections.push({\n heading: current.title,\n level: current.level,\n content: content,\n position: current.position\n });\n }\n\n return sections;\n}\n\nmodule.exports = {\n extractOutline,\n splitByHeadings\n};\n"], ["/easy-dataset/electron/modules/database.js", "const fs = require('fs');\nconst path = require('path');\nconst { dialog } = require('electron');\nconst { updateDatabase } = require('./db-updater');\n\n/**\n * 清除数据库缓存\n * @param {Object} app Electron app 对象\n * @returns {Promise} 操作是否成功\n */\nasync function clearDatabaseCache(app) {\n // 清理local-db目录,保留db.sqlite文件\n const localDbDir = path.join(app.getPath('userData'), 'local-db');\n if (fs.existsSync(localDbDir)) {\n // 读取目录下所有文件\n const files = await fs.promises.readdir(localDbDir);\n // 删除除了db.sqlite之外的所有文件\n for (const file of files) {\n if (file !== 'db.sqlite') {\n const filePath = path.join(localDbDir, file);\n const stat = await fs.promises.stat(filePath);\n if (stat.isFile()) {\n await fs.promises.unlink(filePath);\n global.appLog(`已删除数据库缓存文件: ${filePath}`);\n } else if (stat.isDirectory()) {\n // 如果是目录,可能需要递归删除,根据需求决定\n global.appLog(`跳过目录: ${filePath}`);\n }\n }\n }\n }\n return true;\n}\n\n/**\n * 初始化数据库\n * @param {Object} app Electron app 对象\n * @returns {Promise} 数据库配置信息\n */\nasync function initializeDatabase(app) {\n try {\n // 设置数据库路径\n const userDataPath = app.getPath('userData');\n const dataDir = path.join(userDataPath, 'local-db');\n const dbFilePath = path.join(dataDir, 'db.sqlite');\n const dbJSONPath = path.join(dataDir, 'db.json');\n fs.writeFileSync(path.join(process.resourcesPath, 'root-path.txt'), dataDir);\n\n // 确保数据目录存在\n if (!fs.existsSync(dataDir)) {\n fs.mkdirSync(dataDir, { recursive: true });\n console.log(`数据目录已创建: ${dataDir}`);\n }\n\n // 设置数据库连接字符串 (Prisma 格式)\n const dbConnectionString = `file:${dbFilePath}`;\n process.env.DATABASE_URL = dbConnectionString;\n\n // 仅在开发环境记录日志\n const logs = {\n userDataPath,\n dataDir,\n dbFilePath,\n dbConnectionString,\n dbExists: fs.existsSync(dbFilePath)\n };\n global.appLog(`数据库配置: ${JSON.stringify(logs)}`);\n\n if (!fs.existsSync(dbFilePath)) {\n global.appLog('数据库文件不存在,正在初始化...');\n\n try {\n const resourcePath =\n process.env.NODE_ENV === 'development'\n ? path.join(__dirname, '../..', 'prisma', 'template.sqlite')\n : path.join(process.resourcesPath, 'prisma', 'template.sqlite');\n\n const resourceJSONPath =\n process.env.NODE_ENV === 'development'\n ? path.join(__dirname, '../..', 'prisma', 'sql.json')\n : path.join(process.resourcesPath, 'prisma', 'sql.json');\n\n global.appLog(`resourcePath: ${resourcePath}`);\n\n if (fs.existsSync(resourcePath)) {\n fs.copyFileSync(resourcePath, dbFilePath);\n global.appLog(`数据库已从模板初始化: ${dbFilePath}`);\n }\n\n if (fs.existsSync(resourceJSONPath)) {\n fs.copyFileSync(resourceJSONPath, dbJSONPath);\n global.appLog(`数据库SQL配置已初始化: ${dbJSONPath}`);\n }\n } catch (error) {\n console.error('数据库初始化失败:', error);\n dialog.showErrorBox('数据库初始化失败', `应用无法初始化数据库,可能需要重新安装。\\n错误详情: ${error.message}`);\n throw error;\n }\n } else {\n // 数据库文件存在,检查是否需要更新\n global.appLog('检查数据库是否需要更新...');\n try {\n const resourcesPath =\n process.env.NODE_ENV === 'development' ? path.join(__dirname, '../..') : process.resourcesPath;\n\n const isDev = process.env.NODE_ENV === 'development';\n\n // 更新数据库\n const result = await updateDatabase(userDataPath, resourcesPath, isDev, global.appLog);\n\n if (result.updated) {\n global.appLog(`数据库更新成功: ${result.message}`);\n global.appLog(`执行的版本: ${result.executedVersions.join(', ')}`);\n } else {\n global.appLog(`数据库无需更新: ${result.message}`);\n }\n } catch (error) {\n console.error('数据库更新失败:', error);\n global.appLog(`数据库更新失败: ${error.message}`, 'error');\n\n // 非致命错误,只提示但不阻止应用启动\n dialog.showMessageBox({\n type: 'warning',\n title: '数据库更新警告',\n message: '数据库更新过程中出现错误,部分功能可能受影响。',\n detail: `错误详情: ${error.message}\\n\\n您可以继续使用应用,但如果遇到问题,请重新安装应用。`,\n buttons: ['继续']\n });\n }\n }\n\n return {\n userDataPath,\n dataDir,\n dbFilePath,\n dbConnectionString\n };\n } catch (error) {\n console.error('初始化数据库时发生错误:', error);\n throw error;\n }\n}\n\nmodule.exports = {\n clearDatabaseCache,\n initializeDatabase\n};\n"], ["/easy-dataset/lib/file/file-process/get-content.js", "import TurndownService from 'turndown';\nimport mammoth from 'mammoth';\n\n/**\n * 获取文件内容\n * @param {*} file\n */\nexport async function getContent(file) {\n let fileContent;\n let fileName = file.name;\n\n // 如果是 docx 文件,先转换为 markdown\n if (file.name.endsWith('.docx')) {\n const arrayBuffer = await file.arrayBuffer();\n const htmlResult = await mammoth.convertToHtml(\n { arrayBuffer },\n {\n convertImage: image => {\n return mammoth.docx.paragraph({\n children: [\n mammoth.docx.textRun({\n text: ''\n })\n ]\n });\n }\n }\n );\n const turndownService = new TurndownService();\n fileContent = turndownService.turndown(htmlResult.value);\n fileName = file.name.replace('.docx', '.md');\n } else {\n // 对于 md 和 txt 文件,直接读取内容\n const reader = new FileReader();\n fileContent = await new Promise((resolve, reject) => {\n reader.onload = () => resolve(reader.result);\n reader.onerror = reject;\n reader.readAsArrayBuffer(file);\n });\n fileName = file.name.replace('.txt', '.md');\n }\n return { fileContent, fileName };\n}\n"], ["/easy-dataset/app/api/projects/[projectId]/tasks/[taskId]/route.js", "import { NextResponse } from 'next/server';\nimport { PrismaClient } from '@prisma/client';\n\nconst prisma = new PrismaClient();\n\n// 获取任务详情\nexport async function GET(request, { params }) {\n try {\n const { projectId, taskId } = params;\n\n // 验证必填参数\n if (!projectId || !taskId) {\n return NextResponse.json(\n {\n code: 400,\n error: '缺少必要参数'\n },\n { status: 400 }\n );\n }\n\n // 查询任务详情\n const task = await prisma.task.findUnique({\n where: {\n id: taskId,\n projectId\n }\n });\n\n if (!task) {\n return NextResponse.json(\n {\n code: 404,\n error: '任务不存在'\n },\n { status: 404 }\n );\n }\n\n return NextResponse.json({\n code: 0,\n data: task,\n message: '获取任务详情成功'\n });\n } catch (error) {\n console.error('获取任务详情失败:', String(error));\n return NextResponse.json(\n {\n code: 500,\n error: '获取任务详情失败',\n message: error.message\n },\n { status: 500 }\n );\n }\n}\n\n// 更新任务状态\nexport async function PATCH(request, { params }) {\n try {\n const { projectId, taskId } = params;\n const data = await request.json();\n\n // 验证必填参数\n if (!projectId || !taskId) {\n return NextResponse.json(\n {\n code: 400,\n error: '缺少必要参数'\n },\n { status: 400 }\n );\n }\n\n // 获取要更新的字段\n const { status, completedCount, totalCount, detail, note, endTime } = data;\n\n // 构建更新数据\n const updateData = {};\n\n if (status !== undefined) {\n updateData.status = status;\n }\n\n if (completedCount !== undefined) {\n updateData.completedCount = completedCount;\n }\n\n if (totalCount !== undefined) {\n updateData.totalCount = totalCount;\n }\n\n if (detail !== undefined) {\n updateData.detail = detail;\n }\n\n if (note !== undefined) {\n updateData.note = note;\n }\n\n // 如果状态变为已完成、失败或已中断,自动添加结束时间\n if (status === 1 || status === 2 || status === 3) {\n updateData.endTime = endTime || new Date();\n }\n\n // 更新任务\n const updatedTask = await prisma.task.update({\n where: {\n id: taskId\n },\n data: updateData\n });\n\n return NextResponse.json({\n code: 0,\n data: updatedTask,\n message: '更新任务状态成功'\n });\n } catch (error) {\n console.error('更新任务状态失败:', String(error));\n return NextResponse.json(\n {\n code: 500,\n error: '更新任务状态失败',\n message: error.message\n },\n { status: 500 }\n );\n }\n}\n\n// 删除任务\nexport async function DELETE(request, { params }) {\n try {\n const { projectId, taskId } = params;\n\n // 验证必填参数\n if (!projectId || !taskId) {\n return NextResponse.json(\n {\n code: 400,\n error: '缺少必要参数'\n },\n { status: 400 }\n );\n }\n\n // 删除任务\n await prisma.task.delete({\n where: {\n id: taskId,\n projectId\n }\n });\n\n return NextResponse.json({\n code: 0,\n message: '删除任务成功'\n });\n } catch (error) {\n console.error('删除任务失败:', String(error));\n return NextResponse.json(\n {\n code: 500,\n error: '删除任务失败',\n message: error.message\n },\n { status: 500 }\n );\n }\n}\n"], ["/easy-dataset/hooks/useTaskSettings.js", "import { useState, useEffect } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { DEFAULT_SETTINGS } from '@/constant/setting';\n\nexport default function useTaskSettings(projectId) {\n const { t } = useTranslation();\n const [taskSettings, setTaskSettings] = useState({\n ...DEFAULT_SETTINGS\n });\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n const [success, setSuccess] = useState(false);\n\n useEffect(() => {\n async function fetchTaskSettings() {\n try {\n setLoading(true);\n const response = await fetch(`/api/projects/${projectId}/tasks`);\n if (!response.ok) {\n throw new Error(t('settings.fetchTasksFailed'));\n }\n\n const data = await response.json();\n\n // 如果没有配置,使用默认值\n if (Object.keys(data).length === 0) {\n setTaskSettings({\n ...DEFAULT_SETTINGS\n });\n } else {\n setTaskSettings({\n ...DEFAULT_SETTINGS,\n ...data\n });\n }\n } catch (error) {\n console.error('获取任务配置出错:', error);\n setError(error.message);\n } finally {\n setLoading(false);\n }\n }\n\n fetchTaskSettings();\n }, [projectId, t]);\n\n return {\n taskSettings,\n setTaskSettings,\n loading,\n error,\n success,\n setSuccess\n };\n}\n"], ["/easy-dataset/app/api/projects/[projectId]/split/route.js", "import { NextResponse } from 'next/server';\nimport { splitProjectFile, getProjectChunks } from '@/lib/file/text-splitter';\nimport { getProject, updateProject } from '@/lib/db/projects';\nimport { getTags } from '@/lib/db/tags';\nimport { handleDomainTree } from '@/lib/util/domain-tree';\n\n// 处理文本分割请求\nexport async function POST(request, { params }) {\n try {\n const { projectId } = params;\n\n // 获取请求体\n const { fileNames, model, language, domainTreeAction = 'rebuild' } = await request.json();\n\n if (!model) {\n return NextResponse.json({ error: 'Pelease Select Model' }, { status: 400 });\n }\n\n const project = await getProject(projectId);\n\n let result = {\n totalChunks: 0,\n chunks: [],\n toc: ''\n };\n for (let i = 0; i < fileNames.length; i++) {\n const fileName = fileNames[i];\n // 分割文本\n const { toc, chunks, totalChunks } = await splitProjectFile(projectId, fileName);\n result.toc += toc;\n result.chunks.push(...chunks);\n result.totalChunks += totalChunks;\n console.log(projectId, fileName, `Text split completed, ${domainTreeAction} domain tree`);\n }\n\n // 调用领域树处理模块\n const tags = await handleDomainTree({\n projectId,\n action: domainTreeAction,\n newToc: result.toc,\n model,\n language,\n fileNames,\n project\n });\n\n if (!tags && domainTreeAction !== 'keep') {\n await updateProject(projectId, { ...project });\n return NextResponse.json(\n { error: 'AI analysis failed, please check model configuration, delete file and retry!' },\n { status: 400 }\n );\n }\n\n return NextResponse.json({ ...result, tags });\n } catch (error) {\n console.error('Text split error:', String(error));\n return NextResponse.json({ error: error.message || 'Text split failed' }, { status: 500 });\n }\n}\n\n// 获取项目中的所有文本块\nexport async function GET(request, { params }) {\n try {\n const { projectId } = params;\n const { searchParams } = new URL(request.url);\n const filter = searchParams.get('filter');\n // 验证项目ID\n if (!projectId) {\n return NextResponse.json({ error: 'The project ID cannot be empty' }, { status: 400 });\n }\n\n // 获取文本块详细信息\n const result = await getProjectChunks(projectId, filter);\n\n const tags = await getTags(projectId);\n\n // 返回详细的文本块信息和文件结果(单个文件)\n return NextResponse.json({\n chunks: result.chunks,\n ...result.fileResult, // 单个文件结果,而不是数组\n tags\n });\n } catch (error) {\n console.error('Failed to get text chunks:', String(error));\n return NextResponse.json({ error: error.message || 'Failed to get text chunks' }, { status: 500 });\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/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/app/api/projects/[projectId]/llamaFactory/checkConfig/route.js", "import { NextResponse } from 'next/server';\nimport path from 'path';\nimport fs from 'fs';\nimport { getProjectRoot } from '@/lib/db/base';\n\nexport async function GET(request, { params }) {\n try {\n const { projectId } = params;\n if (!projectId) {\n return NextResponse.json({ error: 'The project ID cannot be empty' }, { status: 400 });\n }\n\n const projectRoot = await getProjectRoot();\n const projectPath = path.join(projectRoot, projectId);\n const configPath = path.join(projectPath, 'dataset_info.json');\n\n const exists = fs.existsSync(configPath);\n\n return NextResponse.json({\n exists,\n configPath: exists ? configPath : null\n });\n } catch (error) {\n console.error('Error checking Llama Factory config:', String(error));\n return NextResponse.json({ error: error.message }, { status: 500 });\n }\n}\n"], ["/easy-dataset/lib/llm/prompts/questionEn.js", "/**\n * Builds the GA prompt string.\n * @param {Object} activeGaPair - The currently active GA pair.\n * @returns {String} The constructed GA prompt string.\n */\nfunction buildGaPrompt(activeGaPair = null) {\n if (activeGaPair && activeGaPair.active) {\n return `\n## Special Requirements - Genre & Audience Perspective Questioning:\nAdjust your questioning approach and question style based on the following genre and audience combination:\n\n**Target Genre**: ${activeGaPair.genre}\n**Target Audience**: ${activeGaPair.audience}\n\nPlease ensure:\n1. The question should fully conform to the style, focus, depth, and other attributes defined by \"${activeGaPair.genre}\".\n2. The question should consider the knowledge level, cognitive characteristics, and potential points of interest of \"${activeGaPair.audience}\".\n3. Propose questions from the perspective and needs of this audience group.\n4. Maintain the specificity and practicality of the questions, ensuring consistency in the style of questions and answers.\n5. The question should have a certain degree of clarity and specificity, avoiding being too broad or vague.\n`;\n }\n\n return '';\n}\n\n/**\n * Question generation prompt template.\n * @param {string} text - The text to be processed.\n * @param {number} number - The number of questions.\n * @param {string} language - The language of the questions.\n * @param {string} globalPrompt - Global prompt for the LLM.\n * @param {string} questionPrompt - Specific prompt for question generation.\n * @param {Object} activeGaPair - The currently active GA pair.\n * @returns {string} The complete prompt for question generation.\n */\nmodule.exports = function getQuestionPrompt({\n text,\n number = Math.floor(text.length / 240),\n language = 'English',\n globalPrompt = '',\n questionPrompt = '',\n activeGaPair = null\n}) {\n if (globalPrompt) {\n globalPrompt = `In subsequent tasks, you must strictly follow these rules: ${globalPrompt}`;\n }\n if (questionPrompt) {\n questionPrompt = `- In generating questions, you must strictly follow these rules: ${questionPrompt}`;\n }\n\n // Build GA pairs related prompts\n const gaPrompt = buildGaPrompt(activeGaPair);\n\n return `\n # Role Mission\n You are a professional text analysis expert, skilled at extracting key information from complex texts and generating structured data(only generate questions) that can be used for model fine - tuning.\n ${globalPrompt}\n\n ## Core Task\n Based on the text provided by the user(length: ${text.length} characters), generate no less than ${number} high - quality questions.\n\n ## Constraints(Important!!!)\n ✔️ Must be directly generated based on the text content.\n ✔️ Questions should have a clear answer orientation.\n ✔️ Should cover different aspects of the text.\n ❌ It is prohibited to generate hypothetical, repetitive, or similar questions.\n\n ${gaPrompt}\n\n ## Processing Flow\n 1. 【Text Parsing】Process the content in segments, identify key entities and core concepts.\n 2. 【Question Generation】Select the best questioning points based on the information density${gaPrompt ? ', and incorporate the specified genre-audience perspective' : ''}\n 3. 【Quality Check】Ensure that:\n - The answers to the questions can be found in the original text.\n - The labels are strongly related to the question content.\n - There are no formatting errors.\n ${gaPrompt ? '- Question style matches the specified genre and audience' : ''}\n\n ## Output Format\n - The JSON array format must be correct.\n - Use English double - quotes for field names.\n - The output JSON array must strictly follow the following structure:\n \\`\\`\\`json\n [\"Question 1\", \"Question 2\", \"...\"]\n \\`\\`\\`\n\n ## Output Example\n \\`\\`\\`json\n [ \"What core elements should an AI ethics framework include?\", \"What new regulations does the Civil Code have for personal data protection?\"]\n \\`\\`\\`\n\n ## Text to be Processed\n ${text}\n\n ## Restrictions\n - Must output in the specified JSON format and do not output any other irrelevant content.\n - Generate no less than ${number} high - quality questions.\n - Questions should not be related to the material itself. For example, questions related to the author, chapters, table of contents, etc. are prohibited.\n ${questionPrompt}\n `;\n};\n"], ["/easy-dataset/lib/util/logger.js", "// lib/utils/logger.js\nconst isElectron = typeof process !== 'undefined' && process.versions && process.versions.electron;\n\nfunction log(level, ...args) {\n try {\n const message = args.map(arg => (typeof arg === 'object' ? JSON.stringify(arg) : arg)).join(' ');\n if (isElectron) {\n // 在 Electron 环境下,将日志写入文件\n const { ipcRenderer } = require('electron');\n ipcRenderer.send('log', { level, message });\n } else {\n // 在非 Electron 环境下,只输出到控制台\n console[level](...args);\n }\n } catch (error) {\n console.error('Failed to log:', error);\n }\n}\n\nexport default {\n info: (...args) => log('info', ...args),\n error: (...args) => log('error', ...args),\n warn: (...args) => log('warn', ...args),\n debug: (...args) => log('debug', ...args)\n};\n"], ["/easy-dataset/components/dataset-square/DatasetSearchBar.js", "'use client';\n\nimport { useState, useEffect, useRef } from 'react';\nimport {\n Box,\n TextField,\n InputAdornment,\n List,\n ListItem,\n ListItemButton,\n ListItemText,\n Paper,\n Typography,\n ClickAwayListener,\n Fade,\n Avatar,\n useTheme,\n alpha\n} from '@mui/material';\nimport SearchIcon from '@mui/icons-material/Search';\nimport LaunchIcon from '@mui/icons-material/Launch';\nimport TravelExploreIcon from '@mui/icons-material/TravelExplore';\nimport sites from '@/constant/sites.json';\nimport { useTranslation } from 'react-i18next';\n\nexport function DatasetSearchBar() {\n const [searchQuery, setSearchQuery] = useState('');\n const [showSuggestions, setShowSuggestions] = useState(false);\n const [recentSearches, setRecentSearches] = useState([]);\n const searchRef = useRef(null);\n const suggestionsRef = useRef(null);\n const theme = useTheme();\n const { t } = useTranslation();\n\n // 从 localStorage 加载最近搜索\n useEffect(() => {\n const savedSearches = localStorage.getItem('recentDatasetSearches');\n if (savedSearches) {\n try {\n const searches = JSON.parse(savedSearches);\n setRecentSearches(searches);\n } catch (e) {\n console.error('解析最近搜索失败', e);\n }\n }\n }, []);\n\n // 处理搜索输入变化\n const handleSearchChange = event => {\n setSearchQuery(event.target.value);\n if (event.target.value) {\n setShowSuggestions(true);\n } else {\n setShowSuggestions(false);\n }\n };\n\n // 处理回车搜索\n const handleSearchSubmit = event => {\n if (event.key === 'Enter' && searchQuery.trim()) {\n // 默认使用第一个搜索引擎\n if (sites.length > 0) {\n handleSuggestionClick(sites[0]);\n }\n }\n };\n\n // 保存最近搜索\n const saveRecentSearch = query => {\n if (!query.trim()) return;\n\n // 添加到最近搜索并去重\n const updatedSearches = [query, ...recentSearches.filter(s => s !== query)].slice(0, 5);\n setRecentSearches(updatedSearches);\n\n // 保存到 localStorage\n try {\n localStorage.setItem('recentDatasetSearches', JSON.stringify(updatedSearches));\n } catch (e) {\n console.error('保存最近搜索失败', e);\n }\n };\n\n // 处理点击搜索建议\n const handleSuggestionClick = site => {\n if (searchQuery.trim()) {\n // 根据不同网站处理搜索参数\n let searchUrl = site.link;\n\n // 如果链接中不包含问号,则添加搜索参数\n if (site.link.includes('huggingface.co')) {\n searchUrl = `${site.link}?sort=trending&search=${encodeURIComponent(searchQuery)}`;\n } else if (site.link.includes('kaggle.com')) {\n searchUrl = `${site.link}?search=${encodeURIComponent(searchQuery)}`;\n } else if (site.link.includes('datasetsearch.research.google.com')) {\n searchUrl = `${site.link}/search?query=${encodeURIComponent(searchQuery)}&src=0`;\n } else if (site.link.includes('paperswithcode.com')) {\n searchUrl = `${site.link}?q=${encodeURIComponent(searchQuery)}`;\n } else if (site.link.includes('modelscope.cn')) {\n searchUrl = `${site.link}?query=${encodeURIComponent(searchQuery)}`;\n } else if (site.link.includes('opendatalab.com')) {\n searchUrl = `${site.link}?keywords=${encodeURIComponent(searchQuery)}`;\n } else if (site.link.includes('tianchi.aliyun.com')) {\n searchUrl = `${site.link}?q=${encodeURIComponent(searchQuery)}`;\n } else {\n // 默认处理方式,在URL后添加搜索参数\n searchUrl = `${site.link}${site.link.includes('?') ? '&' : '?'}search=${encodeURIComponent(searchQuery)}`;\n }\n\n // 保存最近搜索\n saveRecentSearch(searchQuery);\n\n window.open(searchUrl, '_blank');\n }\n setShowSuggestions(false);\n };\n\n // 处理点击外部关闭建议\n const handleClickAway = event => {\n // 确保点击的不是建议框本身\n if (suggestionsRef.current && !suggestionsRef.current.contains(event.target)) {\n setShowSuggestions(false);\n }\n };\n\n return (\n \n \n searchQuery && setShowSuggestions(true)}\n InputProps={{\n startAdornment: (\n \n \n \n ),\n sx: {\n height: 56,\n borderRadius: 3,\n backgroundColor:\n theme.palette.mode === 'dark'\n ? alpha(theme.palette.background.default, 0.6)\n : alpha(theme.palette.background.default, 0.8),\n backdropFilter: 'blur(8px)',\n px: 2,\n transition: 'all 0.3s ease',\n boxShadow: `0 0 0 1px ${alpha(theme.palette.primary.main, 0.15)}`,\n '&.MuiOutlinedInput-root': {\n '& fieldset': {\n borderColor: 'transparent'\n },\n '&:hover fieldset': {\n borderColor: 'transparent'\n },\n '&.Mui-focused': {\n boxShadow: `0 0 0 2px ${alpha(theme.palette.primary.main, 0.3)}`,\n backgroundColor:\n theme.palette.mode === 'dark'\n ? alpha(theme.palette.background.paper, 0.8)\n : alpha(theme.palette.common.white, 0.95)\n },\n '&.Mui-focused fieldset': {\n borderColor: 'transparent'\n }\n }\n }\n }}\n sx={{\n mb: 1,\n '& .MuiInputBase-input': {\n fontSize: '1rem',\n fontWeight: 500,\n color: theme.palette.text.primary\n },\n '& .MuiInputBase-input::placeholder': {\n color: alpha(theme.palette.text.primary, 0.6),\n opacity: 0.7\n }\n }}\n />\n\n {/* 搜索建议下拉框 - 使用绝对定位确保不被裁剪 */}\n {showSuggestions && searchQuery && (\n \n \n \n \n {sites.slice(0, 5).map((site, index) => (\n \n handleSuggestionClick(site)}\n sx={{\n py: 1.5,\n '&:hover': {\n bgcolor: alpha(theme.palette.primary.main, 0.05)\n }\n }}\n >\n \n \n \n \n \n \n {t('datasetSquare.searchVia')} {site.name} Search\n \n \n \n \n \"{searchQuery}\"\n \n \n \n \n }\n />\n \n \n ))}\n \n \n \n \n )}\n \n \n );\n}\n"], ["/easy-dataset/electron/modules/menu.js", "const { Menu, dialog, shell, app } = require('electron');\nconst path = require('path');\nconst fs = require('fs');\nconst os = require('os');\nconst { getAppVersion } = require('../util');\n\n/**\n * 创建应用菜单\n * @param {BrowserWindow} mainWindow 主窗口\n * @param {Function} clearCache 清除缓存函数\n */\nfunction createMenu(mainWindow, clearCache) {\n const template = [\n {\n label: 'File',\n submenu: [{ role: 'quit', label: 'Quit' }]\n },\n {\n label: 'Edit',\n submenu: [\n { role: 'undo', label: 'Undo' },\n { role: 'redo', label: 'Redo' },\n { type: 'separator' },\n { role: 'cut', label: 'Cut' },\n { role: 'copy', label: 'Copy' },\n { role: 'paste', label: 'Paste' }\n ]\n },\n {\n label: 'View',\n submenu: [\n { role: 'reload', label: 'Refresh' },\n { type: 'separator' },\n { role: 'resetzoom', label: 'Reset Zoom' },\n { role: 'zoomin', label: 'Zoom In' },\n { role: 'zoomout', label: 'Zoom Out' },\n { type: 'separator' },\n { role: 'togglefullscreen', label: 'Fullscreen' }\n ]\n },\n {\n label: 'Help',\n submenu: [\n {\n label: 'About',\n click: () => {\n dialog.showMessageBox(mainWindow, {\n title: 'About Easy Dataset',\n message: `Easy Dataset v${getAppVersion()}`,\n detail: 'An application for creating fine-tuning datasets for large models.',\n buttons: ['OK']\n });\n }\n },\n {\n label: 'Visit GitHub',\n click: () => {\n shell.openExternal('https://github.com/ConardLi/easy-dataset');\n }\n }\n ]\n },\n {\n label: 'More',\n submenu: [\n { role: 'toggledevtools', label: 'Developer Tools' },\n {\n label: 'Open Logs Directory',\n click: () => {\n const logsDir = path.join(app.getPath('userData'), 'logs');\n if (!fs.existsSync(logsDir)) {\n fs.mkdirSync(logsDir, { recursive: true });\n }\n shell.openPath(logsDir);\n }\n },\n {\n label: 'Open Data Directory',\n click: () => {\n const dataDir = path.join(app.getPath('userData'), 'local-db');\n if (!fs.existsSync(dataDir)) {\n fs.mkdirSync(dataDir, { recursive: true });\n }\n shell.openPath(dataDir);\n }\n },\n {\n label: 'Open Data Directory (History)',\n click: () => {\n const dataDir = path.join(os.homedir(), '.easy-dataset-db');\n if (!fs.existsSync(dataDir)) {\n fs.mkdirSync(dataDir, { recursive: true });\n }\n shell.openPath(dataDir);\n }\n },\n {\n label: 'Clear Cache',\n click: async () => {\n try {\n const response = await dialog.showMessageBox(mainWindow, {\n type: 'question',\n buttons: ['Cancel', 'Confirm'],\n defaultId: 1,\n title: 'Clear Cache',\n message: 'Are you sure you want to clear the cache?',\n detail:\n 'This will delete all files in the logs directory and local database cache files (excluding main database files).'\n });\n\n if (response.response === 1) {\n // User clicked confirm\n await clearCache();\n dialog.showMessageBox(mainWindow, {\n type: 'info',\n title: 'Cleared Successfully',\n message: 'Cache has been cleared successfully'\n });\n }\n } catch (error) {\n global.appLog(`Failed to clear cache: ${error.message}`, 'error');\n dialog.showErrorBox('Failed to clear cache', error.message);\n }\n }\n }\n ]\n }\n ];\n\n const menu = Menu.buildFromTemplate(template);\n Menu.setApplicationMenu(menu);\n}\n\nmodule.exports = {\n createMenu\n};\n"], ["/easy-dataset/next.config.js", "// 最佳实践配置示例\nmodule.exports = {\n experimental: {\n serverComponentsExternalPackages: ['@opendocsg/pdf2md', 'pdfjs-dist', '@hyzyla/pdfium'],\n esmExternals: 'loose'\n },\n webpack: (config, { isServer }) => {\n if (!isServer) {\n config.externals.push({\n unpdf: 'window.unpdf',\n 'pdfjs-dist': 'window.pdfjsLib'\n });\n } else {\n config.externals.push('pdfjs-dist');\n config.externals.push('@hyzyla/pdfium');\n }\n return config;\n }\n};\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/lib/file/split-markdown/output/fileWriter.js", "/**\n * 文件输出模块\n */\n\nconst fs = require('fs');\nconst path = require('path');\nconst { ensureDirectoryExists } = require('../utils/common');\n\n/**\n * 将分割结果保存到单独的文件\n * @param {Array} splitResult - 分割结果数组\n * @param {string} baseFilename - 基础文件名(不包含扩展名)\n * @param {Function} callback - 回调函数\n */\nfunction saveToSeparateFiles(splitResult, baseFilename, callback) {\n // 获取基础目录和文件名(无扩展名)\n const basePath = path.dirname(baseFilename);\n const filenameWithoutExt = path.basename(baseFilename).replace(/\\.[^/.]+$/, '');\n\n // 创建用于存放分割文件的目录\n const outputDir = path.join(basePath, `${filenameWithoutExt}_parts`);\n\n // 确保目录存在\n ensureDirectoryExists(outputDir);\n\n // 递归保存文件\n function saveFile(index) {\n if (index >= splitResult.length) {\n // 所有文件保存完成\n callback(null, outputDir, splitResult.length);\n return;\n }\n\n const part = splitResult[index];\n const paddedIndex = String(index + 1).padStart(3, '0'); // 确保文件排序正确\n const outputFile = path.join(outputDir, `${filenameWithoutExt}_part${paddedIndex}.md`);\n\n // 将摘要和内容格式化为Markdown\n const content = `> **📑 Summarization:** *${part.summary}*\\n\\n---\\n\\n${part.content}`;\n\n fs.writeFile(outputFile, content, 'utf8', err => {\n if (err) {\n callback(err);\n return;\n }\n\n // 继续保存下一个文件\n saveFile(index + 1);\n });\n }\n\n // 开始保存文件\n saveFile(0);\n}\n\nmodule.exports = {\n saveToSeparateFiles\n};\n"], ["/easy-dataset/lib/db/chunks.js", "'use server';\nimport { db } from '@/lib/db/index';\nimport { ensureDir, getProjectRoot } from '@/lib/db/base';\nimport path from 'path';\nimport fs from 'fs';\n\nexport async function saveChunks(chunks) {\n try {\n return await db.chunks.createMany({ data: chunks });\n } catch (error) {\n console.error('Failed to create chunks in database');\n throw error;\n }\n}\n\nexport async function getChunkById(chunkId) {\n try {\n return await db.chunks.findUnique({ where: { id: chunkId } });\n } catch (error) {\n console.error('Failed to get chunks by id in database');\n throw error;\n }\n}\n\nexport async function getChunksByFileIds(fileIds) {\n try {\n return await db.chunks.findMany({\n where: { fileId: { in: fileIds } },\n include: {\n Questions: {\n select: {\n question: true\n }\n }\n }\n });\n } catch (error) {\n console.error('Failed to get chunks by id in database');\n throw error;\n }\n}\n\n// 获取项目中所有文本片段的ID\nexport async function getChunkByProjectId(projectId, filter) {\n try {\n const whereClause = {\n projectId,\n NOT: {\n name: {\n contains: 'Distilled Content'\n }\n }\n };\n if (filter === 'generated') {\n whereClause.Questions = {\n some: {}\n };\n } else if (filter === 'ungenerated') {\n whereClause.Questions = {\n none: {}\n };\n }\n return await db.chunks.findMany({\n where: whereClause,\n include: {\n Questions: {\n select: {\n question: true\n }\n }\n }\n });\n } catch (error) {\n console.error('Failed to get chunks by projectId in database');\n throw error;\n }\n}\n\nexport async function deleteChunkById(chunkId) {\n try {\n const delQuestions = db.questions.deleteMany({ where: { chunkId } });\n const delChunk = db.chunks.delete({ where: { id: chunkId } });\n return await db.$transaction([delQuestions, delChunk]);\n } catch (error) {\n console.error('Failed to delete chunks by id in database');\n throw error;\n }\n}\n\n/**\n * 根据文本块名称获取文本块\n * @param {string} projectId - 项目ID\n * @param {string} chunkName - 文本块名称\n * @returns {Promise} - 查询结果\n */\nexport async function getChunkByName(projectId, chunkName) {\n try {\n return await db.chunks.findFirst({\n where: {\n projectId,\n name: chunkName\n }\n });\n } catch (error) {\n console.error('根据名称获取文本块失败', error);\n throw error;\n }\n}\n\n/**\n * 根据文件ID删除所有相关文本块\n * @param {string} projectId - 项目ID\n * @param {string} fileId - 文件ID\n * @returns {Promise} - 删除操作的结果\n */\nexport async function deleteChunksByFileId(projectId, fileId) {\n try {\n // 查找与该文件相关的所有文本块\n const chunks = await db.chunks.findMany({\n where: { projectId, fileId },\n select: { id: true }\n });\n\n // 提取文本块ID\n const chunkIds = chunks.map(chunk => chunk.id);\n\n // 如果没有找到文本块,直接返回\n if (chunkIds.length === 0) {\n return { count: 0 };\n }\n\n // 删除相关的问题\n const delQuestions = db.questions.deleteMany({\n where: { chunkId: { in: chunkIds } }\n });\n\n // 删除文本块\n const delChunks = db.chunks.deleteMany({\n where: { id: { in: chunkIds } }\n });\n\n // 使用事务确保原子性操作\n const result = await db.$transaction([delQuestions, delChunks]);\n\n return { count: result[1].count };\n } catch (error) {\n console.error('删除文件相关文本块失败:', error);\n throw error;\n }\n}\n\nexport async function updateChunkById(chunkId, chunkData) {\n try {\n return await db.chunks.update({ where: { id: chunkId }, data: chunkData });\n } catch (error) {\n console.error('Failed to update chunks by id in database');\n throw error;\n }\n}\n\n// 删除文件及相关TOC文件\n// TODO 后期优化 将文件也新增表结构关联 防止删除错误\nexport async function deleteChunkAndFile(projectId, fileName) {\n try {\n const projectRoot = await getProjectRoot();\n const projectPath = path.join(projectRoot, projectId);\n const filesDir = path.join(projectPath, 'files');\n const tocDir = path.join(projectPath, 'toc');\n\n // 确保目录存在\n await ensureDir(tocDir);\n\n // 删除原始文件\n const filePath = path.join(filesDir, fileName);\n try {\n await fs.promises.access(filePath);\n await fs.promises.unlink(filePath);\n } catch (error) {\n console.error(`删除文件 ${fileName} 失败:`, error);\n // 如果文件不存在,继续处理\n }\n\n // 删除相关的TOC文件\n const baseName = path.basename(fileName, path.extname(fileName));\n const tocPath = path.join(filesDir, `${baseName}-toc.json`);\n try {\n await fs.promises.access(tocPath);\n await fs.promises.unlink(tocPath);\n } catch (error) {\n // 如果TOC文件不存在,继续处理\n }\n\n // TODO 暂不删除数据库中Chunk数据 如果删除 Question Dataset关联的Chunk数据是否也要删除?\n // return await db.chunks.deleteMany({\n // where: {\n // name: {\n // startsWith: baseName + '-part-',\n // }, projectId\n // }\n // });\n } catch (error) {\n console.error('Failed to delete chunks by id in database');\n throw error;\n }\n}\n"], ["/easy-dataset/app/api/projects/[projectId]/models/[modelId]/route.js", "import { NextResponse } from 'next/server';\nimport { getProjectRoot } from '@/lib/db/base';\nimport path from 'path';\nimport fs from 'fs/promises';\n\nexport async function GET(request, { params }) {\n try {\n const { projectId, modelId } = params;\n\n // 验证项目ID和模型ID\n if (!projectId || !modelId) {\n return NextResponse.json({ error: 'The project ID and model ID cannot be empty' }, { status: 400 });\n }\n\n // 获取项目根目录\n const projectRoot = await getProjectRoot();\n const projectPath = path.join(projectRoot, projectId);\n\n // 检查项目是否存在\n try {\n await fs.access(projectPath);\n } catch (error) {\n return NextResponse.json({ error: 'The project does not exist' }, { status: 404 });\n }\n\n // 获取模型配置文件路径\n const modelConfigPath = path.join(projectPath, 'model-config.json');\n\n // 检查模型配置文件是否存在\n try {\n await fs.access(modelConfigPath);\n } catch (error) {\n return NextResponse.json({ error: 'The model configuration does not exist' }, { status: 404 });\n }\n\n // 读取模型配置文件\n const modelConfigData = await fs.readFile(modelConfigPath, 'utf-8');\n const modelConfig = JSON.parse(modelConfigData);\n\n // 查找指定ID的模型\n const model = modelConfig.find(model => model.id === modelId);\n\n if (!model) {\n return NextResponse.json({ error: 'The model does not exist' }, { status: 404 });\n }\n\n return NextResponse.json(model);\n } catch (error) {\n console.error('Error getting model:', String(error));\n return NextResponse.json({ error: 'Failed to get model' }, { status: 500 });\n }\n}\n\nexport async function PUT(request, { params }) {\n try {\n const { projectId, modelId } = params;\n\n // 验证项目ID和模型ID\n if (!projectId || !modelId) {\n return NextResponse.json({ error: 'The project ID and model ID cannot be empty' }, { status: 400 });\n }\n\n // 获取请求体\n const modelData = await request.json();\n\n // 验证请求体\n if (!modelData || !modelData.provider || !modelData.name) {\n return NextResponse.json({ error: 'The model data is incomplete' }, { status: 400 });\n }\n\n // 获取项目根目录\n const projectRoot = await getProjectRoot();\n const projectPath = path.join(projectRoot, projectId);\n\n // 检查项目是否存在\n try {\n await fs.access(projectPath);\n } catch (error) {\n return NextResponse.json({ error: 'The project does not exist' }, { status: 404 });\n }\n\n // 获取模型配置文件路径\n const modelConfigPath = path.join(projectPath, 'model-config.json');\n\n // 读取模型配置文件\n let modelConfig = [];\n try {\n const modelConfigData = await fs.readFile(modelConfigPath, 'utf-8');\n modelConfig = JSON.parse(modelConfigData);\n } catch (error) {\n // 如果文件不存在,创建一个空数组\n }\n\n // 更新模型数据\n const modelIndex = modelConfig.findIndex(model => model.id === modelId);\n\n if (modelIndex >= 0) {\n // 更新现有模型\n modelConfig[modelIndex] = {\n ...modelConfig[modelIndex],\n ...modelData,\n id: modelId // 确保ID不变\n };\n } else {\n // 添加新模型\n modelConfig.push({\n ...modelData,\n id: modelId\n });\n }\n\n // 写入模型配置文件\n await fs.writeFile(modelConfigPath, JSON.stringify(modelConfig, null, 2), 'utf-8');\n\n return NextResponse.json({ message: 'Model configuration updated successfully' });\n } catch (error) {\n console.error('Error updating model configuration:', String(error));\n return NextResponse.json({ error: 'Failed to update model configuration' }, { status: 500 });\n }\n}\n\nexport async function DELETE(request, { params }) {\n try {\n const { projectId, modelId } = params;\n\n // 验证项目ID和模型ID\n if (!projectId || !modelId) {\n return NextResponse.json({ error: 'The project ID and model ID cannot be empty' }, { status: 400 });\n }\n\n // 获取项目根目录\n const projectRoot = await getProjectRoot();\n const projectPath = path.join(projectRoot, projectId);\n\n // 检查项目是否存在\n try {\n await fs.access(projectPath);\n } catch (error) {\n return NextResponse.json({ error: 'The project does not exist' }, { status: 404 });\n }\n\n // 获取模型配置文件路径\n const modelConfigPath = path.join(projectPath, 'model-config.json');\n\n // 检查模型配置文件是否存在\n try {\n await fs.access(modelConfigPath);\n } catch (error) {\n return NextResponse.json({ error: 'The model configuration does not exist' }, { status: 404 });\n }\n\n // 读取模型配置文件\n const modelConfigData = await fs.readFile(modelConfigPath, 'utf-8');\n let modelConfig = JSON.parse(modelConfigData);\n\n // 过滤掉要删除的模型\n const initialLength = modelConfig.length;\n modelConfig = modelConfig.filter(model => model.id !== modelId);\n\n // 检查是否找到并删除了模型\n if (modelConfig.length === initialLength) {\n return NextResponse.json({ error: 'The model does not exist' }, { status: 404 });\n }\n\n // 写入模型配置文件\n await fs.writeFile(modelConfigPath, JSON.stringify(modelConfig, null, 2), 'utf-8');\n\n return NextResponse.json({ message: 'Model deleted successfully' });\n } catch (error) {\n console.error('Error deleting model:', String(error));\n return NextResponse.json({ error: 'Failed to delete model' }, { status: 500 });\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/lib/db/files.js", "/**\n * 文件操作辅助函数\n */\nconst path = require('path');\nconst { promises: fs } = require('fs');\nconst { getProjectRoot, readJSON } = require('./base');\nconst { getProject } = require('./projects');\nconst { getUploadFileInfoById } = require('./upload-files');\n\n/**\n * 获取项目文件内容\n * @param {string} projectId - 项目ID\n * @param {string} fileName - 文件名\n * @returns {Promise} 文件内容\n */\nasync function getProjectFileContent(projectId, fileName) {\n try {\n // 获取项目根目录\n const projectRoot = await getProjectRoot();\n const projectPath = path.join(projectRoot, projectId);\n const filePath = path.join(projectPath, 'files', fileName);\n\n // 读取文件内容\n const content = await fs.readFile(filePath, 'utf-8');\n return content;\n } catch (error) {\n console.error('获取项目文件内容失败:', error);\n return '';\n }\n}\n\n/**\n * 根据文件ID获取项目文件内容\n * @param {string} projectId - 项目ID\n * @param {string} fileId - 文件ID\n * @returns {Promise} 文件内容\n */\nasync function getProjectFileContentById(projectId, fileId) {\n try {\n // 获取文件信息\n const fileInfo = await getUploadFileInfoById(fileId);\n if (!fileInfo) {\n throw new Error('文件不存在');\n }\n\n // 获取项目根目录\n const projectRoot = await getProjectRoot();\n const projectPath = path.join(projectRoot, projectId);\n const filePath = path.join(projectPath, 'files', fileInfo.fileName);\n\n // 读取文件内容\n const content = await fs.readFile(filePath, 'utf-8');\n return content;\n } catch (error) {\n console.error('根据ID获取项目文件内容失败:', error);\n return '';\n }\n}\n\nmodule.exports = {\n getProjectFileContent,\n getProjectFileContentById\n};\n"], ["/easy-dataset/lib/llm/prompts/answerEn.js", "module.exports = function getAnswerPrompt({\n text,\n question,\n language = 'English',\n globalPrompt = '',\n answerPrompt = ''\n}) {\n if (globalPrompt) {\n globalPrompt = `In subsequent tasks, you must strictly follow these rules: ${globalPrompt}`;\n }\n if (answerPrompt) {\n answerPrompt = `In generating answers, you must strictly follow these rules: ${answerPrompt}`;\n }\n\n return `\n# Role: Fine-tuning Dataset Generation Expert\n## Profile:\n- Description: You are an expert in generating fine-tuning datasets, skilled at generating accurate answers to questions from the given content, ensuring the accuracy and relevance of the answers.\n${globalPrompt}\n\n## Skills:\n1. The answer must be based on the given content.\n2. The answer must be accurate and not fabricated.\n3. The answer must be relevant to the question.\n4. The answer must be logical.\n\n## Workflow:\n1. Take a deep breath and work on this problem step-by-step.\n2. First, analyze the given file content.\n3. Then, extract key information from the content.\n4. Next, generate an accurate answer related to the question.\n5. Finally, ensure the accuracy and relevance of the answer.\n\n## Reference Content:\n${text}\n\n## Question\n${question}\n\n## Constrains:\n1. The answer must be based on the given content.\n2. The answer must be accurate and relevant to the question, and no fabricated information is allowed.\n3. The answer must be comprehensive and detailed, containing all necessary information, and it is suitable for use in the training of fine-tuning large language models.\n ${answerPrompt}\n`;\n};\n"], ["/easy-dataset/app/projects/[projectId]/text-split/useFileProcessing.js", "'use client';\n\nimport { useState, useCallback } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { selectedModelInfoAtom } from '@/lib/store';\nimport { useAtomValue } from 'jotai/index';\nimport { toast } from 'sonner';\nimport i18n from '@/lib/i18n';\nimport axios from 'axios';\n\n/**\n * 文件处理的自定义Hook\n * @param {string} projectId - 项目ID\n * @returns {Object} - 文件处理状态和操作方法\n */\nexport default function useFileProcessing(projectId) {\n const { t } = useTranslation();\n const [fileProcessing, setFileProcessing] = useState(false);\n const [progress, setProgress] = useState({\n total: 0,\n completed: 0,\n percentage: 0,\n questionCount: 0\n });\n const model = useAtomValue(selectedModelInfoAtom);\n\n /**\n * 重置进度状态\n */\n const resetProgress = useCallback(() => {\n setTimeout(() => {\n setProgress({\n total: 0,\n completed: 0,\n percentage: 0,\n questionCount: 0\n });\n }, 1000); // 延迟重置,让用户看到完成的进度\n }, []);\n\n /**\n * 处理文件\n * @param {Array} files - 文件列表\n * @param {string} pdfStrategy - PDF处理策略\n * @param {string} selectedViosnModel - 选定的视觉模型\n */\n const handleFileProcessing = useCallback(\n async (files, pdfStrategy, selectedViosnModel, domainTreeAction) => {\n try {\n const currentLanguage = i18n.language === 'zh-CN' ? '中文' : 'en';\n\n //获取到视觉策略要使用的模型\n const availableModels = JSON.parse(localStorage.getItem('modelConfigList'));\n const vsionModel = availableModels.find(m => m.id === selectedViosnModel);\n\n const response = await axios.post(`/api/projects/${projectId}/tasks`, {\n taskType: 'file-processing',\n modelInfo: localStorage.getItem('selectedModelInfo'),\n language: currentLanguage,\n detail: '文件处理任务',\n note: {\n vsionModel,\n projectId,\n fileList: files,\n strategy: pdfStrategy,\n domainTreeAction\n }\n });\n\n if (response.data?.code !== 0) {\n throw new Error(t('textSplit.pdfProcessingFailed') + (response.data?.error || ''));\n }\n\n //提示后台任务进行中\n toast.success(t('textSplit.pdfProcessingToast'));\n } catch (error) {\n toast.error(t('textSplit.pdfProcessingFailed') + error.message || '');\n }\n },\n [projectId, t, resetProgress]\n );\n\n return {\n fileProcessing,\n progress,\n setFileProcessing,\n setProgress,\n handleFileProcessing,\n resetProgress\n };\n}\n"], ["/easy-dataset/components/TaskIcon.js", "'use client';\n\nimport React, { useState, useEffect } from 'react';\nimport { Badge, IconButton, Tooltip, Box, CircularProgress } from '@mui/material';\nimport TaskAltIcon from '@mui/icons-material/TaskAlt';\nimport { useTranslation } from 'react-i18next';\nimport { useRouter } from 'next/navigation';\nimport useFileProcessingStatus from '@/hooks/useFileProcessingStatus';\nimport axios from 'axios';\n\n// 任务图标组件\nexport default function TaskIcon({ projectId, theme }) {\n const { t } = useTranslation();\n const router = useRouter();\n const [tasks, setTasks] = useState([]);\n const [polling, setPolling] = useState(false);\n const { setTaskFileProcessing, setTask } = useFileProcessingStatus();\n\n // 获取项目的未完成任务列表\n const fetchPendingTasks = async () => {\n if (!projectId) return;\n\n try {\n const response = await axios.get(`/api/projects/${projectId}/tasks/list?status=0`);\n if (response.data?.code === 0) {\n const tasks = response.data.data || [];\n setTasks(tasks);\n // 检查是否有文件处理任务正在进行\n const hasActiveFileTask = tasks.some(\n task => task.projectId === projectId && task.taskType === 'file-processing'\n );\n setTaskFileProcessing(hasActiveFileTask);\n //存在文件处理任务,将任务信息传递给共享状态\n if (hasActiveFileTask) {\n const activeTask = tasks.find(task => task.projectId === projectId && task.taskType === 'file-processing');\n // 解析任务详情信息\n const detailInfo = JSON.parse(activeTask.detail);\n setTask(detailInfo);\n }\n }\n } catch (error) {\n console.error('获取任务列表失败:', error);\n }\n };\n\n // 初始化时获取任务列表\n useEffect(() => {\n if (projectId) {\n fetchPendingTasks();\n\n // 启动轮询\n const intervalId = setInterval(() => {\n fetchPendingTasks();\n }, 10000); // 每10秒轮询一次\n\n setPolling(true);\n\n return () => {\n clearInterval(intervalId);\n setPolling(false);\n };\n }\n }, [projectId]);\n\n // 打开任务列表页面\n const handleOpenTaskList = () => {\n router.push(`/projects/${projectId}/tasks`);\n };\n\n // 图标渲染逻辑\n const renderTaskIcon = () => {\n const pendingTasks = tasks.filter(task => task.status === 0);\n\n if (pendingTasks.length > 0) {\n // 当有任务处理中时,显示 loading 状态同时保留徽标\n return (\n \n \n \n );\n }\n\n // 没有处理中的任务时,显示完成图标\n return ;\n };\n\n // 悬停提示文本\n const getTooltipText = () => {\n const pendingTasks = tasks.filter(task => task.status === 0);\n\n if (pendingTasks.length > 0) {\n return t('tasks.pending', { count: pendingTasks.length });\n }\n\n return t('tasks.completed');\n };\n\n if (!projectId) return null;\n\n return (\n \n \n {renderTaskIcon()}\n \n \n );\n}\n"], ["/easy-dataset/components/settings/TaskSettings.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 Slider,\n InputAdornment,\n Alert,\n Snackbar,\n FormControl,\n Select,\n InputLabel,\n MenuItem,\n Chip,\n FormHelperText\n} from '@mui/material';\nimport { useTranslation } from 'react-i18next';\n\nimport SaveIcon from '@mui/icons-material/Save';\nimport useTaskSettings from '@/hooks/useTaskSettings';\n\nexport default function TaskSettings({ projectId }) {\n const { t } = useTranslation();\n const { taskSettings, setTaskSettings, loading, error, success, setSuccess } = useTaskSettings(projectId);\n // 处理设置变更\n const handleSettingChange = e => {\n const { name, value } = e.target;\n setTaskSettings(prev => ({\n ...prev,\n [name]: value\n }));\n };\n\n // 处理滑块变更\n const handleSliderChange = name => (event, newValue) => {\n setTaskSettings(prev => ({\n ...prev,\n [name]: newValue\n }));\n };\n\n // 保存任务配置\n const handleSaveTaskSettings = async () => {\n try {\n // 确保数组类型的数据被正确处理\n const settingsToSave = { ...taskSettings };\n\n // 确保递归分块的分隔符数组存在\n if (settingsToSave.splitType === 'recursive' && settingsToSave.separatorsInput) {\n if (!settingsToSave.separators || !Array.isArray(settingsToSave.separators)) {\n settingsToSave.separators = settingsToSave.separatorsInput.split(',').map(item => item.trim());\n }\n }\n\n console.log('Saving settings:', settingsToSave);\n\n const response = await fetch(`/api/projects/${projectId}/tasks`, {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(settingsToSave)\n });\n\n if (!response.ok) {\n throw new Error(t('settings.saveTasksFailed'));\n }\n\n setSuccess(true);\n } catch (error) {\n console.error('保存任务配置出错:', error);\n //setError(error.message);\n }\n };\n\n const handleCloseSnackbar = () => {\n setSuccess(false);\n //setError(null);\n };\n\n if (loading) {\n return {t('common.loading')};\n }\n\n return (\n \n {' '}\n {/* 添加底部填充,为固定按钮留出空间 */}\n \n \n \n \n \n {t('settings.textSplitSettings')}\n \n \n {/* 分块策略选择 */}\n \n {t('settings.splitType')}\n \n \n \n {t('settings.splitTypeMarkdown')}\n \n {t('settings.splitTypeMarkdownDesc')}\n \n \n \n \n \n {t('settings.splitTypeRecursive')}\n \n {t('settings.splitTypeRecursiveDesc')}\n \n \n \n \n \n {t('settings.splitTypeText')}\n \n {t('settings.splitTypeTextDesc')}\n \n \n \n \n \n {t('settings.splitTypeToken')}\n \n {t('settings.splitTypeTokenDesc')}\n \n \n \n \n \n {t('settings.splitTypeCode')}\n \n {t('settings.splitTypeCodeDesc')}\n \n \n \n \n \n\n {/* Markdown模式设置 */}\n {(!taskSettings.splitType || taskSettings.splitType === 'markdown') && (\n <>\n \n {t('settings.minLength')}: {taskSettings.textSplitMinLength}\n \n \n\n \n {t('settings.maxLength')}: {taskSettings.textSplitMaxLength}\n \n \n \n )}\n\n {/* 通用 LangChain 参数设置 */}\n {taskSettings.splitType && taskSettings.splitType !== 'markdown' && (\n <>\n \n {t('settings.chunkSize')}: {taskSettings.chunkSize || 1500}\n \n \n\n \n {t('settings.chunkOverlap')}: {taskSettings.chunkOverlap || 200}\n \n \n \n )}\n\n {/* Text 分块器特殊设置 */}\n {taskSettings.splitType === 'text' && (\n \n )}\n\n {/* Code 分块器特殊设置 */}\n {taskSettings.splitType === 'code' && (\n \n {t('settings.codeLanguage')}\n \n JavaScript\n Python\n Java\n Go\n Ruby\n C++\n C\n C#\n PHP\n Rust\n TypeScript\n Swift\n Kotlin\n Scala\n \n {t('settings.codeLanguageHelper')}\n \n )}\n\n {/* Recursive 分块器特殊设置 */}\n {taskSettings.splitType === 'recursive' && (\n \n {t('settings.separators')}\n ,-'}\n onChange={e => {\n const value = e.target.value;\n // 同时更新输入框值和分隔符数组\n setTaskSettings(prev => ({\n ...prev,\n separatorsInput: value,\n separators: value.split(',').map(item => item.trim())\n }));\n }}\n helperText={t('settings.separatorsHelper')}\n />\n \n {(taskSettings.separators || ['|', '##', '>', '-']).map((sep, index) => (\n \n ))}\n \n \n )}\n\n \n {t('settings.textSplitDescription')}\n \n \n \n \n \n \n \n \n \n \n \n {t('settings.questionGenSettings')}\n \n \n \n {t('settings.questionGenLength', { length: taskSettings.questionGenerationLength })}\n \n \n \n {t('settings.questionGenDescription')}\n \n\n \n {t('settings.questionMaskRemovingProbability', {\n probability: taskSettings.questionMaskRemovingProbability\n })}\n \n \n\n \n \n \n \n \n \n \n \n \n \n \n {t('settings.pdfSettings')}\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n {t('settings.datasetUpload')}\n \n hf_\n }}\n />\n \n \n \n \n \n \n {t('settings.saveSuccess')}\n \n \n \n \n {error}\n \n \n {/* 吸底保存按钮 */}\n \n }\n onClick={handleSaveTaskSettings}\n >\n {t('settings.saveTaskConfig')}\n \n \n \n );\n}\n"], ["/easy-dataset/lib/llm/prompts/distillQuestionsEn.js", "function removeLeadingNumber(label) {\n // 正则说明:\n // ^\\d+ 匹配开头的一个或多个数字\n // (?:\\.\\d+)* 匹配零个或多个「点+数字」的组合(非捕获组)\n // \\s+ 匹配序号后的一个或多个空格(确保序号与内容有空格分隔)\n const numberPrefixRegex = /^\\d+(?:\\.\\d+)*\\s+/;\n // 仅当匹配到数字开头的序号时才替换,否则返回原标签\n return label.replace(numberPrefixRegex, '');\n}\n\n/**\n * 根据标签构造问题的提示词\n * @param {string} tagPath - 标签链路,例如 \"体育->足球->足球先生\"\n * @param {string} currentTag - 当前子标签,例如 \"足球先生\"\n * @param {number} count - 希望生成问题的数量,例如:10\n * @param {Array} existingQuestions - 当前标签已经生成的问题(避免重复)\n * @param {string} globalPrompt - 项目全局提示词\n * @returns {string} 提示词\n */\nexport function distillQuestionsEnPrompt(tagPath, currentTag, count = 10, existingQuestions = [], globalPrompt = '') {\n currentTag = removeLeadingNumber(currentTag);\n const existingQuestionsText =\n existingQuestions.length > 0\n ? `Existing questions include:\\n${existingQuestions.map(q => `- ${q}`).join('\\n')}\\nPlease do not generate questions that are repetitive or highly similar to these.`\n : '';\n\n // 构建全局提示词部分\n const globalPromptText = globalPrompt ? `You must adhere to this requirement: ${globalPrompt}` : '';\n\n return `\nYou are a professional knowledge question generation assistant, proficient in the field of ${currentTag}. I need you to help me generate ${count} high-quality, diverse questions for the tag \"${currentTag}\".\n\nThe complete tag path is: ${tagPath}\n\nPlease follow these rules:\n${globalPromptText}\n1. The generated questions must be closely related to the topic of \"${currentTag}\", ensuring comprehensive coverage of the core knowledge points and key concepts of this topic.\n2. Questions should be evenly distributed across the following difficulty levels (each level should account for at least 20%):\n - Basic: Suitable for beginners, focusing on basic concepts, definitions, and simple applications.\n - Intermediate: Requires some domain knowledge, involving principle explanations, case analyses, and application scenarios.\n - Advanced: Requires in-depth thinking, including cutting-edge developments, cross-domain connections, complex problem solutions, etc.\n\n3. Question types should be diverse, including but not limited to (the following are just references and can be adjusted flexibly according to the actual situation; there is no need to limit to the following topics):\n - Conceptual explanation: \"What is...\", \"How to define...\"\n - Principle analysis: \"Why...\", \"How to explain...\"\n - Comparison and contrast: \"What is the difference between... and...\", \"What are the advantages of... compared to...\"\n - Application practice: \"How to apply... to solve...\", \"What is the best practice for...\"\n - Development trends: \"What is the future development direction of...\", \"What challenges does... face?\"\n - Case analysis: \"Please analyze... in the case of...\"\n - Thought-provoking: \"What would happen if...\", \"How to evaluate...\"\n\n4. Question phrasing should be clear, accurate, and professional. Avoid the following:\n - Avoid vague or overly broad phrasing.\n - Avoid closed-ended questions that can be answered with \"yes/no\".\n - Avoid questions containing misleading assumptions.\n - Avoid repetitive or highly similar questions.\n\n5. The depth and breadth of questions should be appropriate:\n - Cover the history, current situation, theoretical basis, and practical applications of the topic.\n - Include mainstream views and controversial topics in the field.\n - Consider the cross-associations between this topic and related fields.\n - Focus on emerging technologies, methods, or trends in this field.\n\n${existingQuestionsText}\n\nPlease directly return the questions in the format of a JSON array, without any additional explanations or notes, in the following format:\n[\"Question 1\", \"Question 2\", \"Question 3\", ...]\n\nNote: Each question should be complete and self-contained, understandable and answerable without relying on other contexts.\n`;\n}\n"], ["/easy-dataset/components/text-split/components/UploadArea.js", "'use client';\n\nimport {\n Box,\n Button,\n Typography,\n List,\n ListItem,\n ListItemText,\n Divider,\n CircularProgress,\n Tooltip\n} from '@mui/material';\nimport UploadFileIcon from '@mui/icons-material/UploadFile';\nimport DeleteIcon from '@mui/icons-material/Delete';\nimport { alpha } from '@mui/material/styles';\nimport { useTranslation } from 'react-i18next';\nimport React, { useRef, useState } from 'react';\n\nexport default function UploadArea({\n theme,\n files,\n uploading,\n uploadedFiles,\n onFileSelect,\n onRemoveFile,\n onUpload,\n selectedModel\n}) {\n const { t } = useTranslation();\n const [dragActive, setDragActive] = useState(false);\n const inputRef = useRef(null);\n\n // 拖拽进入\n const handleDragOver = e => {\n e.preventDefault();\n e.stopPropagation();\n if (!dragActive) setDragActive(true);\n };\n // 拖拽离开\n const handleDragLeave = e => {\n e.preventDefault();\n e.stopPropagation();\n setDragActive(false);\n };\n // 拖拽释放\n const handleDrop = e => {\n e.preventDefault();\n e.stopPropagation();\n setDragActive(false);\n if (!selectedModel?.id || uploading) return;\n const files = e.dataTransfer.files;\n if (files && files.length > 0) {\n // 构造一个模拟的 event 以复用 onFileSelect\n const event = { target: { files } };\n onFileSelect(event);\n }\n };\n\n return (\n \n {dragActive && (\n \n \n \n \n {t('textSplit.dragToUpload', { defaultValue: '拖拽文件到此处上传' })}\n \n \n \n )}\n \n {t('textSplit.uploadNewDocument')}\n \n\n \n \n }\n sx={{ mb: 2, mt: 2 }}\n disabled={!selectedModel?.id || uploading}\n >\n {t('textSplit.selectFile')}\n \n \n \n \n\n \n {uploadedFiles.total > 0 ? t('textSplit.mutilFileMessage') : t('textSplit.supportedFormats')}\n \n\n {files.length > 0 && (\n \n \n {t('textSplit.selectedFiles', { count: files.length })}\n \n\n \n {files.map((file, index) => (\n \n }\n onClick={() => onRemoveFile(index)}\n disabled={uploading}\n >\n {t('common.delete')}\n \n }\n >\n \n \n {index < files.length - 1 && }\n \n ))}\n \n\n \n \n \n \n {uploading ? : t('textSplit.uploadAndProcess')}\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/export/HuggingFaceTab.js", "// HuggingFaceTab.js 组件\nimport React, { useState, useEffect } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport {\n Typography,\n Box,\n TextField,\n Button,\n FormControlLabel,\n Checkbox,\n Alert,\n CircularProgress,\n Divider,\n Paper,\n Grid,\n Tooltip,\n IconButton,\n Link\n} from '@mui/material';\nimport InfoIcon from '@mui/icons-material/Info';\nimport HelpOutlineIcon from '@mui/icons-material/HelpOutline';\nimport CheckCircleOutlineIcon from '@mui/icons-material/CheckCircleOutline';\n\nconst HuggingFaceTab = ({\n projectId,\n systemPrompt,\n confirmedOnly,\n includeCOT,\n formatType,\n fileFormat,\n customFields,\n handleSystemPromptChange,\n handleConfirmedOnlyChange,\n handleIncludeCOTChange\n}) => {\n const { t } = useTranslation();\n const [token, setToken] = useState('');\n const [datasetName, setDatasetName] = useState('');\n const [isPrivate, setIsPrivate] = useState(false);\n const [uploading, setUploading] = useState(false);\n const [error, setError] = useState('');\n const [success, setSuccess] = useState(false);\n const [datasetUrl, setDatasetUrl] = useState('');\n const [hasToken, setHasToken] = useState(false);\n const [loading, setLoading] = useState(true);\n\n // 从配置中获取 huggingfaceToken\n useEffect(() => {\n if (projectId) {\n setLoading(true);\n fetch(`/api/projects/${projectId}/config`)\n .then(res => res.json())\n .then(data => {\n if (data.huggingfaceToken) {\n setToken(data.huggingfaceToken);\n setHasToken(true);\n }\n setLoading(false);\n })\n .catch(err => {\n console.error('获取 HuggingFace Token 失败:', err);\n setLoading(false);\n });\n }\n }, [projectId]);\n\n // 处理上传数据集到 HuggingFace\n const handleUpload = async () => {\n if (!hasToken) {\n return;\n }\n\n if (!datasetName) {\n setError('请输入数据集名称');\n return;\n }\n\n try {\n setUploading(true);\n setError('');\n setSuccess(false);\n\n const response = await fetch(`/api/projects/${projectId}/huggingface/upload`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n token,\n datasetName,\n isPrivate,\n formatType,\n systemPrompt,\n confirmedOnly,\n includeCOT,\n fileFormat,\n customFields: formatType === 'custom' ? customFields : undefined\n })\n });\n\n const data = await response.json();\n if (!response.ok) {\n throw new Error(data.error || '上传失败');\n }\n\n setSuccess(true);\n setDatasetUrl(data.url);\n } catch (err) {\n setError(err.message);\n } finally {\n setUploading(false);\n }\n };\n\n return (\n \n {error && (\n \n {error}\n \n )}\n\n {success && (\n }>\n {t('export.uploadSuccess')}\n {datasetUrl && (\n \n \n {t('export.viewOnHuggingFace')}\n \n \n )}\n \n )}\n\n {!hasToken ? (\n \n {t('export.noTokenWarning')}\n \n (window.location.href = `/projects/${projectId}/settings`)}\n >\n {t('export.goToSettings')}\n \n \n \n ) : null}\n\n \n\n \n \n {t('export.datasetSettings')}\n \n\n \n \n setDatasetName(e.target.value)}\n helperText={t('export.datasetNameHelp')}\n sx={{ mb: 2 }}\n />\n \n\n \n setIsPrivate(e.target.checked)} />}\n label={t('export.privateDataset')}\n />\n \n \n \n\n \n \n {t('export.exportOptions')}\n \n\n \n \n {t('export.systemPrompt')}\n \n \n \n\n \n }\n label={t('export.onlyConfirmed')}\n />\n\n }\n label={t('export.includeCOT')}\n />\n \n \n\n \n \n {uploading ? : t('export.uploadToHuggingFace')}\n \n \n \n );\n};\n\nexport default HuggingFaceTab;\n"], ["/easy-dataset/app/api/projects/[projectId]/custom-split/route.js", "import { NextResponse } from 'next/server';\nimport { saveChunks, deleteChunksByFileId } from '@/lib/db/chunks';\nimport path from 'path';\nimport fs from 'fs/promises';\nimport { getProjectRoot } from '@/lib/db/base';\n\n/**\n * 处理自定义分块请求\n * @param {Request} request - 请求对象\n * @param {Object} params - 路由参数\n * @returns {Promise} - 响应对象\n */\nexport async function POST(request, { params }) {\n try {\n const { projectId } = params;\n const { fileId, fileName, content, splitPoints } = await request.json();\n\n // 参数验证\n if (!projectId || !fileId || !fileName || !content || !splitPoints) {\n return NextResponse.json({ error: 'Missing required parameters' }, { status: 400 });\n }\n\n // 获取项目根目录\n const projectRoot = await getProjectRoot();\n const projectPath = path.join(projectRoot, projectId);\n\n // 检查项目是否存在\n try {\n await fs.access(projectPath);\n } catch (error) {\n return NextResponse.json({ error: 'Project does not exist' }, { status: 404 });\n }\n\n // 先删除该文件已有的文本块\n await deleteChunksByFileId(projectId, fileId);\n\n // 根据分块点将文件内容分割成多个块\n const customChunks = generateCustomChunks(projectId, fileId, fileName, content, splitPoints);\n\n // 保存新的文本块\n await saveChunks(customChunks);\n\n return NextResponse.json({\n success: true,\n message: 'Custom chunks saved successfully',\n totalChunks: customChunks.length\n });\n } catch (error) {\n console.error('自定义分块处理出错:', String(error));\n return NextResponse.json({ error: error.message || 'Failed to process custom split request' }, { status: 500 });\n }\n}\n\n/**\n * 根据分块点生成自定义文本块\n * @param {string} projectId - 项目ID\n * @param {string} fileId - 文件ID\n * @param {string} fileName - 文件名\n * @param {string} content - 文件内容\n * @param {Array} splitPoints - 分块点数组\n * @returns {Array} - 生成的文本块数组\n */\nfunction generateCustomChunks(projectId, fileId, fileName, content, splitPoints) {\n // 按位置排序分块点\n const sortedPoints = [...splitPoints].sort((a, b) => a.position - b.position);\n\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\n // 提取当前分块内容\n const chunkContent = content.substring(startPos, endPos);\n\n // 跳过空白分块\n if (chunkContent.trim().length === 0) {\n startPos = endPos;\n continue;\n }\n\n // 创建分块对象\n const chunk = {\n projectId,\n name: `${path.basename(fileName, path.extname(fileName))}-part-${i + 1}`,\n fileId,\n fileName,\n content: chunkContent,\n summary: `${fileName} 自定义分块 ${i + 1}/${sortedPoints.length + 1}`,\n size: chunkContent.length\n };\n\n chunks.push(chunk);\n startPos = endPos;\n }\n\n // 添加最后一个分块(如果有内容)\n const lastChunkContent = content.substring(startPos);\n if (lastChunkContent.trim().length > 0) {\n const lastChunk = {\n projectId,\n name: `${path.basename(fileName, path.extname(fileName))}-part-${sortedPoints.length + 1}`,\n fileId,\n fileName,\n content: lastChunkContent,\n summary: `${fileName} 自定义分块 ${sortedPoints.length + 1}/${sortedPoints.length + 1}`,\n size: lastChunkContent.length\n };\n\n chunks.push(lastChunk);\n }\n\n return chunks;\n}\n"], ["/easy-dataset/lib/db/texts.js", "'use server';\n\nimport fs from 'fs';\nimport path from 'path';\nimport { getProjectRoot, ensureDir } from './base';\n\n// 获取项目中所有原始文件\nexport async function getFiles(projectId) {\n const projectRoot = await getProjectRoot();\n const projectPath = path.join(projectRoot, projectId);\n const filesDir = path.join(projectPath, 'files');\n await fs.promises.access(filesDir);\n const files = await fs.promises.readdir(filesDir);\n const fileStats = await Promise.all(\n files.map(async fileName => {\n // 跳过非文件项目\n const filePath = path.join(filesDir, fileName);\n const stats = await fs.promises.stat(filePath);\n\n // 只返回Markdown文件,跳过其他文件\n if (!fileName.endsWith('.md')) {\n return null;\n }\n\n return {\n name: fileName,\n path: filePath,\n size: stats.size,\n createdAt: stats.birthtime\n };\n })\n );\n return fileStats.filter(Boolean); // 过滤掉null值\n}\n\n// 删除项目中的原始文件及相关的文本块\nexport async function deleteFile(projectId, fileName) {\n const projectRoot = await getProjectRoot();\n const projectPath = path.join(projectRoot, projectId);\n const filesDir = path.join(projectPath, 'files');\n const chunksDir = path.join(projectPath, 'chunks');\n const tocDir = path.join(projectPath, 'toc');\n\n // 确保目录存在\n await ensureDir(tocDir);\n\n // 删除原始文件\n const filePath = path.join(filesDir, fileName);\n try {\n await fs.promises.access(filePath);\n await fs.promises.unlink(filePath);\n } catch (error) {\n console.error(`删除文件 ${fileName} 失败:`, error);\n // 如果文件不存在,继续处理\n }\n\n // 删除相关的TOC文件\n const baseName = path.basename(fileName, path.extname(fileName));\n const tocPath = path.join(tocDir, `${baseName}-toc.json`);\n console.log(111, tocPath);\n try {\n await fs.promises.access(tocPath);\n await fs.promises.unlink(tocPath);\n } catch (error) {\n // 如果TOC文件不存在,继续处理\n }\n\n // 删除相关的文本块\n try {\n await fs.promises.access(chunksDir);\n const chunks = await fs.promises.readdir(chunksDir);\n\n // 过滤出与该文件相关的文本块\n const relatedChunks = chunks.filter(chunk => chunk.startsWith(`${baseName}-part-`) && chunk.endsWith('.txt'));\n\n // 删除相关的文本块\n for (const chunk of relatedChunks) {\n const chunkPath = path.join(chunksDir, chunk);\n await fs.promises.unlink(chunkPath);\n }\n } catch (error) {\n console.error(`删除文件 ${fileName} 相关的文本块失败:`, error);\n }\n\n return { success: true, fileName };\n}\n"], ["/easy-dataset/app/api/llm/providers/route.js", "import { NextResponse } from 'next/server';\nimport { getLlmProviders } from '@/lib/db/llm-providers';\n\n// 获取 LLM 提供商数据\nexport async function GET() {\n try {\n const result = await getLlmProviders();\n return NextResponse.json(result);\n } catch (error) {\n console.error('Database query error:', String(error));\n return NextResponse.json({ error: 'Database query failed' }, { status: 500 });\n }\n}\n"], ["/easy-dataset/components/text-split/components/PdfProcessingDialog.js", "'use client';\n\nimport {\n Dialog,\n DialogTitle,\n DialogContent,\n Card,\n CardContent,\n Typography,\n Box,\n Stack,\n FormControl,\n InputLabel,\n Select,\n MenuItem\n} from '@mui/material';\nimport { useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { styled } from '@mui/material/styles';\nimport ArticleOutlinedIcon from '@mui/icons-material/ArticleOutlined';\nimport ScienceOutlinedIcon from '@mui/icons-material/ScienceOutlined';\nimport LaunchOutlinedIcon from '@mui/icons-material/LaunchOutlined';\nimport SmartToyOutlinedIcon from '@mui/icons-material/SmartToyOutlined';\n\nconst StyledCard = styled(Card)(({ theme, disabled }) => ({\n cursor: disabled ? 'not-allowed' : 'pointer',\n opacity: disabled ? 0.6 : 1,\n transition: 'transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out',\n '&:hover': disabled\n ? {}\n : {\n transform: 'translateY(-4px)',\n boxShadow: theme.shadows[4]\n }\n}));\n\nconst OptionCard = ({\n icon,\n title,\n description,\n disabled,\n onClick,\n selected,\n isVisionEnabled,\n visionModels,\n selectorName,\n handleSettingChange,\n selectedViosnModel\n}) => (\n \n \n \n {icon}\n \n {title}\n \n \n {description}\n \n {isVisionEnabled && (\n \n {selectorName}\n handleSettingChange(e)}\n name=\"vision\"\n >\n {visionModels.map(item => (\n \n {item.modelName} ({item.providerName})\n \n ))}\n \n \n )}\n \n \n \n);\n\nexport default function PdfProcessingDialog({\n open,\n onClose,\n onRadioChange,\n value,\n taskSettings,\n visionModels,\n selectedViosnModel,\n setSelectedViosnModel\n}) {\n const { t } = useTranslation();\n\n //检查配置中是否启用MinerU\n const isMinerUEnabled = taskSettings && taskSettings.minerUToken ? true : false;\n\n //检查配置中是否启用Vision策略\n const isVisionEnabled = visionModels.length > 0 ? true : false;\n\n //用于传递到父组件,显示当前选中的模型\n let selectedModel = selectedViosnModel;\n\n const handleOptionClick = optionValue => {\n if (optionValue === 'mineru-web') {\n window.open('https://mineru.net/OpenSourceTools/Extractor', '_blank');\n } else {\n onRadioChange({ target: { value: optionValue, selectedVision: selectedModel } });\n onClose();\n }\n };\n\n // 处理设置变更\n const handleSettingChange = e => {\n const { value } = e.target;\n selectedModel = value;\n setSelectedViosnModel(value);\n };\n\n return (\n \n {t('textSplit.pdfProcess')}\n \n \n }\n title={t('textSplit.basicPdfParsing')}\n description={t('textSplit.basicPdfParsingDesc')}\n onClick={() => handleOptionClick('default')}\n selected={value === 'default'}\n />\n }\n title=\"MinerU API\"\n description={isMinerUEnabled ? t('textSplit.mineruApiDesc') : t('textSplit.mineruApiDescDisabled')}\n disabled={!isMinerUEnabled}\n onClick={() => handleOptionClick('mineru')}\n selected={value === 'mineru'}\n />\n }\n title={t('textSplit.mineruWebPlatform')}\n description={t('textSplit.mineruWebPlatformDesc')}\n onClick={() => handleOptionClick('mineru-web')}\n />\n }\n title={t('textSplit.customVisionModel')}\n description={t('textSplit.customVisionModelDesc')}\n disabled={!isVisionEnabled}\n onClick={() => handleOptionClick('vision')}\n selected={value === 'vision'}\n isVisionEnabled={isVisionEnabled}\n visionModels={visionModels}\n selectorName={t('settings.vision')}\n selectedViosnModel={selectedViosnModel}\n handleSettingChange={handleSettingChange}\n />\n \n \n \n );\n}\n"], ["/easy-dataset/electron/main.js", "const { app, dialog, ipcMain } = require('electron');\nconst { setupLogging, setupIpcLogging } = require('./modules/logger');\nconst { createWindow, loadAppUrl, openDevTools, getMainWindow } = require('./modules/window-manager');\nconst { createMenu } = require('./modules/menu');\nconst { startNextServer } = require('./modules/server');\nconst { setupAutoUpdater } = require('./modules/updater');\nconst { initializeDatabase } = require('./modules/database');\nconst { clearCache } = require('./modules/cache');\nconst { setupIpcHandlers } = require('./modules/ipc-handlers');\n\n// 是否是开发环境\nconst isDev = process.env.NODE_ENV === 'development';\nconst port = 1717;\nlet mainWindow;\n\n// 当 Electron 完成初始化时创建窗口\napp.whenReady().then(async () => {\n try {\n // 设置日志系统\n setupLogging(app);\n\n // 设置 IPC 处理程序\n setupIpcHandlers(app, isDev);\n setupIpcLogging(ipcMain, app, isDev);\n\n // 初始化数据库\n await initializeDatabase(app);\n\n // 创建主窗口\n mainWindow = createWindow(isDev, port);\n\n // 创建菜单\n createMenu(mainWindow, () => clearCache(app));\n\n // 在开发环境中加载 localhost URL\n if (isDev) {\n loadAppUrl(`http://localhost:${port}`);\n openDevTools();\n } else {\n // 在生产环境中启动 Next.js 服务\n const appUrl = await startNextServer(port, app);\n loadAppUrl(appUrl);\n }\n\n // 设置自动更新\n setupAutoUpdater(mainWindow);\n\n // 应用启动完成后的一段时间后自动检查更新\n setTimeout(() => {\n if (!isDev) {\n const { autoUpdater } = require('electron-updater');\n autoUpdater.checkForUpdates().catch(err => {\n console.error('Automatic update check failed:', err);\n });\n }\n }, 10000); // Check for updates after 10 seconds\n } catch (error) {\n console.error('An error occurred during application initialization:', error);\n dialog.showErrorBox(\n 'Application Initialization Error',\n `An error occurred during startup, which may affect application functionality.\n Error details: ${error.message}`\n );\n }\n});\n\n// 当所有窗口关闭时退出应用\napp.on('window-all-closed', () => {\n if (process.platform !== 'darwin') {\n app.quit();\n }\n});\n\napp.on('activate', () => {\n if (BrowserWindow.getAllWindows().length === 0) {\n mainWindow = createWindow(isDev, port);\n }\n});\n\n// 应用退出前清理\napp.on('before-quit', () => {\n console.log('应用正在退出...');\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/app/projects/[projectId]/settings/page.js", "'use client';\n\nimport { useState, useEffect } from 'react';\nimport { Container, Typography, Box, Tabs, Tab, Paper, Alert, CircularProgress } from '@mui/material';\nimport { useSearchParams, useRouter } from 'next/navigation';\nimport { useTranslation } from 'react-i18next';\n\n// 导入设置组件\nimport BasicSettings from '@/components/settings/BasicSettings';\nimport ModelSettings from '@/components/settings/ModelSettings';\nimport TaskSettings from '@/components/settings/TaskSettings';\nimport PromptSettings from './components/PromptSettings';\n\n// 定义 TAB 枚举\nconst TABS = {\n BASIC: 'basic',\n MODEL: 'model',\n TASK: 'task',\n PROMPTS: 'prompts'\n};\n\nexport default function SettingsPage({ params }) {\n const { t } = useTranslation();\n const { projectId } = params;\n const searchParams = useSearchParams();\n const router = useRouter();\n const [activeTab, setActiveTab] = useState(TABS.BASIC);\n const [projectExists, setProjectExists] = useState(true);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n\n // 从 URL hash 中获取当前 tab\n useEffect(() => {\n const tab = searchParams.get('tab');\n if (tab && Object.values(TABS).includes(tab)) {\n setActiveTab(tab);\n }\n }, [searchParams]);\n\n // 检查项目是否存在\n useEffect(() => {\n async function checkProject() {\n try {\n setLoading(true);\n const response = await fetch(`/api/projects/${projectId}`);\n\n if (!response.ok) {\n if (response.status === 404) {\n setProjectExists(false);\n } else {\n throw new Error(t('projects.fetchFailed'));\n }\n } else {\n setProjectExists(true);\n }\n } catch (error) {\n console.error('获取项目详情出错:', error);\n setError(error.message);\n } finally {\n setLoading(false);\n }\n }\n\n checkProject();\n }, [projectId, t]);\n\n // 处理 tab 切换\n const handleTabChange = (event, newValue) => {\n setActiveTab(newValue);\n // 更新 URL hash\n router.push(`/projects/${projectId}/settings?tab=${newValue}`);\n };\n\n if (loading) {\n return (\n \n \n \n );\n }\n\n if (!projectExists) {\n return (\n \n {t('projects.notExist')}\n \n );\n }\n\n if (error) {\n return (\n \n {error}\n \n );\n }\n\n return (\n \n \n \n \n \n \n \n \n \n\n {activeTab === TABS.BASIC && }\n\n {activeTab === TABS.MODEL && }\n\n {activeTab === TABS.TASK && }\n\n {activeTab === TABS.PROMPTS && }\n \n );\n}\n"], ["/easy-dataset/lib/llm/prompts/enhancedAnswer.js", "/**\n * 增强版答案生成提示词 - 基于GA pairs\n * @param {Object} params - 参数对象\n * @param {string} params.text - 参考文本内容\n * @param {string} params.question - 问题内容\n * @param {string} params.language - 语言\n * @param {string} params.globalPrompt - 全局提示词\n * @param {string} params.answerPrompt - 答案提示词\n * @param {Array} params.gaPairs - GA pairs数组,包含genre和audience信息\n * @param {Object} params.activeGaPair - 当前激活的GA pair\n */\nexport default function getEnhancedAnswerPrompt({\n text,\n question,\n globalPrompt = '',\n answerPrompt = '',\n activeGaPair = null\n}) {\n if (globalPrompt) {\n globalPrompt = `- 在后续的任务中,你务必遵循这样的规则:${globalPrompt}`;\n }\n if (answerPrompt) {\n answerPrompt = `- 在生成答案时,你务必遵循这样的规则:${answerPrompt}`;\n }\n\n // 构建GA pairs相关的提示词\n let gaPrompt = '';\n if (activeGaPair && activeGaPair.active) {\n gaPrompt = `\n## 特殊要求 - 体裁与受众适配(MGA):\n根据以下体裁与受众组合,调整你的回答风格和深度:\n\n**当前体裁**: ${activeGaPair.genre}\n**目标受众**: ${activeGaPair.audience}\n\n请确保:\n1. 答案的组织、风格、详略程度和语言应完全符合「${activeGaPair.genre}」的要求。\n2. 答案应考虑到「${activeGaPair.audience}」的理解能力和知识背景,力求清晰易懂。\n3. 用词选择和解释详细程度匹配目标受众的知识背景。\n4. 保持内容的准确性和专业性,同时增强针对性。\n5. 如果「${activeGaPair.genre}」或「${activeGaPair.audience}」暗示需要,答案可以适当包含解释、示例或步骤。\n6. 答案应直接回应问题,确保问答的逻辑性和连贯性,不要包含无关信息或引用标记如GA对中提到的内容防止污染数据生成的效果。\n`;\n } else {\n gaPrompt = '';\n }\n\n return `\n# Role: 微调数据集生成专家 (MGA增强版)\n## Profile:\n- Description: 你是一名微调数据集生成专家,擅长从给定的内容中生成准确的问题答案,并能根据体裁与受众(Genre-Audience)组合调整回答风格,确保答案的准确性、相关性和针对性。\n${globalPrompt}\n\n## Skills:\n1. 答案必须基于给定的内容\n2. 答案必须准确,不能胡编乱造\n3. 答案必须与问题相关\n4. 答案必须符合逻辑\n5. 基于给定参考内容,用自然流畅的语言整合成一个完整答案,不需要提及文献来源或引用标记\n6. 能够根据指定的体裁与受众组合调整回答风格和深度\n7. 在保持内容准确性的同时,增强答案的针对性和适用性\n\n${gaPrompt}\n\n## Workflow:\n1. Take a deep breath and work on this problem step-by-step.\n2. 首先,分析给定的文件内容和问题类型\n3. 然后,从内容中提取关键信息\n4. 如果有指定的体裁与受众组合,分析如何调整回答风格\n5. 接着,生成与问题相关的准确答案,并根据体裁受众要求调整表达方式\n6. 最后,确保答案的准确性、相关性和风格适配性\n\n## 参考内容:\n${text}\n\n## 问题\n${question}\n\n## Constrains:\n1. 答案必须基于给定的内容\n2. 答案必须准确,必须与问题相关,不能胡编乱造\n3. 答案必须充分、详细、包含所有必要的信息、适合微调大模型训练使用\n4. 答案中不得出现 ' 参考 / 依据 / 文献中提到 ' 等任何引用性表述,只需呈现最终结果\n5. 如果指定了体裁与受众组合,必须在保持内容准确性的前提下,调整表达风格和深度\n6. 答案必须直接回应问题, 确保答案的准确性和逻辑性。\n${answerPrompt}\n`;\n}\n"], ["/easy-dataset/lib/db/tags.js", "'use server';\n\nimport path from 'path';\nimport { getProjectRoot, readJsonFile, writeJsonFile } from './base';\nimport { db } from '@/lib/db/index';\nimport fs from 'fs';\n\n// 获取标签树\nexport async function getTags(projectId) {\n try {\n return await getTagsTreeWithQuestionCount(projectId);\n } catch (error) {\n return [];\n }\n}\n\n// 递归查询树状结构,并统计问题数量\nasync function getTagsTreeWithQuestionCount(projectId, parentId = null) {\n // 查询当前层级的分类\n const tags = await db.tags.findMany({\n where: { parentId, projectId }\n });\n\n // 遍历每个分类,递归查询子节点\n for (const tag of tags) {\n // 获取当前分类及其子分类的所有 label\n const labels = await getAllLabels(tag.id);\n\n // 统计当前分类及其子分类的问题数量\n tag.questionCount = await db.questions.count({\n where: { label: { in: labels }, projectId }\n });\n\n // 递归查询子节点\n tag.child = await getTagsTreeWithQuestionCount(projectId, tag.id);\n }\n\n return tags;\n}\n\n// 获取某个分类及其所有子分类的 label\nasync function getAllLabels(tagId) {\n const labels = [];\n const queue = [tagId];\n\n while (queue.length > 0) {\n const currentId = queue.shift();\n const tag = await db.tags.findUnique({\n where: { id: currentId }\n });\n\n if (tag) {\n labels.push(tag.label);\n // 获取子分类的 ID,加入队列\n const children = await db.tags.findMany({\n where: { parentId: currentId },\n select: { id: true }\n });\n queue.push(...children.map(child => child.id));\n }\n }\n\n return labels;\n}\n\nexport async function createTag(projectId, label, parentId) {\n try {\n let data = {\n projectId,\n label\n };\n if (parentId) {\n data.parentId = parentId;\n }\n return await db.tags.create({ data });\n } catch (error) {\n console.error('Error insert tags db:', error);\n throw error;\n }\n}\n\nexport async function updateTag(label, id) {\n try {\n return await db.tags.update({ where: { id }, data: { label } });\n } catch (error) {\n console.error('Error update tags db:', error);\n throw error;\n }\n}\n\n/**\n * 删除标签及其所有子标签、问题和数据集\n * @param {string} id - 要删除的标签 ID\n * @returns {Promise} 删除结果\n */\nexport async function deleteTag(id) {\n try {\n console.log(`开始删除标签: ${id}`);\n\n // 1. 获取要删除的标签\n const tag = await db.tags.findUnique({\n where: { id }\n });\n\n if (!tag) {\n throw new Error(`标签不存在: ${id}`);\n }\n\n // 2. 获取所有子标签(所有层级)\n const allChildTags = await getAllChildTags(id, tag.projectId);\n console.log(`找到 ${allChildTags.length} 个子标签需要删除`);\n\n // 3. 从叶子节点开始删除,防止外键约束问题\n for (const childTag of allChildTags.reverse()) {\n // 删除与标签相关的数据集\n await deleteDatasetsByTag(childTag.label, childTag.projectId);\n\n // 删除与标签相关的问题\n await deleteQuestionsByTag(childTag.label, childTag.projectId);\n\n // 删除标签\n await db.tags.delete({ where: { id: childTag.id } });\n console.log(`删除子标签: ${childTag.id} (${childTag.label})`);\n }\n\n // 4. 删除与当前标签相关的数据集\n await deleteDatasetsByTag(tag.label, tag.projectId);\n\n // 5. 删除与当前标签相关的问题\n await deleteQuestionsByTag(tag.label, tag.projectId);\n\n // 6. 删除当前标签\n console.log(`删除主标签: ${id} (${tag.label})`);\n return await db.tags.delete({ where: { id } });\n } catch (error) {\n console.error('删除标签时出错:', error);\n throw error;\n }\n}\n\n/**\n * 获取标签的所有子标签(所有层级)\n * @param {string} parentId - 父标签 ID\n * @param {string} projectId - 项目 ID\n * @returns {Promise} 所有子标签列表\n */\nasync function getAllChildTags(parentId, projectId) {\n const result = [];\n\n // 递归获取子标签\n async function fetchChildTags(pid) {\n // 查询直接子标签\n const children = await db.tags.findMany({\n where: {\n parentId: pid,\n projectId\n }\n });\n\n // 如果有子标签\n if (children.length > 0) {\n // 将子标签添加到结果中\n result.push(...children);\n\n // 递归获取每个子标签的子标签\n for (const child of children) {\n await fetchChildTags(child.id);\n }\n }\n }\n\n // 开始递归获取\n await fetchChildTags(parentId);\n\n return result;\n}\n\n/**\n * 删除与标签相关的问题\n * @param {string} label - 标签名称\n * @param {string} projectId - 项目 ID\n */\nasync function deleteQuestionsByTag(label, projectId) {\n try {\n // 查找并删除与标签相关的所有问题\n await db.questions.deleteMany({\n where: {\n label,\n projectId\n }\n });\n } catch (error) {\n console.error(`删除标签 \"${label}\" 相关问题时出错:`, error);\n throw error;\n }\n}\n\n/**\n * 删除与标签相关的数据集\n * @param {string} label - 标签名称\n * @param {string} projectId - 项目 ID\n */\nasync function deleteDatasetsByTag(label, projectId) {\n try {\n // 查找并删除与标签相关的所有数据集\n await db.datasets.deleteMany({\n where: {\n questionLabel: label,\n projectId\n }\n });\n } catch (error) {\n console.error(`删除标签 \"${label}\" 相关数据集时出错:`, error);\n throw error;\n }\n}\n\n// 保存整个标签树\nexport async function batchSaveTags(projectId, tags) {\n try {\n // 仅在入口函数删除所有标签,避免递归中重复删除\n await db.tags.deleteMany({ where: { projectId } });\n // 处理标签树\n await insertTags(projectId, tags);\n } catch (error) {\n console.error('Error insert tags db:', error);\n throw error;\n }\n}\n\nasync function insertTags(projectId, tags, parentId = null) {\n // 删除操作已移至外层函数,这里不再需要\n for (const tag of tags) {\n // 插入当前节点\n const createdTag = await db.tags.create({\n data: {\n projectId,\n label: tag.label,\n parentId: parentId\n }\n });\n // 如果有子节点,递归插入\n if (tag.child && tag.child.length > 0) {\n await insertTags(projectId, tag.child, createdTag.id);\n }\n }\n}\n"], ["/easy-dataset/components/ThemeRegistry.js", "'use client';\n\nimport { createTheme, ThemeProvider } from '@mui/material/styles';\nimport CssBaseline from '@mui/material/CssBaseline';\nimport { ThemeProvider as NextThemeProvider, useTheme } from 'next-themes';\nimport { useEffect, useState } from 'react';\n\n// 导入字体\nimport '@fontsource/inter/300.css';\nimport '@fontsource/inter/400.css';\nimport '@fontsource/inter/500.css';\nimport '@fontsource/inter/600.css';\nimport '@fontsource/inter/700.css';\nimport '@fontsource/jetbrains-mono/400.css';\nimport '@fontsource/jetbrains-mono/500.css';\n\n// 创建主题配置\nconst getTheme = mode => {\n // 主色调\n const mainBlue = '#2A5CAA';\n const darkGray = '#2D2D2D';\n\n // 辅助色 - 数据可视化色谱\n const dataVizColors = [\n '#6366F1', // 紫蓝色\n '#10B981', // 绿色\n '#F59E0B', // 琥珀色\n '#EC4899', // 粉色\n '#8B5CF6', // 紫色\n '#3B82F6' // 蓝色\n ];\n\n // 状态色\n const successColor = '#10B981'; // 翡翠绿\n const warningColor = '#F59E0B'; // 琥珀色\n const errorColor = '#EF4444'; // 珊瑚红\n\n // 渐变色\n const gradientPrimary = 'linear-gradient(90deg, #2A5CAA 0%, #8B5CF6 100%)';\n\n // 根据模式调整颜色\n return createTheme({\n palette: {\n mode,\n primary: {\n main: mainBlue,\n dark: '#1E4785',\n light: '#4878C6',\n contrastText: '#FFFFFF'\n },\n secondary: {\n main: '#8B5CF6',\n dark: '#7039F2',\n light: '#A78BFA',\n contrastText: '#FFFFFF'\n },\n error: {\n main: errorColor,\n dark: '#DC2626',\n light: '#F87171'\n },\n warning: {\n main: warningColor,\n dark: '#D97706',\n light: '#FBBF24'\n },\n success: {\n main: successColor,\n dark: '#059669',\n light: '#34D399'\n },\n background: {\n default: mode === 'dark' ? '#121212' : '#F8F9FA',\n paper: mode === 'dark' ? '#1E1E1E' : '#FFFFFF',\n subtle: mode === 'dark' ? '#2A2A2A' : '#F3F4F6'\n },\n text: {\n primary: mode === 'dark' ? '#F3F4F6' : darkGray,\n secondary: mode === 'dark' ? '#9CA3AF' : '#6B7280',\n disabled: mode === 'dark' ? '#4B5563' : '#9CA3AF'\n },\n divider: mode === 'dark' ? 'rgba(255, 255, 255, 0.12)' : 'rgba(0, 0, 0, 0.12)',\n dataViz: dataVizColors,\n gradient: {\n primary: gradientPrimary\n }\n },\n typography: {\n fontFamily:\n '\"Inter\", \"HarmonyOS Sans\", \"PingFang SC\", -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, sans-serif',\n fontSize: 14,\n fontWeightLight: 300,\n fontWeightRegular: 400,\n fontWeightMedium: 500,\n fontWeightBold: 600,\n h1: {\n fontSize: '2rem', // 32px\n fontWeight: 600,\n lineHeight: 1.2,\n letterSpacing: '-0.01em'\n },\n h2: {\n fontSize: '1.5rem', // 24px\n fontWeight: 600,\n lineHeight: 1.3,\n letterSpacing: '-0.005em'\n },\n h3: {\n fontSize: '1.25rem', // 20px\n fontWeight: 600,\n lineHeight: 1.4\n },\n h4: {\n fontSize: '1.125rem', // 18px\n fontWeight: 600,\n lineHeight: 1.4\n },\n h5: {\n fontSize: '1rem', // 16px\n fontWeight: 600,\n lineHeight: 1.5\n },\n h6: {\n fontSize: '0.875rem', // 14px\n fontWeight: 600,\n lineHeight: 1.5\n },\n body1: {\n fontSize: '1rem', // 16px\n lineHeight: 1.5\n },\n body2: {\n fontSize: '0.875rem', // 14px\n lineHeight: 1.5\n },\n caption: {\n fontSize: '0.75rem', // 12px\n lineHeight: 1.5\n },\n code: {\n fontFamily: '\"JetBrains Mono\", monospace',\n fontSize: '0.875rem'\n }\n },\n shape: {\n borderRadius: 8\n },\n spacing: 8, // 基础间距单位为8px\n components: {\n MuiCssBaseline: {\n styleOverrides: {\n body: {\n scrollbarWidth: 'thin',\n scrollbarColor: mode === 'dark' ? '#4B5563 transparent' : '#9CA3AF transparent',\n '&::-webkit-scrollbar': {\n width: '8px',\n height: '8px'\n },\n '&::-webkit-scrollbar-track': {\n background: 'transparent'\n },\n '&::-webkit-scrollbar-thumb': {\n background: mode === 'dark' ? '#4B5563' : '#9CA3AF',\n borderRadius: '4px'\n }\n },\n // 确保代码块使用 JetBrains Mono 字体\n 'code, pre': {\n fontFamily: '\"JetBrains Mono\", monospace'\n },\n // 自定义渐变文本的通用样式\n '.gradient-text': {\n background: gradientPrimary,\n WebkitBackgroundClip: 'text',\n WebkitTextFillColor: 'transparent',\n backgroundClip: 'text',\n textFillColor: 'transparent'\n }\n }\n },\n MuiButton: {\n styleOverrides: {\n root: {\n textTransform: 'none',\n fontWeight: 500,\n borderRadius: '8px',\n padding: '6px 16px'\n },\n contained: {\n boxShadow: 'none',\n '&:hover': {\n boxShadow: '0px 2px 4px rgba(0, 0, 0, 0.1)'\n }\n },\n containedPrimary: {\n background: mainBlue,\n '&:hover': {\n backgroundColor: '#1E4785'\n }\n },\n containedSecondary: {\n background: '#8B5CF6',\n '&:hover': {\n backgroundColor: '#7039F2'\n }\n },\n outlined: {\n borderWidth: '1.5px',\n '&:hover': {\n borderWidth: '1.5px'\n }\n }\n }\n },\n MuiAppBar: {\n styleOverrides: {\n root: {\n boxShadow: 'none',\n background: mode === 'dark' ? '#1A1A1A' : mainBlue\n }\n }\n },\n MuiCard: {\n styleOverrides: {\n root: {\n borderRadius: '12px',\n boxShadow: mode === 'dark' ? '0px 4px 8px rgba(0, 0, 0, 0.4)' : '0px 4px 8px rgba(0, 0, 0, 0.05)'\n }\n }\n },\n MuiPaper: {\n styleOverrides: {\n root: {\n borderRadius: '12px'\n }\n }\n },\n MuiChip: {\n styleOverrides: {\n root: {\n borderRadius: '6px',\n fontWeight: 500\n }\n }\n },\n MuiTableHead: {\n styleOverrides: {\n root: {\n '& .MuiTableCell-head': {\n fontWeight: 600,\n backgroundColor: mode === 'dark' ? '#2A2A2A' : '#F3F4F6'\n }\n }\n }\n },\n MuiTabs: {\n styleOverrides: {\n indicator: {\n height: '3px',\n borderRadius: '3px 3px 0 0'\n }\n }\n },\n MuiTab: {\n styleOverrides: {\n root: {\n textTransform: 'none',\n fontWeight: 500,\n '&.Mui-selected': {\n fontWeight: 600\n }\n }\n }\n },\n MuiListItemButton: {\n styleOverrides: {\n root: {\n borderRadius: '8px'\n }\n }\n },\n MuiDialogTitle: {\n styleOverrides: {\n root: {\n fontSize: '1.25rem',\n fontWeight: 600\n }\n }\n }\n }\n });\n};\n\nexport default function ThemeRegistry({ children }) {\n const [mounted, setMounted] = useState(false);\n\n useEffect(() => {\n setMounted(true);\n }, []);\n\n if (!mounted) {\n return null;\n }\n\n return (\n \n {children}\n \n );\n}\n\nfunction InnerThemeRegistry({ children }) {\n const { resolvedTheme } = useTheme();\n const theme = getTheme(resolvedTheme === 'dark' ? 'dark' : 'light');\n\n return (\n \n \n {children}\n \n );\n}\n"], ["/easy-dataset/components/Navbar.js", "'use client';\n\nimport React, { useState } from 'react';\nimport {\n AppBar,\n Toolbar,\n Typography,\n Box,\n MenuItem,\n FormControl,\n Select,\n Tabs,\n Tab,\n IconButton,\n useTheme as useMuiTheme,\n Tooltip,\n Menu,\n ListItemIcon,\n ListItemText,\n Divider\n} from '@mui/material';\nimport { useTranslation } from 'react-i18next';\nimport ModelSelect from './ModelSelect';\nimport LanguageSwitcher from './LanguageSwitcher';\nimport UpdateChecker from './UpdateChecker';\nimport TaskIcon from './TaskIcon';\nimport Link from 'next/link';\nimport { usePathname } from 'next/navigation';\nimport { useTheme } from 'next-themes';\nimport HelpOutlineIcon from '@mui/icons-material/HelpOutline';\n\n// 图标\nimport LightModeOutlinedIcon from '@mui/icons-material/LightModeOutlined';\nimport DarkModeOutlinedIcon from '@mui/icons-material/DarkModeOutlined';\nimport StorageIcon from '@mui/icons-material/Storage';\nimport GitHubIcon from '@mui/icons-material/GitHub';\nimport DescriptionOutlinedIcon from '@mui/icons-material/DescriptionOutlined';\nimport TokenOutlinedIcon from '@mui/icons-material/TokenOutlined';\nimport QuestionAnswerOutlinedIcon from '@mui/icons-material/QuestionAnswerOutlined';\nimport DatasetOutlinedIcon from '@mui/icons-material/DatasetOutlined';\nimport SettingsOutlinedIcon from '@mui/icons-material/SettingsOutlined';\nimport ScienceOutlinedIcon from '@mui/icons-material/ScienceOutlined';\nimport MoreVertIcon from '@mui/icons-material/MoreVert';\nimport { toast } from 'sonner';\nimport axios from 'axios';\nimport { useSetAtom } from 'jotai/index';\nimport { modelConfigListAtom, selectedModelInfoAtom } from '@/lib/store';\n\nexport default function Navbar({ projects = [], currentProject }) {\n const [selectedProject, setSelectedProject] = useState(currentProject || '');\n const { t, i18n } = useTranslation();\n const pathname = usePathname();\n const theme = useMuiTheme();\n const { resolvedTheme, setTheme } = useTheme();\n const setConfigList = useSetAtom(modelConfigListAtom);\n const setSelectedModelInfo = useSetAtom(selectedModelInfoAtom);\n // 只在项目详情页显示模块选项卡\n const isProjectDetail = pathname.includes('/projects/') && pathname.split('/').length > 3;\n // 更多菜单状态\n const [moreMenuAnchor, setMoreMenuAnchor] = useState(null);\n const isMoreMenuOpen = Boolean(moreMenuAnchor);\n\n // 处理更多菜单打开\n const handleMoreMenuOpen = event => {\n setMoreMenuAnchor(event.currentTarget);\n };\n\n // 处理更多菜单悬浮打开\n const handleMoreMenuHover = event => {\n setMoreMenuAnchor(event.currentTarget);\n };\n\n // 关闭更多菜单\n const handleMoreMenuClose = () => {\n setMoreMenuAnchor(null);\n };\n\n // 处理菜单区域的鼠标离开\n const handleMenuMouseLeave = () => {\n setMoreMenuAnchor(null);\n };\n\n const handleProjectChange = event => {\n const newProjectId = event.target.value;\n setSelectedProject(newProjectId);\n axios\n .get(`/api/projects/${newProjectId}/model-config`)\n .then(response => {\n setConfigList(response.data.data);\n if (response.data.defaultModelConfigId) {\n setSelectedModelInfo(response.data.data.find(item => item.id === response.data.defaultModelConfigId));\n } else {\n setSelectedModelInfo('');\n }\n })\n .catch(error => {\n toast.error('get model list error');\n });\n // 跳转到新选择的项目页面\n window.location.href = `/projects/${newProjectId}/text-split`;\n };\n\n const toggleTheme = () => {\n setTheme(resolvedTheme === 'dark' ? 'light' : 'dark');\n };\n\n return (\n \n \n {/* 左侧Logo和项目选择 */}\n \n {\n window.location.href = '/';\n }}\n >\n \n \n Easy DataSet\n \n \n\n {isProjectDetail && (\n \n \n \n {t('projects.selectProject')}\n \n {projects.map(project => (\n \n {project.name}\n \n ))}\n \n \n )}\n \n\n {/* 中间的功能模块导航 - 使用Flex布局居中 */}\n {isProjectDetail && (\n \n \n \n \n \n }\n iconPosition=\"start\"\n label={t('textSplit.title')}\n value={`/projects/${selectedProject}/text-split`}\n component={Link}\n href={`/projects/${selectedProject}/text-split`}\n />\n \n \n \n }\n iconPosition=\"start\"\n label={t('distill.title')}\n value={`/projects/${selectedProject}/distill`}\n component={Link}\n href={`/projects/${selectedProject}/distill`}\n />\n \n \n \n }\n iconPosition=\"start\"\n label={t('questions.title')}\n value={`/projects/${selectedProject}/questions`}\n component={Link}\n href={`/projects/${selectedProject}/questions`}\n />\n \n \n \n }\n iconPosition=\"start\"\n label={t('datasets.management')}\n value={`/projects/${selectedProject}/datasets`}\n component={Link}\n href={`/projects/${selectedProject}/datasets`}\n />\n \n \n \n }\n iconPosition=\"start\"\n label={t('common.more')}\n onMouseEnter={handleMoreMenuHover}\n value=\"more\"\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 {/* 右侧操作区 - 使用Flex布局 */}\n \n {/* 模型选择 */}\n {location.pathname.includes('/projects/') && }\n {/* 任务图标 - 仅在项目页面显示 */}\n {location.pathname.includes('/projects/') && }\n\n {/* 语言切换器 */}\n \n \n \n {/* 主题切换按钮 */}\n \n \n {resolvedTheme === 'dark' ? (\n \n ) : (\n \n )}\n \n \n\n {/* 文档链接 */}\n \n \n \n \n \n\n {/* GitHub链接 */}\n \n window.open('https://github.com/ConardLi/easy-dataset', '_blank')}\n size=\"small\"\n sx={{\n bgcolor: theme.palette.mode === 'dark' ? 'rgba(255, 255, 255, 0.05)' : 'rgba(255, 255, 255, 0.15)',\n color: theme.palette.mode === 'dark' ? 'inherit' : 'white',\n p: 1,\n borderRadius: 1.5,\n '&:hover': {\n bgcolor: theme.palette.mode === 'dark' ? 'rgba(255, 255, 255, 0.1)' : 'rgba(255, 255, 255, 0.25)'\n }\n }}\n >\n \n \n \n\n {/* 更新检查器 */}\n \n \n \n \n );\n}\n"], ["/easy-dataset/app/projects/[projectId]/questions/hooks/useQuestionEdit.js", "'use client';\n\nimport { useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport request from '@/lib/util/request';\n\nexport function useQuestionEdit(projectId, onSuccess) {\n const { t } = useTranslation();\n const [editDialogOpen, setEditDialogOpen] = useState(false);\n const [editMode, setEditMode] = useState('create');\n const [editingQuestion, setEditingQuestion] = useState(null);\n\n const handleOpenCreateDialog = () => {\n setEditMode('create');\n setEditingQuestion(null);\n setEditDialogOpen(true);\n };\n\n const handleOpenEditDialog = question => {\n setEditMode('edit');\n setEditingQuestion(question);\n setEditDialogOpen(true);\n };\n\n const handleCloseDialog = () => {\n setEditDialogOpen(false);\n setEditingQuestion(null);\n };\n\n const handleSubmitQuestion = async formData => {\n try {\n const response = await request(`/api/projects/${projectId}/questions`, {\n method: editMode === 'create' ? 'POST' : 'PUT',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(\n editMode === 'create'\n ? {\n question: formData.question,\n chunkId: formData.chunkId,\n label: formData.label\n }\n : {\n id: formData.id,\n question: formData.question,\n chunkId: formData.chunkId,\n label: formData.label\n }\n )\n });\n\n if (!response.ok) {\n const errorData = await response.json();\n throw new Error(errorData.error || t('questions.operationFailed'));\n }\n\n // 获取更新后的问题数据\n const updatedQuestion = await response.json();\n\n // 直接更新问题列表中的数据,而不是重新获取整个列表\n if (onSuccess) {\n onSuccess(updatedQuestion);\n }\n handleCloseDialog();\n } catch (error) {\n console.error('操作失败:', error);\n }\n };\n\n return {\n editDialogOpen,\n editMode,\n editingQuestion,\n handleOpenCreateDialog,\n handleOpenEditDialog,\n handleCloseDialog,\n handleSubmitQuestion\n };\n}\n"], ["/easy-dataset/lib/llm/prompts/distillTagsEn.js", "/**\n * Prompt for constructing sub-tags based on parent tag\n * @param {string} tagPath - Tag chain, e.g., \"Knowledge Base->Sports\"\n * @param {string} parentTag - Parent tag name, e.g., \"Sports\"\n * @param {Array} existingTags - Existing sub-tags under this parent tag (to avoid duplicates), e.g., [\"Football\", \"Table Tennis\"]\n * @param {number} count - Number of sub-tags to generate, e.g.: 10\n * @param {string} globalPrompt - Project-wide global prompt\n * @returns {string} Prompt\n */\nexport function distillTagsEnPrompt(tagPath, parentTag, existingTags = [], count = 10, globalPrompt = '') {\n const existingTagsText =\n existingTags.length > 0\n ? `Existing sub-tags include: ${existingTags.join('、')}. Please do not generate duplicate tags.`\n : '';\n\n // Build the global prompt section\n const globalPromptText = globalPrompt ? `You must follow this requirement: ${globalPrompt}` : '';\n\n return `\nYou are a professional knowledge tag generation assistant. I need you to generate ${count} sub-tags for the parent tag \"${parentTag}\".\n\nThe full tag chain is: ${tagPath || parentTag}\n\nPlease follow these rules:\n${globalPromptText}\n1. Generated tags should be professional sub-categories or sub-topics within the \"${parentTag}\" domain\n2. Each tag should be concise and clear, typically 2-6 characters\n3. Tags should be clearly distinguishable, covering different aspects\n4. Tags should be nouns or noun phrases; avoid verbs or adjectives\n5. Tags should be practical and serve as a basis for question generation\n6. Tags should have explicit numbering. If the parent tag is numbered (e.g., 1 Automobiles), sub-tags should be 1.1 Car Brands, 1.2 Car Models, 1.3 Car Prices, etc.\n7. If the parent tag is unnumbered (e.g., \"Automobiles\"), indicating top-level tag generation, sub-tags should be 1 Car Brands 2 Car Models 3 Car Prices, etc.\n\n${existingTagsText}\n\nPlease directly return the tags in JSON array format without any additional explanations or descriptions, in the following format:\n[\"Number Tag 1\", \"Number Tag 2\", \"Number Tag 3\", ...]\n`;\n}\n"], ["/easy-dataset/app/projects/[projectId]/playground/page.js", "'use client';\n\nimport React from 'react';\nimport { Box, Typography, Paper, Alert } from '@mui/material';\nimport { useParams } from 'next/navigation';\nimport { useTheme } from '@mui/material/styles';\nimport ChatArea from '@/components/playground/ChatArea';\nimport MessageInput from '@/components/playground/MessageInput';\nimport PlaygroundHeader from '@/components/playground/PlaygroundHeader';\nimport useModelPlayground from '@/hooks/useModelPlayground';\nimport { playgroundStyles } from '@/styles/playground';\nimport { useTranslation } from 'react-i18next';\nimport { useAtomValue } from 'jotai/index';\nimport { modelConfigListAtom } from '@/lib/store';\n\nexport default function ModelPlayground({ searchParams }) {\n const theme = useTheme();\n const params = useParams();\n const { projectId } = params;\n const modelId = searchParams?.modelId || null;\n const styles = playgroundStyles(theme);\n const { t } = useTranslation();\n\n const {\n selectedModels,\n loading,\n userInput,\n conversations,\n error,\n outputMode,\n uploadedImage,\n handleModelSelection,\n handleInputChange,\n handleImageUpload,\n handleRemoveImage,\n handleSendMessage,\n handleClearConversations,\n handleOutputModeChange\n } = useModelPlayground(projectId, modelId);\n\n const availableModels = useAtomValue(modelConfigListAtom);\n\n // 获取模型名称\n const getModelName = modelId => {\n const model = availableModels.find(m => m.id === modelId);\n return model ? `${model.providerName}: ${model.modelName}` : modelId;\n };\n return (\n \n \n {t('playground.title')}\n \n\n {error && (\n \n {error}\n \n )}\n\n \n \n\n \n\n \n \n \n );\n}\n"], ["/easy-dataset/app/api/projects/[projectId]/tasks/route.js", "import { NextResponse } from 'next/server';\nimport path from 'path';\nimport fs from 'fs/promises';\nimport { getProjectRoot } from '@/lib/db/base';\nimport { getTaskConfig } from '@/lib/db/projects';\nimport { processTask } from '@/lib/services/tasks';\nimport { db } from '@/lib/db/index';\n\n// 获取任务配置\nexport async function GET(request, { params }) {\n try {\n const { projectId } = params;\n\n // 验证项目 ID\n if (!projectId) {\n return NextResponse.json({ error: 'Project ID is required' }, { status: 400 });\n }\n\n // 获取项目根目录\n const projectRoot = await getProjectRoot();\n const projectPath = path.join(projectRoot, projectId);\n\n // 检查项目是否存在\n try {\n await fs.access(projectPath);\n } catch (error) {\n return NextResponse.json({ error: 'Project does not exist' + projectPath }, { status: 404 });\n }\n\n const taskConfig = await getTaskConfig(projectId);\n return NextResponse.json(taskConfig);\n } catch (error) {\n console.error('Failed to obtain task configuration:', String(error));\n return NextResponse.json({ error: 'Failed to obtain task configuration' }, { status: 500 });\n }\n}\n\n// 更新任务配置\nexport async function PUT(request, { params }) {\n try {\n const { projectId } = params;\n\n // 验证项目 ID\n if (!projectId) {\n return NextResponse.json({ error: 'Project ID is required' }, { status: 400 });\n }\n\n // 获取请求体\n const taskConfig = await request.json();\n\n // 验证请求体\n if (!taskConfig) {\n return NextResponse.json({ error: 'Task configuration cannot be empty' }, { status: 400 });\n }\n\n // 获取项目根目录\n const projectRoot = await getProjectRoot();\n const projectPath = path.join(projectRoot, projectId);\n\n // 检查项目是否存在\n try {\n await fs.access(projectPath);\n } catch (error) {\n return NextResponse.json({ error: 'Project does not exist' }, { status: 404 });\n }\n\n // 获取任务配置文件路径\n const taskConfigPath = path.join(projectPath, 'task-config.json');\n\n // 写入任务配置文件\n await fs.writeFile(taskConfigPath, JSON.stringify(taskConfig, null, 2), 'utf-8');\n\n return NextResponse.json({ message: 'Task configuration updated successfully' });\n } catch (error) {\n console.error('Failed to update task configuration:', String(error));\n return NextResponse.json({ error: 'Failed to update task configuration' }, { status: 500 });\n }\n}\n\n// 创建新任务\nexport async function POST(request, { params }) {\n try {\n const { projectId } = params;\n const data = await request.json();\n\n // 验证必填字段\n const { taskType, modelInfo, language, detail = '', totalCount = 0, note } = data;\n\n if (!taskType) {\n return NextResponse.json(\n {\n code: 400,\n error: 'Missing required parameter: taskType'\n },\n { status: 400 }\n );\n }\n\n // 创建新任务\n const newTask = await db.task.create({\n data: {\n projectId,\n taskType,\n status: 0, // 初始状态: 处理中\n modelInfo: typeof modelInfo === 'string' ? modelInfo : JSON.stringify(modelInfo),\n language: language || 'zh-CN',\n detail: detail || '',\n totalCount,\n note: note ? JSON.stringify(note) : '',\n completedCount: 0\n }\n });\n\n // 异步启动任务处理\n processTask(newTask.id).catch(err => {\n console.error(`Task startup failed: ${newTask.id}`, String(err));\n });\n\n return NextResponse.json({\n code: 0,\n data: newTask,\n message: 'Task created successfully'\n });\n } catch (error) {\n console.error('Failed to create task:', String(error));\n return NextResponse.json(\n {\n code: 500,\n error: 'Failed to create task',\n message: error.message\n },\n { status: 500 }\n );\n }\n}\n"], ["/easy-dataset/lib/llm/prompts/answer.js", "module.exports = function getAnswerPrompt({ text, question, language = '中文', globalPrompt = '', answerPrompt = '' }) {\n if (globalPrompt) {\n globalPrompt = `- 在后续的任务中,你务必遵循这样的规则:${globalPrompt}`;\n }\n if (answerPrompt) {\n answerPrompt = `- 在生成答案时,你务必遵循这样的规则:${answerPrompt}`;\n }\n return `\n# Role: 微调数据集生成专家\n## Profile:\n- Description: 你是一名微调数据集生成专家,擅长从给定的内容中生成准确的问题答案,确保答案的准确性和相关性,,你要直接回答用户问题,所有信息已内化为你的专业知识。\n${globalPrompt}\n\n## Skills :\n1. 答案必须基于给定的内容\n2. 答案必须准确,不能胡编乱造\n3. 答案必须与问题相关\n4. 答案必须符合逻辑\n5. 基于给定参考内容,用自然流畅的语言整合成一个完整答案,不需要提及文献来源或引用标记\n \n## Workflow:\n1. Take a deep breath and work on this problem step-by-step.\n2. 首先,分析给定的文件内容\n3. 然后,从内容中提取关键信息\n4. 接着,生成与问题相关的准确答案\n5. 最后,确保答案的准确性和相关性\n\n## 参考内容:\n${text}\n\n## 问题\n${question}\n\n## Constrains:\n1. 答案必须基于给定的内容\n2. 答案必须准确,必须与问题相关,不能胡编乱造\n3. 答案必须充分、详细、包含所有必要的信息、适合微调大模型训练使用\n4. 答案中不得出现 ' 参考 / 依据 / 文献中提到 ' 等任何引用性表述,只需呈现最终结\n${answerPrompt}\n `;\n};\n"], ["/easy-dataset/app/api/projects/route.js", "import { createProject, getProjects, isExistByName } from '@/lib/db/projects';\nimport { createInitModelConfig, getModelConfigByProjectId } from '@/lib/db/model-config';\n\nexport async function POST(request) {\n try {\n const projectData = await request.json();\n // 验证必要的字段\n if (!projectData.name) {\n return Response.json({ error: '项目名称不能为空' }, { status: 400 });\n }\n\n // 验证项目名称是否已存在\n if (await isExistByName(projectData.name)) {\n return Response.json({ error: '项目名称已存在' }, { status: 400 });\n }\n // 创建项目\n const newProject = await createProject(projectData);\n // 如果指定了要复用的项目配置\n if (projectData.reuseConfigFrom) {\n let data = await getModelConfigByProjectId(projectData.reuseConfigFrom);\n\n let newData = data.map(item => {\n delete item.id;\n return {\n ...item,\n projectId: newProject.id\n };\n });\n await createInitModelConfig(newData);\n }\n return Response.json(newProject, { status: 201 });\n } catch (error) {\n console.error('创建项目出错:', String(error));\n return Response.json({ error: String(error) }, { status: 500 });\n }\n}\n\nexport async function GET(request) {\n try {\n // 获取所有项目\n const projects = await getProjects();\n return Response.json(projects);\n } catch (error) {\n console.error('获取项目列表出错:', String(error));\n return Response.json({ error: String(error) }, { status: 500 });\n }\n}\n"], ["/easy-dataset/app/api/projects/[projectId]/chunks/[chunkId]/questions/route.js", "import { NextResponse } from 'next/server';\nimport { getQuestionsForChunk } from '@/lib/db/questions';\nimport logger from '@/lib/util/logger';\nimport questionService from '@/lib/services/questions';\n\n// 为指定文本块生成问题\nexport async function POST(request, { params }) {\n try {\n const { projectId, chunkId } = params;\n\n // 验证项目ID和文本块ID\n if (!projectId || !chunkId) {\n return NextResponse.json({ error: 'Project ID or text block ID cannot be empty' }, { status: 400 });\n } // 获取请求体\n const { model, language = '中文', number, enableGaExpansion = false } = await request.json();\n\n if (!model) {\n return NextResponse.json({ error: 'Model cannot be empty' }, { status: 400 });\n }\n\n // 后续会根据是否有GA对来选择是否启用GA扩展选择服务函数\n const serviceFunc = questionService.generateQuestionsForChunkWithGA;\n\n // 使用问题生成服务\n const result = await serviceFunc(projectId, chunkId, {\n model,\n language,\n number,\n enableGaExpansion\n });\n\n // 统一返回格式,确保包含GA扩展信息\n const response = {\n chunkId,\n questions: result.questions || result.labelQuestions || [],\n total: result.total || (result.questions || result.labelQuestions || []).length,\n gaExpansionUsed: result.gaExpansionUsed || false,\n gaPairsCount: result.gaPairsCount || 0,\n expectedTotal: result.expectedTotal || result.total\n };\n\n // 返回生成的问题\n return NextResponse.json(response);\n } catch (error) {\n logger.error('Error generating questions:', error);\n return NextResponse.json({ error: error.message || 'Error generating questions' }, { status: 500 });\n }\n}\n\n// 获取指定文本块的问题\nexport async function GET(request, { params }) {\n try {\n const { projectId, chunkId } = params;\n\n // 验证项目ID和文本块ID\n if (!projectId || !chunkId) {\n return NextResponse.json({ error: 'The item ID or text block ID cannot be empty' }, { status: 400 });\n }\n\n // 获取文本块的问题\n const questions = await getQuestionsForChunk(projectId, chunkId);\n\n // 返回问题列表\n return NextResponse.json({\n chunkId,\n questions,\n total: questions.length\n });\n } catch (error) {\n console.error('Error getting questions:', String(error));\n return NextResponse.json({ error: error.message || 'Error getting questions' }, { status: 500 });\n }\n}\n"], ["/easy-dataset/lib/db/upload-files.js", "'use server';\nimport { db } from '@/lib/db/index';\nimport fs from 'fs';\nimport path from 'path';\nimport { deleteDataset } from './datasets';\nimport { deleteChunkById } from './chunks';\n\n//获取文件列表\nexport async function getUploadFilesPagination(projectId, page = 1, pageSize = 10, fileName) {\n try {\n const whereClause = {\n projectId,\n fileName: { contains: fileName }\n };\n const [data, total] = await Promise.all([\n db.uploadFiles.findMany({\n where: whereClause,\n orderBy: {\n createAt: 'desc'\n },\n skip: (page - 1) * pageSize,\n take: pageSize\n }),\n db.uploadFiles.count({\n where: whereClause\n })\n ]);\n return { data, total };\n } catch (error) {\n console.error('Failed to get uploadFiles by pagination in database');\n throw error;\n }\n}\n\nexport async function getUploadFileInfoById(fileId) {\n try {\n return await db.uploadFiles.findUnique({ where: { id: fileId } });\n } catch (error) {\n console.error('Failed to get uploadFiles by id in database');\n throw error;\n }\n}\n\nexport async function getUploadFilesByProjectId(projectId) {\n try {\n return await db.uploadFiles.findMany({\n where: {\n projectId,\n NOT: {\n id: {\n in: await db.chunks\n .findMany({\n where: { projectId },\n select: { fileId: true }\n })\n .then(chunks => chunks.map(chunk => chunk.fileId))\n }\n }\n }\n });\n } catch (error) {\n console.error('Failed to get uploadFiles by id in database');\n throw error;\n }\n}\n\nexport async function checkUploadFileInfoByMD5(projectId, md5) {\n try {\n return await db.uploadFiles.findFirst({\n where: {\n projectId,\n md5\n }\n });\n } catch (error) {\n console.error('Failed to check uploadFiles by md5 in database');\n throw error;\n }\n}\n\nexport async function createUploadFileInfo(fileInfo) {\n try {\n return await db.uploadFiles.create({ data: fileInfo });\n } catch (error) {\n console.error('Failed to get uploadFiles by id in database');\n throw error;\n }\n}\n\nexport async function delUploadFileInfoById(fileId) {\n try {\n // 1. 获取文件信息\n let fileInfo = await db.uploadFiles.findUnique({ where: { id: fileId } });\n if (!fileInfo) {\n throw new Error('File not found');\n }\n\n // 2. 获取与文件关联的所有文本块\n const chunks = await db.chunks.findMany({\n where: { fileId: fileId }\n });\n\n // 记录统计数据,用于返回给前端显示\n const chunkIds = chunks.map(chunk => chunk.id);\n const stats = {\n chunks: chunks.length,\n questions: 0,\n datasets: 0\n };\n\n // 3. 找出所有关联的问题和数据集\n let questionIds = [];\n let datasets = [];\n\n if (chunkIds.length > 0) {\n // 统计问题数量\n const questionsCount = await db.questions.count({\n where: { chunkId: { in: chunkIds } }\n });\n stats.questions = questionsCount;\n\n // 获取所有问题ID\n const questions = await db.questions.findMany({\n where: { chunkId: { in: chunkIds } },\n select: { id: true }\n });\n\n questionIds = questions.map(q => q.id);\n\n // 4. 统计数据集数量\n if (questionIds.length > 0) {\n const datasetsCount = await db.datasets.count({\n where: { questionId: { in: questionIds } }\n });\n stats.datasets = datasetsCount;\n\n // 获取所有数据集\n datasets = await db.datasets.findMany({\n where: { questionId: { in: questionIds } },\n select: { id: true }\n });\n }\n }\n\n // 5. 使用事务批量删除所有数据库数据\n // 按照外键依赖关系从外到内删除\n const deleteOperations = [];\n\n // 先删除数据集\n if (datasets.length > 0) {\n deleteOperations.push(\n db.datasets.deleteMany({\n where: { id: { in: datasets.map(d => d.id) } }\n })\n );\n }\n\n // 再删除问题\n if (questionIds.length > 0) {\n deleteOperations.push(\n db.questions.deleteMany({\n where: { id: { in: questionIds } }\n })\n );\n }\n\n // 然后删除文本块\n if (chunkIds.length > 0) {\n deleteOperations.push(\n db.chunks.deleteMany({\n where: { id: { in: chunkIds } }\n })\n );\n }\n\n // 最后删除文件记录\n deleteOperations.push(\n db.uploadFiles.delete({\n where: { id: fileId }\n })\n );\n\n // 执行数据库事务,确保原子性\n await db.$transaction(deleteOperations);\n\n // 6. 删除文件系统中的文件\n let projectPath = path.join(fileInfo.path, fileInfo.fileName);\n if (fileInfo.fileExt !== '.md') {\n let filePath = path.join(fileInfo.path, fileInfo.fileName.replace(/\\.[^/.]+$/, '.md'));\n if (fs.existsSync(filePath)) {\n await fs.promises.rm(filePath, { recursive: true });\n }\n }\n if (fs.existsSync(projectPath)) {\n await fs.promises.rm(projectPath, { recursive: true });\n }\n\n return { success: true, stats, fileName: fileInfo.fileName, fileInfo };\n } catch (error) {\n console.error('Failed to delete uploadFiles by id in database:', error);\n throw error;\n }\n}\n"], ["/easy-dataset/lib/file/file-process/pdf/util.js", "import { getProjectRoot } from '@/lib/db/base';\nimport path from 'path';\n\nexport async function getFilePageCount(projectId, fileList) {\n const projectRoot = await getProjectRoot();\n let totalPages = 0;\n const { getPageNum } = await import('pdf2md-js');\n for (const file of fileList) {\n if (file.fileName.endsWith('.pdf')) {\n const filePath = path.join(projectRoot, projectId, 'files', file.fileName);\n try {\n const pageCount = await getPageNum(filePath);\n totalPages += pageCount;\n file.pageCount = pageCount;\n } catch (error) {\n console.error(`Failed to get page count for ${file.fileName}:`, error);\n }\n } else {\n totalPages += 1;\n file.pageCount = 1;\n }\n }\n console.log(`Total pages to process: ${totalPages}`);\n return totalPages;\n}\n"], ["/easy-dataset/components/playground/MessageInput.js", "'use client';\n\nimport React, { useState } from 'react';\nimport { Box, TextField, Button, IconButton, Badge, Tooltip } from '@mui/material';\nimport SendIcon from '@mui/icons-material/Send';\nimport ImageIcon from '@mui/icons-material/Image';\nimport CancelIcon from '@mui/icons-material/Cancel';\nimport { useTheme } from '@mui/material/styles';\nimport { playgroundStyles } from '@/styles/playground';\nimport { useTranslation } from 'react-i18next';\n\nconst MessageInput = ({\n userInput,\n handleInputChange,\n handleSendMessage,\n loading,\n selectedModels,\n uploadedImage,\n handleImageUpload,\n handleRemoveImage,\n availableModels\n}) => {\n const theme = useTheme();\n const styles = playgroundStyles(theme);\n const { t } = useTranslation();\n\n const isDisabled = Object.values(loading).some(value => value) || selectedModels.length === 0;\n const isSendDisabled = isDisabled || (!userInput.trim() && !uploadedImage);\n\n // 检查是否有视觉模型被选中\n const hasVisionModel = selectedModels.some(modelId => {\n const model = availableModels.find(m => m.id === modelId);\n return model && model.type === 'vision';\n });\n\n return (\n \n {uploadedImage && (\n \n \n \n \n }\n sx={{ width: '100%' }}\n overlap=\"rectangular\"\n anchorOrigin={{ vertical: 'top', horizontal: 'right' }}\n >\n \n \n \n )}\n \n {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n handleSendMessage();\n }\n }}\n multiline\n maxRows={4}\n />\n {hasVisionModel && (\n \n \n \n \n \n \n \n \n )}\n }\n onClick={handleSendMessage}\n disabled={isSendDisabled}\n sx={styles.sendButton}\n >\n {t('playground.send')}\n \n \n \n );\n};\n\nexport default MessageInput;\n"], ["/easy-dataset/app/projects/[projectId]/text-split/useChunks.js", "'use client';\n\nimport { useState, useCallback } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { toast } from 'sonner';\n\n/**\n * 文本块管理的自定义Hook\n * @param {string} projectId - 项目ID\n * @param {string} [currentFilter='all'] - 当前筛选条件\n * @returns {Object} - 文本块状态和操作方法\n */\nexport default function useChunks(projectId, currentFilter = 'all') {\n const { t } = useTranslation();\n const [chunks, setChunks] = useState([]);\n const [tocData, setTocData] = useState('');\n const [loading, setLoading] = useState(false);\n\n /**\n * 获取文本块列表\n * @param {string} filter - 筛选条件\n */\n const fetchChunks = useCallback(\n async (filter = 'all') => {\n try {\n setLoading(true);\n const response = await fetch(`/api/projects/${projectId}/split?filter=${filter}`);\n\n if (!response.ok) {\n const errorData = await response.json();\n throw new Error(errorData.error || t('textSplit.fetchChunksFailed'));\n }\n\n const data = await response.json();\n setChunks(data.chunks || []);\n\n // 如果有文件结果,处理详细信息\n if (data.toc) {\n console.log(t('textSplit.fileResultReceived'), data.fileResult);\n // 如果有目录结构,设置目录数据\n setTocData(data.toc);\n }\n } catch (error) {\n toast.error(error.message);\n } finally {\n setLoading(false);\n }\n },\n [projectId, t, setLoading, setChunks, setTocData]\n );\n\n /**\n * 处理删除文本块\n * @param {string} chunkId - 文本块ID\n */\n const handleDeleteChunk = useCallback(\n async chunkId => {\n try {\n const response = await fetch(`/api/projects/${projectId}/chunks/${encodeURIComponent(chunkId)}`, {\n method: 'DELETE'\n });\n\n if (!response.ok) {\n const errorData = await response.json();\n throw new Error(errorData.error || t('textSplit.deleteChunkFailed'));\n }\n\n // 更新文本块列表\n setChunks(prev => prev.filter(chunk => chunk.id !== chunkId));\n } catch (error) {\n toast.error(error.message);\n }\n },\n [projectId, t]\n );\n\n /**\n * 处理文本块编辑\n * @param {string} chunkId - 文本块ID\n * @param {string} newContent - 新内容\n */\n const handleEditChunk = useCallback(\n async (chunkId, newContent) => {\n try {\n setLoading(true);\n\n const response = await fetch(`/api/projects/${projectId}/chunks/${encodeURIComponent(chunkId)}`, {\n method: 'PATCH',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({ content: newContent })\n });\n\n if (!response.ok) {\n const errorData = await response.json();\n throw new Error(errorData.error || t('textSplit.editChunkFailed'));\n }\n\n // 更新成功后使用当前筛选条件刷新文本块列表\n // 直接从 URL 获取当前筛选参数,确保获取到的是最新的值\n const url = new URL(window.location.href);\n const filterParam = url.searchParams.get('filter') || 'all';\n await fetchChunks(filterParam);\n\n toast.success(t('textSplit.editChunkSuccess'));\n } catch (error) {\n toast.error(error.message);\n } finally {\n setLoading(false);\n }\n },\n [projectId, t, fetchChunks]\n );\n\n /**\n * 设置文本块列表\n * @param {Array} data - 新的文本块列表\n */\n const updateChunks = useCallback(data => {\n setChunks(data);\n }, []);\n\n /**\n * 添加新的文本块\n * @param {Array} newChunks - 新的文本块列表\n */\n const addChunks = useCallback(newChunks => {\n setChunks(prev => {\n const updatedChunks = [...prev];\n newChunks.forEach(chunk => {\n if (!updatedChunks.find(c => c.id === chunk.id)) {\n updatedChunks.push(chunk);\n }\n });\n return updatedChunks;\n });\n }, []);\n\n /**\n * 设置TOC数据\n * @param {string} toc - TOC数据\n */\n const updateTocData = useCallback(toc => {\n if (toc) {\n setTocData(toc);\n }\n }, []);\n\n return {\n chunks,\n tocData,\n loading,\n fetchChunks,\n handleDeleteChunk,\n handleEditChunk,\n updateChunks,\n addChunks,\n updateTocData,\n setLoading\n };\n}\n"], ["/easy-dataset/components/dataset-square/DatasetSiteList.js", "'use client';\n\nimport { useState, useEffect } from 'react';\nimport { Grid, Box, Typography, Skeleton, Divider, Tabs, Tab, Fade, Chip, useTheme, alpha, Paper } from '@mui/material';\nimport StorageIcon from '@mui/icons-material/Storage';\nimport CategoryIcon from '@mui/icons-material/Category';\nimport StarIcon from '@mui/icons-material/Star';\nimport { DatasetSiteCard } from './DatasetSiteCard';\nimport sites from '@/constant/sites.json';\nimport { useTranslation } from 'react-i18next';\n\nexport function DatasetSiteList() {\n const [loading, setLoading] = useState(true);\n const theme = useTheme();\n const { t } = useTranslation();\n\n // 定义类别\n const CATEGORIES = {\n ALL: t('datasetSquare.categories.all'),\n POPULAR: t('datasetSquare.categories.popular'),\n CHINESE: t('datasetSquare.categories.chinese'),\n ENGLISH: t('datasetSquare.categories.english'),\n RESEARCH: t('datasetSquare.categories.research'),\n MULTIMODAL: t('datasetSquare.categories.multimodal')\n };\n const [activeCategory, setActiveCategory] = useState(CATEGORIES.ALL);\n\n // 模拟加载效果\n useEffect(() => {\n const timer = setTimeout(() => {\n setLoading(false);\n }, 800);\n\n return () => clearTimeout(timer);\n }, []);\n\n // 处理类别切换\n const handleCategoryChange = (event, newValue) => {\n setActiveCategory(newValue);\n };\n\n // 根据当前选中的类别过滤网站\n const getFilteredSites = () => {\n if (activeCategory === CATEGORIES.ALL) {\n return sites;\n } else if (activeCategory === CATEGORIES.POPULAR) {\n return sites.filter(site => site.labels && site.labels.includes(t('datasetSquare.categories.popular')));\n } else if (activeCategory === CATEGORIES.CHINESE) {\n return sites.filter(site => site.labels && site.labels.includes(t('datasetSquare.categories.chinese')));\n } else if (activeCategory === CATEGORIES.ENGLISH) {\n return sites.filter(site => site.labels && site.labels.includes(t('datasetSquare.categories.english')));\n } else if (activeCategory === CATEGORIES.RESEARCH) {\n return sites.filter(site => site.labels && site.labels.includes(t('datasetSquare.categories.research')));\n } else if (activeCategory === CATEGORIES.MULTIMODAL) {\n return sites.filter(site => site.labels && site.labels.includes(t('datasetSquare.categories.multimodal')));\n }\n return sites;\n };\n\n const filteredSites = getFilteredSites();\n\n return (\n \n {/* 类别选择器 */}\n \n \n \n \n {t('datasetSquare.categoryTitle')}\n \n \n\n \n \n }\n iconPosition=\"start\"\n />\n }\n iconPosition=\"start\"\n />\n \n \n \n \n \n \n \n\n {/* 数据集网站列表 */}\n \n {loading ? (\n // 加载骨架屏\n \n {Array.from(new Array(8)).map((_, index) => (\n \n \n \n \n \n \n \n \n \n \n \n ))}\n \n ) : (\n \n \n {/* 结果数量提示 */}\n \n \n {t('datasetSquare.foundResources', { count: filteredSites.length })}{' '}\n \n \n\n {activeCategory !== CATEGORIES.ALL && (\n setActiveCategory(CATEGORIES.ALL)}\n sx={{ borderRadius: 1.5 }}\n />\n )}\n \n\n {filteredSites.length > 0 ? (\n \n {filteredSites.map((site, index) => (\n \n \n \n ))}\n \n ) : (\n \n \n \n {t('datasetSquare.noDatasets')}\n \n \n {t('datasetSquare.tryOtherCategories')}\n \n \n )}\n \n \n )}\n \n \n );\n}\n"], ["/easy-dataset/electron/modules/updater.js", "const { autoUpdater } = require('electron-updater');\nconst { getAppVersion } = require('../util');\n\n/**\n * 设置自动更新\n * @param {BrowserWindow} mainWindow 主窗口\n */\nfunction setupAutoUpdater(mainWindow) {\n autoUpdater.autoDownload = false;\n autoUpdater.allowDowngrade = false;\n\n // 检查更新时出错\n autoUpdater.on('error', error => {\n if (mainWindow) {\n mainWindow.webContents.send('update-error', error.message);\n }\n });\n\n // 检查到更新时\n autoUpdater.on('update-available', info => {\n if (mainWindow) {\n mainWindow.webContents.send('update-available', {\n version: info.version,\n releaseDate: info.releaseDate,\n releaseNotes: info.releaseNotes\n });\n }\n });\n\n // 没有可用更新\n autoUpdater.on('update-not-available', () => {\n if (mainWindow) {\n mainWindow.webContents.send('update-not-available');\n }\n });\n\n // 下载进度\n autoUpdater.on('download-progress', progressObj => {\n if (mainWindow) {\n mainWindow.webContents.send('download-progress', progressObj);\n }\n });\n\n // 下载完成\n autoUpdater.on('update-downloaded', info => {\n if (mainWindow) {\n mainWindow.webContents.send('update-downloaded', {\n version: info.version,\n releaseDate: info.releaseDate,\n releaseNotes: info.releaseNotes\n });\n }\n });\n}\n\n/**\n * 检查更新\n * @param {boolean} isDev 是否为开发环境\n * @returns {Promise} 更新信息\n */\nasync function checkUpdate(isDev) {\n try {\n if (isDev) {\n // 开发环境下模拟更新检查\n return {\n hasUpdate: false,\n currentVersion: getAppVersion(),\n message: '开发环境下不检查更新'\n };\n }\n\n // 返回当前版本信息,并开始检查更新\n const result = await autoUpdater.checkForUpdates();\n return {\n checking: true,\n currentVersion: getAppVersion()\n };\n } catch (error) {\n console.error('检查更新失败:', error);\n return {\n hasUpdate: false,\n currentVersion: getAppVersion(),\n error: error.message\n };\n }\n}\n\n/**\n * 下载更新\n * @returns {Promise} 下载状态\n */\nasync function downloadUpdate() {\n try {\n autoUpdater.downloadUpdate();\n return { downloading: true };\n } catch (error) {\n console.error('下载更新失败:', error);\n return { error: error.message };\n }\n}\n\n/**\n * 安装更新\n * @returns {Object} 安装状态\n */\nfunction installUpdate() {\n autoUpdater.quitAndInstall(false, true);\n return { installing: true };\n}\n\nmodule.exports = {\n setupAutoUpdater,\n checkUpdate,\n downloadUpdate,\n installUpdate\n};\n"], ["/easy-dataset/components/settings/BasicSettings.js", "'use client';\n\nimport { useState, useEffect } from 'react';\nimport { Typography, Box, Button, TextField, Grid, Card, CardContent, Alert, Snackbar } from '@mui/material';\nimport SaveIcon from '@mui/icons-material/Save';\nimport { useTranslation } from 'react-i18next';\n\nexport default function BasicSettings({ projectId }) {\n const { t } = useTranslation();\n const [projectInfo, setProjectInfo] = useState({\n id: '',\n name: '',\n description: ''\n });\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n const [success, setSuccess] = useState(false);\n\n useEffect(() => {\n async function fetchProjectInfo() {\n try {\n setLoading(true);\n const response = await fetch(`/api/projects/${projectId}`);\n\n if (!response.ok) {\n throw new Error(t('projects.fetchFailed'));\n }\n\n const data = await response.json();\n setProjectInfo(data);\n } catch (error) {\n console.error('获取项目信息出错:', error);\n setError(error.message);\n } finally {\n setLoading(false);\n }\n }\n\n fetchProjectInfo();\n }, [projectId, t]);\n\n // 处理项目信息变更\n const handleProjectInfoChange = e => {\n const { name, value } = e.target;\n setProjectInfo(prev => ({\n ...prev,\n [name]: value\n }));\n };\n\n // 保存项目信息\n const handleSaveProjectInfo = async () => {\n try {\n const response = await fetch(`/api/projects/${projectId}`, {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n name: projectInfo.name,\n description: projectInfo.description\n })\n });\n\n if (!response.ok) {\n throw new Error(t('projects.saveFailed'));\n }\n\n setSuccess(true);\n } catch (error) {\n console.error('保存项目信息出错:', error);\n setError(error.message);\n }\n };\n\n const handleCloseSnackbar = () => {\n setSuccess(false);\n setError(null);\n };\n\n if (loading) {\n return {t('common.loading')};\n }\n\n return (\n \n \n \n {t('settings.basicInfo')}\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n \n \n {t('settings.saveSuccess')}\n \n \n\n \n \n {error}\n \n \n \n );\n}\n"], ["/easy-dataset/app/api/projects/[projectId]/questions/route.js", "import { NextResponse } from 'next/server';\nimport {\n getAllQuestionsByProjectId,\n getQuestions,\n getQuestionsIds,\n isExistByQuestion,\n saveQuestions,\n updateQuestion\n} from '@/lib/db/questions';\n\n// 获取项目的所有问题\nexport async function GET(request, { params }) {\n try {\n const { projectId } = params;\n // 验证项目ID\n if (!projectId) {\n return NextResponse.json({ error: 'Missing project ID' }, { status: 400 });\n }\n const { searchParams } = new URL(request.url);\n let status = searchParams.get('status');\n let answered = undefined;\n if (status === 'answered') answered = true;\n if (status === 'unanswered') answered = false;\n let selectedAll = searchParams.get('selectedAll');\n if (selectedAll) {\n let data = await getQuestionsIds(projectId, answered, searchParams.get('input'));\n return NextResponse.json(data);\n }\n let all = searchParams.get('all');\n if (all) {\n let data = await getAllQuestionsByProjectId(projectId);\n return NextResponse.json(data);\n }\n // 获取问题列表\n const questions = await getQuestions(\n projectId,\n parseInt(searchParams.get('page')),\n parseInt(searchParams.get('size')),\n answered,\n searchParams.get('input')\n );\n\n return NextResponse.json(questions);\n } catch (error) {\n console.error('Failed to get questions:', String(error));\n return NextResponse.json({ error: error.message || 'Failed to get questions' }, { status: 500 });\n }\n}\n\n// 新增问题\nexport async function POST(request, { params }) {\n try {\n const { projectId } = params;\n const body = await request.json();\n const { question, chunkId, label } = body;\n\n // 验证必要参数\n if (!projectId || !question || !chunkId) {\n return NextResponse.json({ error: 'Missing necessary parameters' }, { status: 400 });\n }\n\n // 检查问题是否已存在\n const existingQuestion = await isExistByQuestion(question);\n if (existingQuestion) {\n return NextResponse.json({ error: 'Question already exists' }, { status: 400 });\n }\n\n // 添加新问题\n let questions = [\n {\n chunkId: chunkId,\n question: question,\n label: label || 'other'\n }\n ];\n // 保存更新后的数据\n let data = await saveQuestions(projectId, questions);\n\n // 返回成功响应\n return NextResponse.json(data);\n } catch (error) {\n console.error('Failed to create question:', String(error));\n return NextResponse.json({ error: error.message || 'Failed to create question' }, { status: 500 });\n }\n}\n\n// 更新问题\nexport async function PUT(request) {\n try {\n const body = await request.json();\n // 保存更新后的数据\n let data = await updateQuestion(body);\n // 返回更新后的问题数据\n return NextResponse.json(data);\n } catch (error) {\n console.error('更新问题失败:', String(error));\n return NextResponse.json({ error: error.message || '更新问题失败' }, { status: 500 });\n }\n}\n"], ["/easy-dataset/app/api/projects/[projectId]/tags/route.js", "import { NextResponse } from 'next/server';\nimport { getTags, createTag, updateTag, deleteTag } from '@/lib/db/tags';\nimport { getQuestionsByTagName } from '@/lib/db/questions';\n\n// 获取项目的标签树\nexport async function GET(request, { params }) {\n try {\n const { projectId } = params;\n\n // 验证项目ID\n if (!projectId) {\n return NextResponse.json({ error: 'Project ID is required' }, { status: 400 });\n }\n\n // 获取标签树\n const tags = await getTags(projectId);\n\n return NextResponse.json({ tags });\n } catch (error) {\n console.error('Failed to obtain the label tree:', String(error));\n return NextResponse.json({ error: error.message || 'Failed to obtain the label tree' }, { status: 500 });\n }\n}\n\n// 更新项目的标签树\nexport async function PUT(request, { params }) {\n try {\n const { projectId } = params;\n\n // 验证项目ID\n if (!projectId) {\n return NextResponse.json({ error: 'Project ID is required' }, { status: 400 });\n }\n\n // 获取请求体\n const { tags } = await request.json();\n if (tags.id === undefined || tags.id === null || tags.id === '') {\n console.log('createTag', tags);\n let res = await createTag(projectId, tags.label, tags.parentId);\n return NextResponse.json({ tags: res });\n } else {\n let res = await updateTag(tags.label, tags.id);\n return NextResponse.json({ tags: res });\n }\n } catch (error) {\n console.error('Failed to update tags:', String(error));\n return NextResponse.json({ error: error.message || 'Failed to update tags' }, { status: 500 });\n }\n}\n\nexport async function POST(request, { params }) {\n try {\n const { projectId } = params;\n\n // 验证项目ID\n if (!projectId) {\n return NextResponse.json({ error: 'Project ID is required' }, { status: 400 });\n }\n const { tagName } = await request.json();\n console.log('tagName', tagName);\n let data = await getQuestionsByTagName(projectId, tagName);\n\n return NextResponse.json(data);\n } catch (error) {\n console.error('Failed to obtain the label tree:', String(error));\n return NextResponse.json({ error: error.message || 'Failed to obtain the label tree' }, { status: 500 });\n }\n}\n\nexport async function DELETE(request, { params }) {\n try {\n const { projectId } = params;\n\n // 验证项目ID\n if (!projectId) {\n return NextResponse.json({ error: 'Project ID is required' }, { status: 400 });\n }\n\n // 获取要删除的标签ID\n const { searchParams } = new URL(request.url);\n const id = searchParams.get('id');\n\n if (!id) {\n return NextResponse.json({ error: '标签 ID 是必需的' }, { status: 400 });\n }\n\n console.log(`正在删除标签: ${id}`);\n const result = await deleteTag(id);\n console.log(`删除标签成功: ${id}`);\n\n return NextResponse.json({ success: true, message: '删除标签成功', data: result });\n } catch (error) {\n console.error('删除标签失败:', String(error));\n return NextResponse.json(\n {\n error: error.message || '删除标签失败',\n success: false\n },\n { status: 500 }\n );\n }\n}\n"], ["/easy-dataset/app/api/projects/migrate/route.js", "import { NextResponse } from 'next/server';\nimport { main } from '@/lib/db/fileToDb';\n\n// 存储迁移任务状态\nconst migrationTasks = new Map();\n\n/**\n * 开始迁移任务\n */\nexport async function POST() {\n try {\n // 生成唯一的任务ID\n const taskId = Date.now().toString();\n\n // 初始化任务状态\n migrationTasks.set(taskId, {\n status: 'running',\n progress: 0,\n total: 0,\n completed: 0,\n error: null,\n startTime: Date.now()\n });\n\n // 异步执行迁移任务\n executeMigration(taskId);\n\n // 返回任务ID\n return NextResponse.json({\n success: true,\n taskId\n });\n } catch (error) {\n console.error('启动迁移任务失败:', String(error));\n return NextResponse.json(\n {\n success: false,\n error: error.message\n },\n { status: 500 }\n );\n }\n}\n\n/**\n * 获取迁移任务状态\n */\nexport async function GET(request) {\n try {\n // 从URL获取任务ID\n const { searchParams } = new URL(request.url);\n const taskId = searchParams.get('taskId');\n\n if (!taskId) {\n return NextResponse.json(\n {\n success: false,\n error: '缺少任务ID'\n },\n { status: 400 }\n );\n }\n\n // 获取任务状态\n const task = migrationTasks.get(taskId);\n\n if (!task) {\n return NextResponse.json(\n {\n success: false,\n error: '任务不存在'\n },\n { status: 404 }\n );\n }\n\n // 返回任务状态\n return NextResponse.json({\n success: true,\n task\n });\n } catch (error) {\n console.error('获取迁移任务状态失败:', String(error));\n return NextResponse.json(\n {\n success: false,\n error: error.message\n },\n { status: 500 }\n );\n }\n}\n\n/**\n * 异步执行迁移任务\n * @param {string} taskId 任务ID\n */\nasync function executeMigration(taskId) {\n try {\n // 获取任务状态\n const task = migrationTasks.get(taskId);\n\n if (!task) {\n console.error(`任务 ${taskId} 不存在`);\n return;\n }\n\n // 更新任务状态为运行中\n task.status = 'running';\n task.progress = 0;\n task.completed = 0;\n task.total = 0;\n task.startTime = Date.now();\n\n // 每秒更新一次任务状态到存储中,以便前端能获取最新进度\n const statusUpdateInterval = setInterval(() => {\n // 只在任务还在运行时更新\n if (task.status === 'running') {\n migrationTasks.set(taskId, { ...task });\n console.log(`更新任务状态: ${taskId}, 进度: ${task.progress}%, 完成: ${task.completed}/${task.total}`);\n } else {\n // 如果任务已经结束,停止定时更新\n clearInterval(statusUpdateInterval);\n }\n }, 1000);\n\n // 执行迁移操作\n // 将任务状态对象传递给main函数,以便实时更新进度\n const count = await main(task);\n\n // 清除状态更新定时器\n clearInterval(statusUpdateInterval);\n\n // 再次确保任务状态为完成\n task.status = 'completed';\n task.progress = 100;\n task.completed = count;\n if (task.total === 0) task.total = count; // 确保总数不为零\n task.endTime = Date.now();\n\n // 更新最终任务状态\n migrationTasks.set(taskId, { ...task });\n\n // 任务完成后,设置一个定时器清理任务状态(例如30分钟后)\n setTimeout(\n () => {\n migrationTasks.delete(taskId);\n console.log(`清理任务状态: ${taskId}`);\n },\n 30 * 60 * 1000\n );\n } catch (error) {\n console.error(`执行迁移任务 ${taskId} 失败:`, String(error));\n\n // 获取任务状态\n const task = migrationTasks.get(taskId);\n\n if (task) {\n // 更新任务状态为失败\n task.status = 'failed';\n task.error = error.message;\n task.endTime = Date.now();\n\n // 更新任务状态\n migrationTasks.set(taskId, task);\n }\n }\n}\n"], ["/easy-dataset/lib/db/base.js", "'use server';\n\nimport fs from 'fs';\nimport path from 'path';\nimport os from 'os';\n\n// 获取适合的数据存储目录\nfunction getDbDirectory() {\n if (process.resourcesPath) {\n const rootPath = String(fs.readFileSync(path.join(process.resourcesPath, 'root-path.txt')));\n if (rootPath) {\n return rootPath;\n }\n }\n // 检查是否在浏览器环境中运行\n if (typeof window !== 'undefined') {\n // 检查是否在 Electron 渲染进程中运行\n if (window.electron && window.electron.getUserDataPath) {\n // 使用 preload 脚本中暴露的 API 获取用户数据目录\n const userDataPath = window.electron.getUserDataPath();\n if (userDataPath) {\n return path.join(userDataPath, 'local-db');\n }\n }\n\n // 如果不是 Electron 或获取失败,则使用开发环境的路径\n return path.join(process.cwd(), 'local-db');\n } else if (process.versions && process.versions.electron) {\n // 在 Electron 主进程中运行\n try {\n const { app } = require('electron');\n return path.join(app.getPath('userData'), 'local-db');\n } catch (error) {\n console.error('Failed to get user data directory:', String(error), path.join(os.homedir(), '.easy-dataset-db'));\n // 降级处理,使用临时目录\n return path.join(os.homedir(), '.easy-dataset-db');\n }\n } else {\n // 在普通 Node.js 环境中运行(开发模式)\n return path.join(process.cwd(), 'local-db');\n }\n}\n\nlet PROJECT_ROOT = '';\n\n// 获取项目根目录\nexport async function getProjectRoot() {\n if (!PROJECT_ROOT) {\n PROJECT_ROOT = getDbDirectory();\n }\n return PROJECT_ROOT;\n}\n\n// 确保数据库目录存在\nexport async function ensureDbExists() {\n try {\n await fs.promises.access(PROJECT_ROOT);\n } catch (error) {\n await fs.promises.mkdir(PROJECT_ROOT, { recursive: true });\n }\n}\n\n// 读取JSON文件\nexport async function readJsonFile(filePath) {\n try {\n await fs.promises.access(filePath);\n const data = await fs.promises.readFile(filePath, 'utf8');\n return JSON.parse(data);\n } catch (error) {\n return null;\n }\n}\n\n// 写入JSON文件\nexport async function writeJsonFile(filePath, data) {\n // 使用临时文件策略,避免写入中断导致文件损坏\n const tempFilePath = `${filePath}_${Date.now()}.tmp`;\n try {\n // 序列化为JSON字符串\n const jsonString = JSON.stringify(data, null, 2);\n // 先写入临时文件\n await fs.promises.writeFile(tempFilePath, jsonString, 'utf8');\n\n // 从临时文件读取内容并验证\n try {\n const writtenContent = await fs.promises.readFile(tempFilePath, 'utf8');\n JSON.parse(writtenContent); // 验证JSON是否有效\n // 验证通过后,原子性地重命名文件替换原文件\n await fs.promises.rename(tempFilePath, filePath);\n } catch (validationError) {\n // 验证失败,删除临时文件并抛出错误\n await fs.promises.unlink(tempFilePath).catch(() => {});\n throw new Error(`写入的JSON文件内容无效: ${validationError.message}`);\n }\n return data;\n } catch (error) {\n console.error(`写入JSON文件 ${filePath} 失败:`, error);\n throw error;\n } finally {\n // 确保临时文件被删除\n await fs.promises.unlink(tempFilePath).catch(() => {});\n }\n}\n\n// 确保目录存在\nexport async function ensureDir(dirPath) {\n try {\n await fs.promises.access(dirPath);\n } catch (error) {\n await fs.promises.mkdir(dirPath, { recursive: true });\n }\n}\n"], ["/easy-dataset/lib/db/index.js", "import { PrismaClient } from '@prisma/client';\n\nconst createPrismaClient = () =>\n new PrismaClient({\n // log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error']\n log: ['error']\n });\n\nconst globalForPrisma = globalThis;\n\nexport const db = globalForPrisma.prisma || createPrismaClient();\n\nif (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = db;\n"], ["/easy-dataset/lib/api/file.js", "import i18n from '@/lib/i18n';\nimport { request } from '@/lib/util/request';\n\n/**\n * 上传文件\n * @param {File} file 文件\n * @param {string} projectId 项目ID\n * @param {string} fileContent 文件内容\n * @param {string} fileName 文件名\n * @param {function} t 国际化函数\n * @returns\n */\nexport async function uploadFile({ file, projectId, fileContent, fileName, t }) {\n return await request(`/api/projects/${projectId}/files`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/octet-stream',\n 'x-file-name': encodeURIComponent(fileName)\n },\n body: file.name.endsWith('.docx') ? new TextEncoder().encode(fileContent) : fileContent,\n errMsg: t('textSplit.uploadFailed')\n });\n}\n\n/**\n * 删除文件\n * @param {Object} fileToDelete 文件信息\n * @param {string} projectId 项目ID\n * @param {string} domainTreeActionType 域树处理方式\n * @param {Object} modelInfo 模型信息\n * @returns\n */\nexport async function deleteFile({ fileToDelete, projectId, domainTreeActionType, modelInfo }) {\n return await request(\n `/api/projects/${projectId}/files?fileId=${fileToDelete.fileId}&domainTreeAction=${domainTreeActionType || 'keep'}`,\n {\n method: 'DELETE',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n model: modelInfo,\n language: i18n.language === 'zh-CN' ? '中文' : 'en'\n })\n }\n );\n}\n\n/**\n * 获取文件列表\n * @param {string} projectId 项目ID\n * @param {number} page 页码\n * @param {number} size 每页大小\n * @param {string} fileName 搜索文件名(可选)\n */\nexport async function getFiles({ projectId, page, size, fileName }) {\n const params = new URLSearchParams({\n page: page.toString(),\n pageSize: size.toString()\n });\n\n if (fileName && fileName.trim()) {\n params.append('fileName', fileName.trim());\n }\n\n return await request(`/api/projects/${projectId}/files?${params}`);\n}\n"], ["/easy-dataset/app/api/projects/[projectId]/datasets/[datasetId]/route.js", "import { NextResponse } from 'next/server';\nimport { getDatasetsById, getDatasetsCounts, getNavigationItems } from '@/lib/db/datasets';\n\n/**\n * 获取项目的所有数据集\n */\nexport async function GET(request, { params }) {\n try {\n const { projectId, datasetId } = params;\n // 验证项目ID\n if (!projectId) {\n return NextResponse.json({ error: '项目ID不能为空' }, { status: 400 });\n }\n if (!datasetId) {\n return NextResponse.json({ error: '数据集ID不能为空' }, { status: 400 });\n }\n const { searchParams } = new URL(request.url);\n const operateType = searchParams.get('operateType');\n if (operateType !== null) {\n const data = await getNavigationItems(projectId, datasetId, operateType);\n return NextResponse.json(data);\n }\n const datasets = await getDatasetsById(datasetId);\n let counts = await getDatasetsCounts(projectId);\n\n return NextResponse.json({ datasets, ...counts });\n } catch (error) {\n console.error('获取数据集详情失败:', String(error));\n return NextResponse.json(\n {\n error: error.message || '获取数据集详情失败'\n },\n { status: 500 }\n );\n }\n}\n"], ["/easy-dataset/components/datasets/DatasetMetadata.js", "'use client';\n\nimport { Box, Typography, Chip, Tooltip, alpha, CircularProgress } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\nimport { useTheme } from '@mui/material/styles';\nimport { useState } from 'react';\n\n/**\n * 数据集元数据展示组件\n */\nexport default function DatasetMetadata({ currentDataset, onViewChunk }) {\n const { t } = useTranslation();\n const theme = useTheme();\n\n return (\n \n \n {t('datasets.metadata')}\n \n \n \n {currentDataset.questionLabel && (\n \n )}\n \n \n {\n try {\n // 使用新API接口获取文本块内容\n const response = await fetch(\n `/api/projects/${currentDataset.projectId}/chunks/name?chunkName=${encodeURIComponent(currentDataset.chunkName)}`\n );\n\n if (!response.ok) {\n throw new Error(`获取文本块失败: ${response.statusText}`);\n }\n\n const chunkData = await response.json();\n\n // 调用父组件的方法显示文本块\n onViewChunk({\n name: currentDataset.chunkName,\n content: chunkData.content\n });\n } catch (error) {\n console.error('获取文本块内容失败:', error);\n // 即使API请求失败,也尝试调用查看方法\n onViewChunk({\n name: currentDataset.chunkName,\n content: '内容加载失败,请重试'\n });\n }\n }}\n sx={{ cursor: 'pointer' }}\n />\n \n {currentDataset.confirmed && (\n \n )}\n \n \n );\n}\n"], ["/easy-dataset/app/projects/[projectId]/layout.js", "'use client';\n\nimport Navbar from '@/components/Navbar';\nimport { useState, useEffect } from 'react';\nimport { Box, CircularProgress, Typography, Button } from '@mui/material';\nimport { useRouter } from 'next/navigation';\nimport { useTranslation } from 'react-i18next';\n\nexport default function ProjectLayout({ children, params }) {\n const router = useRouter();\n const { projectId } = params;\n const [projects, setProjects] = useState([]);\n const [currentProject, setCurrentProject] = useState(null);\n const [models, setModels] = useState([]);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n const [t] = useTranslation();\n // 定义获取数据的函数\n const fetchData = async () => {\n try {\n setLoading(true);\n\n // 获取用户创建的项目详情\n const projectsResponse = await fetch(`/api/projects`);\n if (!projectsResponse.ok) {\n throw new Error(t('projects.fetchFailed'));\n }\n const projectsData = await projectsResponse.json();\n setProjects(projectsData);\n\n // 获取当前项目详情\n const projectResponse = await fetch(`/api/projects/${projectId}`);\n if (!projectResponse.ok) {\n // 如果项目不存在,跳转到首页\n if (projectResponse.status === 404) {\n router.push('/');\n return;\n }\n throw new Error('获取项目详情失败');\n }\n const projectData = await projectResponse.json();\n setCurrentProject(projectData);\n } catch (error) {\n console.error('加载项目数据出错:', error);\n setError(error.message);\n } finally {\n setLoading(false);\n }\n };\n\n // 初始加载数据\n useEffect(() => {\n // 如果 projectId 是 undefined 或 \"undefined\",直接重定向到首页\n if (!projectId || projectId === 'undefined') {\n router.push('/');\n return;\n }\n\n fetchData();\n }, [projectId, router]);\n\n if (loading) {\n return (\n \n \n 加载项目数据...\n \n );\n }\n\n if (error) {\n return (\n \n \n {t('projects.fetchFailed')}: {error}\n \n \n \n );\n }\n\n return (\n <>\n \n
{children}
\n \n );\n}\n"], ["/easy-dataset/app/api/projects/[projectId]/preview/[fileId]/route.js", "import { NextResponse } from 'next/server';\nimport fs from 'fs';\nimport path from 'path';\nimport { getProjectRoot } from '@/lib/db/base';\nimport { getUploadFileInfoById } from '@/lib/db/upload-files';\n\n// 获取文件内容\nexport async function GET(request, { params }) {\n try {\n const { projectId, fileId } = params;\n\n // 验证参数\n if (!projectId) {\n return NextResponse.json({ error: 'Project ID cannot be empty' }, { status: 400 });\n }\n\n // 获取项目根目录\n let fileInfo = await getUploadFileInfoById(fileId);\n if (!fileInfo) {\n return NextResponse.json({ error: 'file does not exist' }, { status: 400 });\n }\n\n // 获取文件路径\n let filePath = path.join(fileInfo.path, fileInfo.fileName);\n if (fileInfo.fileExt !== '.md') {\n filePath = path.join(fileInfo.path, fileInfo.fileName.replace(/\\.[^/.]+$/, '.md'));\n }\n //获取文件\n const buffer = fs.readFileSync(filePath);\n\n const text = buffer.toString('utf-8');\n\n return NextResponse.json({\n fileId: fileId,\n fileName: fileInfo.fileName,\n content: text\n });\n } catch (error) {\n console.error('Failed to get text block content:', String(error));\n return NextResponse.json({ error: error.message || 'Failed to get text block content' }, { status: 500 });\n }\n}\n"], ["/easy-dataset/app/api/projects/[projectId]/questions/tree/route.js", "import { NextResponse } from 'next/server';\nimport { getQuestionsForTree, getQuestionsByTag } from '@/lib/db/questions';\n\n/**\n * 获取项目的问题树形视图数据\n * @param {Request} request - 请求对象\n * @param {Object} params - 路由参数\n * @returns {Promise} - 包含问题数据的响应\n */\nexport async function GET(request, { params }) {\n try {\n const { projectId } = params;\n\n // 验证项目ID\n if (!projectId) {\n return NextResponse.json({ error: '项目ID不能为空' }, { status: 400 });\n }\n\n const { searchParams } = new URL(request.url);\n const tag = searchParams.get('tag');\n const input = searchParams.get('input');\n const tagsOnly = searchParams.get('tagsOnly') === 'true';\n const isDistill = searchParams.get('isDistill') === 'true';\n\n if (tag) {\n // 获取指定标签的问题数据(包含完整字段)\n const questions = await getQuestionsByTag(projectId, tag, input, isDistill);\n return NextResponse.json(questions);\n } else if (tagsOnly) {\n // 只获取标签信息(仅包含 id 和 label 字段)\n const treeData = await getQuestionsForTree(projectId, input, isDistill);\n return NextResponse.json(treeData);\n } else {\n // 兼容原有请求,获取树形视图数据(仅包含 id 和 label 字段)\n const treeData = await getQuestionsForTree(projectId, null, isDistill);\n return NextResponse.json(treeData);\n }\n } catch (error) {\n console.error('获取问题树形数据失败:', String(error));\n return NextResponse.json({ error: error.message || '获取问题树形数据失败' }, { status: 500 });\n }\n}\n"], ["/easy-dataset/lib/llm/prompts/newAnswer.js", "module.exports = function getNewAnswerPrompt(question, answer, cot, advice) {\n return `\n# Role: 微调数据集答案优化专家\n## Profile:\n- Description: 你是一名微调数据集答案优化专家,擅长根据用户的改进建议,对问题的回答结果和思考过程(思维链)进行优化\n\n## Skills:\n1. 基于给定的优化建议 + 问题,对输入的答案进行优化,并进行适当的丰富和补充\n3. 能够根据优化建议,对答案的思考过程(思维链)进行优化,去除思考过程中参考资料相关的描述(不要在推理逻辑中体现有参考资料,改为正常的推理思路)\n \n\n## 原始问题\n${question}\n\n## 待优化的答案\n${answer}\n\n## 答案优化建议\n${advice},同时对答案进行适当的丰富和补充,确保答案准确、充分、清晰\n\n## 待优化的思考过程\n${cot}\n\n## 思考过程优化建议\n- 通用优化建议:${advice}\n- 去除思考过程中参考资料相关的描述(如:\"根据...\"、\"引用...\"、\"参考...\"等),不要在推理逻辑中体现有参考资料,改为正常的推理思路。\n\n## Constrains:\n1. 结果必须按照 JSON 格式输出(如果给到的待优化思考过程为空,则输出的 COT 字段也为空):\n \\`\\`\\`json\n {\n \"answer\": \"优化后的答案\",\n \"cot\": \"优化后的思考过程\"\n }\n \\`\\`\\`\n `;\n};\n"], ["/easy-dataset/components/distill/utils.js", "'use client';\n\n/**\n * 按照标签前面的序号对标签进行排序\n * @param {Array} tags - 标签数组\n * @returns {Array} 排序后的标签数组\n */\nexport const sortTagsByNumber = tags => {\n return [...tags].sort((a, b) => {\n // 提取标签前面的序号\n const getNumberPrefix = label => {\n // 匹配形如 1, 1.1, 1.1.2 的序号\n const match = label.match(/^([\\d.]+)\\s/);\n if (match) {\n return match[1]; // 返回完整的序号字符串,如 \"1.10\"\n }\n return null; // 没有序号\n };\n\n const aPrefix = getNumberPrefix(a.label);\n const bPrefix = getNumberPrefix(b.label);\n\n // 如果两个标签都有序号,按序号比较\n if (aPrefix && bPrefix) {\n // 将序号分解为数组,然后按数值比较\n const aParts = aPrefix.split('.').map(num => parseInt(num, 10));\n const bParts = bPrefix.split('.').map(num => parseInt(num, 10));\n\n // 比较序号数组\n for (let i = 0; i < Math.min(aParts.length, bParts.length); i++) {\n if (aParts[i] !== bParts[i]) {\n return aParts[i] - bParts[i]; // 数值比较,确保 1.2 排在 1.10 前面\n }\n }\n // 如果前面的数字都相同,则较短的序号在前\n return aParts.length - bParts.length;\n }\n // 如果只有一个标签有序号,则有序号的在前\n else if (aPrefix) {\n return -1;\n } else if (bPrefix) {\n return 1;\n }\n // 如果都没有序号,则按原来的字母序排序\n else {\n return a.label.localeCompare(b.label, 'zh-CN');\n }\n });\n};\n\n/**\n * 获取标签的完整路径\n * @param {Object} tag - 标签对象\n * @param {Array} allTags - 所有标签数组\n * @returns {string} 标签路径,如 \"标签1 > 标签2 > 标签3\"\n */\nexport const getTagPath = (tag, allTags) => {\n if (!tag) return '';\n\n const findPath = (currentTag, path = []) => {\n const newPath = [currentTag.label, ...path];\n\n if (!currentTag.parentId) return newPath;\n\n const parentTag = allTags.find(t => t.id === currentTag.parentId);\n if (!parentTag) return newPath;\n\n return findPath(parentTag, newPath);\n };\n\n return findPath(tag).join(' > ');\n};\n"], ["/easy-dataset/electron/preload.js", "const { contextBridge, ipcRenderer } = require('electron');\n\n// 在渲染进程中暴露安全的 API\ncontextBridge.exposeInMainWorld('electron', {\n // 获取应用版本\n getAppVersion: () => ipcRenderer.invoke('get-app-version'),\n\n // 获取当前语言\n getLanguage: () => {\n // 尝试从本地存储获取语言设置\n const storedLang = localStorage.getItem('i18nextLng');\n // 如果存在则返回,否则返回系统语言或默认为中文\n return storedLang || navigator.language.startsWith('zh') ? 'zh' : 'en';\n },\n\n // 获取用户数据目录\n getUserDataPath: () => {\n try {\n return ipcRenderer.sendSync('get-user-data-path');\n } catch (error) {\n console.error('获取用户数据目录失败:', error);\n return null;\n }\n },\n\n // 更新相关 API\n updater: {\n // 检查更新\n checkForUpdates: () => ipcRenderer.invoke('check-update'),\n\n // 下载更新\n downloadUpdate: () => ipcRenderer.invoke('download-update'),\n\n // 安装更新\n installUpdate: () => ipcRenderer.invoke('install-update'),\n\n // 监听更新事件\n onUpdateAvailable: callback => {\n const handler = (_, info) => callback(info);\n ipcRenderer.on('update-available', handler);\n return () => ipcRenderer.removeListener('update-available', handler);\n },\n\n onUpdateNotAvailable: callback => {\n const handler = () => callback();\n ipcRenderer.on('update-not-available', handler);\n return () => ipcRenderer.removeListener('update-not-available', handler);\n },\n\n onUpdateError: callback => {\n const handler = (_, error) => callback(error);\n ipcRenderer.on('update-error', handler);\n return () => ipcRenderer.removeListener('update-error', handler);\n },\n\n onDownloadProgress: callback => {\n const handler = (_, progress) => callback(progress);\n ipcRenderer.on('download-progress', handler);\n return () => ipcRenderer.removeListener('download-progress', handler);\n },\n\n onUpdateDownloaded: callback => {\n const handler = (_, info) => callback(info);\n ipcRenderer.on('update-downloaded', handler);\n return () => ipcRenderer.removeListener('update-downloaded', handler);\n }\n }\n});\n\n// 通知渲染进程 preload 脚本已加载完成\nwindow.addEventListener('DOMContentLoaded', () => {\n console.log('Electron preload script loaded');\n});\n"], ["/easy-dataset/app/api/projects/[projectId]/distill/questions/by-tag/route.js", "import { NextResponse } from 'next/server';\nimport { db } from '@/lib/db';\n\n/**\n * 根据标签ID获取问题列表\n */\nexport async function GET(request, { params }) {\n try {\n const { projectId } = params;\n const { searchParams } = new URL(request.url);\n const tagId = searchParams.get('tagId');\n\n console.log('[distill/questions/by-tag] 请求参数:', { projectId, tagId });\n\n // 验证参数\n if (!projectId) {\n return NextResponse.json({ error: '项目ID不能为空' }, { status: 400 });\n }\n\n if (!tagId) {\n return NextResponse.json({ error: '标签ID不能为空' }, { status: 400 });\n }\n\n // 获取标签信息\n const tag = await db.tags.findUnique({\n where: { id: tagId }\n });\n\n if (!tag) {\n return NextResponse.json({ error: '标签不存在' }, { status: 404 });\n }\n\n console.log('[distill/questions/by-tag] 标签信息:', tag);\n\n // 获取或创建蒸馏文本块\n let distillChunk = await db.chunks.findFirst({\n where: {\n projectId,\n name: 'Distilled Content'\n }\n });\n\n if (!distillChunk) {\n // 创建一个特殊的蒸馏文本块\n distillChunk = await db.chunks.create({\n data: {\n name: 'Distilled Content',\n projectId,\n fileId: 'distilled',\n fileName: 'distilled.md',\n content:\n 'This text block is used to store questions generated through data distillation and is not related to actual literature.',\n summary: 'Questions generated through data distillation',\n size: 0\n }\n });\n }\n const questions = await db.questions.findMany({\n where: {\n projectId,\n label: tag.label,\n chunkId: distillChunk.id\n }\n });\n\n return NextResponse.json(questions);\n } catch (error) {\n console.error('[distill/questions/by-tag] 获取问题失败:', String(error));\n return NextResponse.json({ error: error.message || '获取问题失败' }, { status: 500 });\n }\n}\n"], ["/easy-dataset/app/projects/[projectId]/datasets/components/DatasetList.js", "'use client';\n\nimport { useState } from 'react';\nimport {\n Box,\n Typography,\n IconButton,\n Table,\n TableBody,\n TableCell,\n TableContainer,\n TableHead,\n TableRow,\n Chip,\n Divider,\n useTheme,\n alpha,\n Tooltip,\n Checkbox,\n TablePagination,\n Card,\n TextField\n} from '@mui/material';\nimport DeleteIcon from '@mui/icons-material/Delete';\nimport VisibilityIcon from '@mui/icons-material/Visibility';\nimport { useTranslation } from 'react-i18next';\n\n// 数据集列表组件\nconst DatasetList = ({\n datasets,\n onViewDetails,\n onDelete,\n page,\n rowsPerPage,\n onPageChange,\n onRowsPerPageChange,\n total,\n selectedIds,\n onSelectAll,\n onSelectItem\n}) => {\n const theme = useTheme();\n const { t } = useTranslation();\n const bgColor = theme.palette.mode === 'dark' ? theme.palette.primary.dark : theme.palette.primary.light;\n const color =\n theme.palette.mode === 'dark'\n ? theme.palette.getContrastText(theme.palette.primary.main)\n : theme.palette.getContrastText(theme.palette.primary.contrastText);\n return (\n \n \n \n \n \n \n 0 && selectedIds.length < total}\n checked={total > 0 && selectedIds.length === total}\n onChange={onSelectAll}\n />\n \n \n {t('datasets.question')}\n \n \n {t('datasets.createdAt')}\n \n \n {t('datasets.model')}\n \n \n {t('datasets.domainTag')}\n \n \n {t('datasets.cot')}\n \n \n {t('datasets.answer')}\n \n {/* \n {t('datasets.chunkId')}\n */}\n \n {t('common.actions')}\n \n \n \n \n {datasets.map((dataset, index) => (\n onViewDetails(dataset.id)}\n >\n \n {\n e.stopPropagation();\n onSelectItem(dataset.id);\n }}\n onClick={e => e.stopPropagation()}\n />\n \n \n \n {dataset.confirmed}\n {dataset.confirmed && (\n \n )}\n {dataset.question}\n \n \n \n \n {new Date(dataset.createAt).toLocaleString('zh-CN')}\n \n \n \n \n \n \n {dataset.questionLabel ? (\n \n ) : (\n \n {t('datasets.noTag')}\n \n )}\n \n \n \n \n \n \n {dataset.answer}\n \n \n {/* \n \n {dataset.chunkId}\n \n */}\n \n \n \n {\n e.stopPropagation();\n onViewDetails(dataset.id);\n }}\n sx={{\n color: theme.palette.primary.main,\n '&:hover': { backgroundColor: alpha(theme.palette.primary.main, 0.1) }\n }}\n >\n \n \n \n \n {\n e.stopPropagation();\n onDelete(dataset);\n }}\n sx={{\n color: theme.palette.error.main,\n '&:hover': { backgroundColor: alpha(theme.palette.error.main, 0.1) }\n }}\n >\n \n \n \n \n \n \n ))}\n {datasets.length === 0 && (\n \n \n \n {t('datasets.noData')}\n \n \n \n )}\n \n
\n
\n \n \n t('datasets.pagination', { from, to, count })}\n sx={{\n '.MuiTablePagination-selectLabel, .MuiTablePagination-displayedRows': {\n fontWeight: 'medium'\n },\n border: 'none'\n }}\n />\n \n {t('common.jumpTo')}:\n {\n if (e.key === 'Enter') {\n const pageNum = parseInt(e.target.value, 10);\n if (pageNum >= 1 && pageNum <= Math.ceil(total / rowsPerPage)) {\n onPageChange(null, pageNum - 1);\n e.target.value = '';\n }\n }\n }}\n />\n \n \n
\n );\n};\n\nexport default DatasetList;\n"], ["/easy-dataset/app/api/projects/[projectId]/datasets/export/route.js", "import { NextResponse } from 'next/server';\nimport { getDatasets } from '@/lib/db/datasets';\n\n/**\n * 获取导出数据集\n */\nexport async function GET(request, { params }) {\n try {\n const { projectId } = params;\n const { searchParams } = new URL(request.url);\n // 验证项目ID\n if (!projectId) {\n return NextResponse.json({ error: '项目ID不能为空' }, { status: 400 });\n }\n let status = searchParams.get('status');\n let confirmed = undefined;\n if (status === 'confirmed') confirmed = true;\n if (status === 'unconfirmed') confirmed = false;\n // 获取数据集\n let datasets = await getDatasets(projectId, confirmed);\n return NextResponse.json(datasets);\n } catch (error) {\n console.error('获取数据集失败:', String(error));\n return NextResponse.json(\n {\n error: error.message || '获取数据集失败'\n },\n { status: 500 }\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/app/api/projects/[projectId]/chunks/[chunkId]/route.js", "import { NextResponse } from 'next/server';\nimport { deleteChunkById, getChunkById, updateChunkById } from '@/lib/db/chunks';\n\n// 获取文本块内容\nexport async function GET(request, { params }) {\n try {\n const { projectId, chunkId } = params;\n // 验证参数\n if (!projectId) {\n return NextResponse.json({ error: 'Project ID cannot be empty' }, { status: 400 });\n }\n if (!chunkId) {\n return NextResponse.json({ error: 'Text block ID cannot be empty' }, { status: 400 });\n }\n // 获取文本块内容\n const chunk = await getChunkById(chunkId);\n\n return NextResponse.json(chunk);\n } catch (error) {\n console.error('Failed to get text block content:', String(error));\n return NextResponse.json({ error: error.message || 'Failed to get text block content' }, { status: 500 });\n }\n}\n\n// 删除文本块\nexport async function DELETE(request, { params }) {\n try {\n const { projectId, chunkId } = params;\n // 验证参数\n if (!projectId) {\n return NextResponse.json({ error: 'Project ID cannot be empty' }, { status: 400 });\n }\n if (!chunkId) {\n return NextResponse.json({ error: 'Text block ID cannot be empty' }, { status: 400 });\n }\n await deleteChunkById(chunkId);\n\n return NextResponse.json({ message: 'Text block deleted successfully' });\n } catch (error) {\n console.error('Failed to delete text block:', String(error));\n return NextResponse.json({ error: error.message || 'Failed to delete text block' }, { status: 500 });\n }\n}\n\n// 编辑文本块内容\nexport async function PATCH(request, { params }) {\n try {\n const { projectId, chunkId } = params;\n\n // 验证参数\n if (!projectId) {\n return NextResponse.json({ error: '项目ID不能为空' }, { status: 400 });\n }\n\n if (!chunkId) {\n return NextResponse.json({ error: '文本块ID不能为空' }, { status: 400 });\n }\n\n // 解析请求体获取新内容\n const requestData = await request.json();\n const { content } = requestData;\n\n if (!content) {\n return NextResponse.json({ error: '内容不能为空' }, { status: 400 });\n }\n\n let res = await updateChunkById(chunkId, { content });\n return NextResponse.json(res);\n } catch (error) {\n console.error('编辑文本块失败:', String(error));\n return NextResponse.json({ error: error.message || '编辑文本块失败' }, { status: 500 });\n }\n}\n"], ["/easy-dataset/lib/llm/prompts/distillQuestions.js", "function removeLeadingNumber(label) {\n // 正则说明:\n // ^\\d+ 匹配开头的一个或多个数字\n // (?:\\.\\d+)* 匹配零个或多个「点+数字」的组合(非捕获组)\n // \\s+ 匹配序号后的一个或多个空格(确保序号与内容有空格分隔)\n const numberPrefixRegex = /^\\d+(?:\\.\\d+)*\\s+/;\n // 仅当匹配到数字开头的序号时才替换,否则返回原标签\n return label.replace(numberPrefixRegex, '');\n}\n\n/**\n * 根据标签构造问题的提示词\n * @param {string} tagPath - 标签链路,例如 \"体育->足球->足球先生\"\n * @param {string} currentTag - 当前子标签,例如 \"足球先生\"\n * @param {number} count - 希望生成问题的数量,例如:10\n * @param {Array} existingQuestions - 当前标签已经生成的问题(避免重复)\n * @param {string} globalPrompt - 项目全局提示词\n * @returns {string} 提示词\n */\nexport function distillQuestionsPrompt(tagPath, currentTag, count = 10, existingQuestions = [], globalPrompt = '') {\n currentTag = removeLeadingNumber(currentTag);\n const existingQuestionsText =\n existingQuestions.length > 0\n ? `已有的问题包括:\\n${existingQuestions.map(q => `- ${q}`).join('\\n')}\\n请不要生成与这些重复或高度相似的问题。`\n : '';\n\n // 构建全局提示词部分\n const globalPromptText = globalPrompt ? `你必须遵循这个要求:${globalPrompt}` : '';\n\n return `\n你是一个专业的知识问题生成助手,精通${currentTag}领域的知识。我需要你帮我为标签\"${currentTag}\"生成${count}个高质量、多样化的问题。\n\n标签完整链路是:${tagPath}\n\n请遵循以下规则:\n${globalPromptText}\n1. 生成的问题必须与\"${currentTag}\"主题紧密相关,确保全面覆盖该主题的核心知识点和关键概念\n2. 问题应该均衡分布在以下难度级别(每个级别至少占20%):\n - 基础级:适合入门者,关注基本概念、定义和简单应用\n - 中级:需要一定领域知识,涉及原理解释、案例分析和应用场景\n - 高级:需要深度思考,包括前沿发展、跨领域联系、复杂问题解决方案等\n\n3. 问题类型应多样化,包括但不限于(以下只是参考,可以根据实际情况灵活调整,不一定要限定下面的主题):\n - 概念解释类:\"什么是...\"、\"如何定义...\"\n - 原理分析类:\"为什么...\"、\"如何解释...\"\n - 比较对比类:\"...与...有何区别\"、\"...相比...的优势是什么\"\n - 应用实践类:\"如何应用...解决...\"、\"...的最佳实践是什么\"\n - 发展趋势类:\"...的未来发展方向是什么\"、\"...面临的挑战有哪些\"\n - 案例分析类:\"请分析...案例中的...\"\n - 启发思考类:\"如果...会怎样\"、\"如何评价...\"\n\n4. 问题表述要清晰、准确、专业,避免以下问题:\n - 避免模糊或过于宽泛的表述\n - 避免可以简单用\"是/否\"回答的封闭性问题\n - 避免包含误导性假设的问题\n - 避免重复或高度相似的问题\n \n5. 问题的深度和广度要适当(以下只是参考,可以根据实际情况灵活调整,不一定要限定下面的主题):\n - 覆盖主题的历史、现状、理论基础和实际应用\n - 包含该领域的主流观点和争议话题\n - 考虑该主题与相关领域的交叉关联\n - 关注该领域的新兴技术、方法或趋势\n\n${existingQuestionsText}\n\n请直接以JSON数组格式返回问题,不要有任何额外的解释或说明,格式如下:\n[\"问题1\", \"问题2\", \"问题3\", ...]\n\n注意:每个问题应该是完整的、自包含的,无需依赖其他上下文即可理解和回答。\n`;\n}\n"], ["/easy-dataset/app/dataset-square/page.js", "'use client';\n\nimport { useState, useEffect } from 'react';\nimport { Box, Container, Typography, Paper, Divider, useTheme, alpha } from '@mui/material';\nimport StorageIcon from '@mui/icons-material/Storage';\nimport Navbar from '@/components/Navbar';\nimport { DatasetSearchBar } from '@/components/dataset-square/DatasetSearchBar';\nimport { DatasetSiteList } from '@/components/dataset-square/DatasetSiteList';\nimport { useTranslation } from 'react-i18next';\n\nexport default function DatasetSquarePage() {\n const [projects, setProjects] = useState([]);\n const theme = useTheme();\n const { t } = useTranslation();\n\n // 获取项目列表和模型列表\n useEffect(() => {\n async function fetchData() {\n try {\n // 获取用户创建的项目详情\n const response = await fetch('/api/projects');\n if (response.ok) {\n const projectsData = await response.json();\n setProjects(projectsData);\n }\n } catch (error) {\n console.error('获取数据失败:', error);\n }\n }\n\n fetchData();\n }, []);\n\n return (\n
\n {/* 导航栏 */}\n \n\n {/* 头部区域 */}\n \n {/* 背景装饰 */}\n \n \n \n\n \n \n \n \n {t('datasetSquare.title')}\n \n \n \n {t('datasetSquare.subtitle')}\n \n\n {/* 搜索栏组件 */}\n \n \n \n \n \n \n \n\n {/* 内容区域 */}\n \n {/* 数据集网站列表组件 */}\n \n \n \n \n
\n );\n}\n"], ["/easy-dataset/app/api/projects/[projectId]/models/route.js", "import { NextResponse } from 'next/server';\nimport path from 'path';\nimport fs from 'fs/promises';\nimport { getProjectRoot } from '@/lib/db/base';\n\n// 获取模型配置\nexport async function GET(request, { params }) {\n try {\n const { projectId } = params;\n\n // 验证项目 ID\n if (!projectId) {\n return NextResponse.json({ error: 'The project ID cannot be empty' }, { status: 400 });\n }\n\n // 获取项目根目录\n const projectRoot = await getProjectRoot();\n const projectPath = path.join(projectRoot, projectId);\n\n // 检查项目是否存在\n try {\n await fs.access(projectPath);\n } catch (error) {\n return NextResponse.json({ error: 'The project does not exist' }, { status: 404 });\n }\n\n // 获取模型配置文件路径\n const modelConfigPath = path.join(projectPath, 'model-config.json');\n\n // 检查模型配置文件是否存在\n try {\n await fs.access(modelConfigPath);\n } catch (error) {\n // 如果配置文件不存在,返回默认配置\n return NextResponse.json([]);\n }\n\n // 读取模型配置文件\n const modelConfigData = await fs.readFile(modelConfigPath, 'utf-8');\n const modelConfig = JSON.parse(modelConfigData);\n\n return NextResponse.json(modelConfig);\n } catch (error) {\n console.error('Error obtaining model configuration:', String(error));\n return NextResponse.json({ error: 'Failed to obtain model configuration' }, { status: 500 });\n }\n}\n\n// 更新模型配置\nexport async function PUT(request, { params }) {\n try {\n const { projectId } = params;\n\n // 验证项目 ID\n if (!projectId) {\n return NextResponse.json({ error: 'The project ID cannot be empty' }, { status: 400 });\n }\n\n // 获取请求体\n const modelConfig = await request.json();\n\n // 验证请求体\n if (!modelConfig || !Array.isArray(modelConfig)) {\n return NextResponse.json({ error: 'The model configuration must be an array' }, { status: 400 });\n }\n\n // 获取项目根目录\n const projectRoot = await getProjectRoot();\n const projectPath = path.join(projectRoot, projectId);\n\n // 检查项目是否存在\n try {\n await fs.access(projectPath);\n } catch (error) {\n return NextResponse.json({ error: 'The project does not exist' }, { status: 404 });\n }\n\n // 获取模型配置文件路径\n const modelConfigPath = path.join(projectPath, 'model-config.json');\n\n // 写入模型配置文件\n await fs.writeFile(modelConfigPath, JSON.stringify(modelConfig, null, 2), 'utf-8');\n\n return NextResponse.json({ message: 'Model configuration updated successfully' });\n } catch (error) {\n console.error('Error updating model configuration:', String(error));\n return NextResponse.json({ error: 'Failed to update model configuration' }, { status: 500 });\n }\n}\n"], ["/easy-dataset/hooks/useSnackbar.js", "'use client';\n\nimport { useState, useCallback } from 'react';\nimport { Snackbar, Alert } from '@mui/material';\n\nexport const useSnackbar = () => {\n const [open, setOpen] = useState(false);\n const [message, setMessage] = useState('');\n const [severity, setSeverity] = useState('info');\n\n const showMessage = useCallback((newMessage, newSeverity = 'info') => {\n setMessage(newMessage);\n setSeverity(newSeverity);\n setOpen(true);\n }, []);\n\n const showSuccess = useCallback(\n message => {\n showMessage(message, 'success');\n },\n [showMessage]\n );\n\n const showError = useCallback(\n message => {\n showMessage(message, 'error');\n },\n [showMessage]\n );\n\n const showInfo = useCallback(\n message => {\n showMessage(message, 'info');\n },\n [showMessage]\n );\n\n const showWarning = useCallback(\n message => {\n showMessage(message, 'warning');\n },\n [showMessage]\n );\n\n const handleClose = useCallback(() => {\n setOpen(false);\n }, []);\n\n const SnackbarComponent = useCallback(\n () => (\n \n \n {message}\n \n \n ),\n [open, message, severity, handleClose]\n );\n\n return {\n showMessage,\n showSuccess,\n showError,\n showInfo,\n showWarning,\n SnackbarComponent\n };\n};\n"], ["/easy-dataset/app/api/projects/open-directory/route.js", "import { getProjectRoot } from '@/lib/db/base';\nimport { NextResponse } from 'next/server';\nimport path from 'path';\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\n\nconst execAsync = promisify(exec);\n\n/**\n * 打开项目目录\n * @returns {Promise} 操作结果响应\n */\nexport async function POST(request) {\n try {\n const { projectId } = await request.json();\n\n if (!projectId) {\n return NextResponse.json(\n {\n success: false,\n error: '项目ID不能为空'\n },\n { status: 400 }\n );\n }\n\n // 获取项目根目录\n const projectRoot = await getProjectRoot();\n const projectPath = path.join(projectRoot, projectId);\n\n // 根据操作系统打开目录\n const platform = process.platform;\n let command;\n\n if (platform === 'win32') {\n // Windows\n command = `explorer \"${projectPath}\"`;\n } else if (platform === 'darwin') {\n // macOS\n command = `open \"${projectPath}\"`;\n } else {\n // Linux 和其他系统\n command = `xdg-open \"${projectPath}\"`;\n }\n\n await execAsync(command);\n\n return NextResponse.json({\n success: true,\n message: '已打开项目目录'\n });\n } catch (error) {\n console.error('打开项目目录出错:', String(error));\n return NextResponse.json(\n {\n success: false,\n error: error.message\n },\n { status: 500 }\n );\n }\n}\n"], ["/easy-dataset/lib/services/models.js", "import { getModelConfigById } from '@/lib/db/model-config';\nimport { getProject } from '@/lib/db/projects';\nimport logger from '@/lib/util/logger';\n\n/**\n * Get the active model configuration for a project\n * @param {string} projectId - Optional project ID to get the default model for\n * @returns {Promise} - Active model configuration or null\n */\nexport async function getActiveModel(projectId = null) {\n try {\n // If projectId is provided, get the default model for that project\n if (projectId) {\n const project = await getProject(projectId);\n if (project && project.defaultModelConfigId) {\n const modelConfig = await getModelConfigById(project.defaultModelConfigId);\n if (modelConfig) {\n logger.info(`Using default model for project ${projectId}: ${modelConfig.modelName}`);\n return modelConfig;\n }\n }\n }\n\n // If no specific project model found, try to get from localStorage context\n // This is a fallback for when the function is called without context\n logger.warn('No active model found');\n return null;\n } catch (error) {\n logger.error('Failed to get active model:', error);\n return null;\n }\n}\n\n/**\n * Get active model by ID\n * @param {string} modelConfigId - Model configuration ID\n * @returns {Promise} - Model configuration or null\n */\nexport async function getModelById(modelConfigId) {\n try {\n if (!modelConfigId) {\n logger.warn('No model ID provided');\n return null;\n }\n\n const modelConfig = await getModelConfigById(modelConfigId);\n if (modelConfig) {\n logger.info(`Retrieved model: ${modelConfig.modelName}`);\n return modelConfig;\n }\n\n logger.warn(`Model not found with ID: ${modelConfigId}`);\n return null;\n } catch (error) {\n logger.error('Failed to get model by ID:', error);\n return null;\n }\n}\n"], ["/easy-dataset/lib/llm/prompts/newAnswerEn.js", "module.exports = function getNewAnswerPrompt(question, answer, cot, advice) {\n return `\n# Role: Fine-tuning Dataset Answer Optimization Expert\n## Profile:\n- Description: You are an expert in optimizing answers for fine-tuning datasets. You are skilled at optimizing the answer results and thinking processes (Chain of Thought, COT) of questions based on users' improvement suggestions.\n\n## Skills:\n1. Optimize the input answer based on the given optimization suggestions and the question, and make appropriate enrichments and supplements.\n3. Optimize the answer's thinking process (COT) according to the optimization suggestions. Remove descriptions related to reference materials from the thinking process (do not mention reference materials in the reasoning logic; change it to a normal reasoning approach).\n\n## Original Question\n${question}\n\n## Answer to be Optimized\n${answer}\n\n## Answer Optimization Suggestions\n${advice}. Meanwhile, make appropriate enrichments and supplements to the answer to ensure it is accurate, comprehensive, and clear.\n\n## Thinking Process to be Optimized\n${cot}\n\n## Thinking Process Optimization Suggestions\n- General Optimization Suggestions: ${advice}\n- Remove descriptions related to reference materials from the thinking process (e.g., \"According to...\", \"Quoting...\", \"Referencing...\", etc.). Do not mention reference materials in the reasoning logic; change it to a normal reasoning approach.\n\n## Constraints:\n1. The result must be output in JSON format (if the thinking process to be optimized is empty, the COT field in the output should also be empty):\n \\`\\`\\`json\n {\n \"answer\": \"Optimized answer\",\n \"cot\": \"Optimized thinking process\"\n }\n \\`\\`\\`\n `;\n};\n"], ["/easy-dataset/lib/llm/prompts/ga-generationEn.js", "/**\n * Genre-Audience pair generation prompt\n * Based on MGA (Massive Genre-Audience) method for data augmentation\n */\n\nexport const GA_GENERATION_PROMPT_EN = `#Identity and Capabilities#\nYou are a content creation expert, skilled in text analysis and designing diverse questioning methods and interactive scenarios based on different knowledge backgrounds and learning objectives, to produce diverse and high-quality text. Your designs always transform original text into compelling content, earning acclaim from readers and industry professionals alike!\n\n#Workflow#\nPlease use your imagination and creativity to generate 5 pairs of [Genre] and [Audience] combinations for the original text. Your analysis should follow these requirements:\n1. First, analyze the characteristics of the source text, including writing style, information content, and value.\n2. Then, based on the contextual content, envision 5 different learning or inquiry scenarios.\n3. Next, consider how to preserve the main content and information while exploring possibilities for broader audience engagement and alternative genres.\n3. Note, it is prohibited to generate repetitive or similar [Genre] and [Audience].\n4. Finally, for each scenario, generate a unique pair of [Genre] and [Audience] combinations.\n\n\n#Detailed Requirements#\nEnsure adherence to the workflow requirements above, then generate 5 pairs of [Genre] and [Audience] combinations according to the following specifications (please remember you must strictly follow the formatting requirements provided in the #Response# section):\nYour provided [Genre] should meet the following requirements:\n1. Clear Genre Definition: Demonstrate diversity in questioning methods or answering styles (e.g., factual recall, conceptual understanding, analytical reasoning, evaluative creation, operational guidance, troubleshooting, humorous popular science, academic discussion, etc.). Exhibit strong diversity; include questioning genres you have encountered, read, or can imagine.\n2. Detailed Genre Description: Provide 2-3 sentences describing each genre, considering but not limited to type, style, emotional tone, form, conflict, rhythm, and atmosphere. Emphasize diversity to guide knowledge adaptation for specific audiences, facilitating comprehension across different backgrounds. Note: Exclude visual formats (picture books, comics, videos); use text-only genres.\n## Example:\nGenre: \"Root Cause Analysis Type\"\nDescription: This type of question aims to explore the fundamental causes or mechanisms behind phenomena. Usually starting with \"Why...\" or \"What is the principle of...?\", it encourages deep thinking and explanation. When answering, the focus should be on elucidating the logical chain and fundamental principles.\n\nYour provided [Audience] should meet the following requirements:\n1. Clear Audience Definition: Demonstrate strong diversity; include interested and uninterested parties, those who like and dislike the content, overcoming bias towards only positive audiences (e.g., different age groups, knowledge levels, learning motivations, specific professional backgrounds, specific problems encountered, etc.).\n2. Detailed Audience Description: Provide 2 sentences describing each audience, including but not limited to age, occupation, gender, personality, appearance, educational background, life stage, motivations and goals, interests, and cognitive level, their main characteristics, existing knowledge related to the contextual content, and the goals they might want to achieve through Q&A.\n## Example:\nAudience: \"Aspiring Engineers Curious About Technical Details\"\nDescription: This is a group of university students with a certain foundation in science and engineering, but who are not yet familiar with the details of specific technical fields. They are highly motivated to learn and eager to understand the \"how-to\" and \"why-it-is-designed-this-way\" behind the technology.\n\n#IMPORTANT: You must respond with ONLY a valid JSON array in this exact format:#\n\n[\n {\n \"genre\": {\n \"title\": \"Genre Title\",\n \"description\": \"Detailed genre description\"\n },\n \"audience\": {\n \"title\": \"Audience Title\", \n \"description\": \"Detailed audience description\"\n }\n },\n {\n \"genre\": {\n \"title\": \"Genre Title\",\n \"description\": \"Detailed genre description\"\n },\n \"audience\": {\n \"title\": \"Audience Title\",\n \"description\": \"Detailed audience description\"\n }\n }\n // ... 3 more pairs (total 5)\n]\n\n**Do not include any explanatory text, markdown formatting, or additional content. Return only the JSON array.**\n\n#Source Text to Analyze#\n{text_content}`;\n"], ["/easy-dataset/app/api/projects/[projectId]/route.js", "// 获取项目详情\nimport { deleteProject, getProject, updateProject, getTaskConfig } from '@/lib/db/projects';\n\nexport async function GET(request, { params }) {\n try {\n const { projectId } = params;\n const project = await getProject(projectId);\n const taskConfig = await getTaskConfig(projectId);\n if (!project) {\n return Response.json({ error: '项目不存在' }, { status: 404 });\n }\n return Response.json({ ...project, taskConfig });\n } catch (error) {\n console.error('获取项目详情出错:', String(error));\n return Response.json({ error: String(error) }, { status: 500 });\n }\n}\n\n// 更新项目\nexport async function PUT(request, { params }) {\n try {\n const { projectId } = params;\n const projectData = await request.json();\n\n // 验证必要的字段\n if (!projectData.name && !projectData.defaultModelConfigId) {\n return Response.json({ error: '项目名称不能为空' }, { status: 400 });\n }\n\n const updatedProject = await updateProject(projectId, projectData);\n\n if (!updatedProject) {\n return Response.json({ error: '项目不存在' }, { status: 404 });\n }\n\n return Response.json(updatedProject);\n } catch (error) {\n console.error('更新项目出错:', String(error));\n return Response.json({ error: String(error) }, { status: 500 });\n }\n}\n\n// 删除项目\nexport async function DELETE(request, { params }) {\n try {\n const { projectId } = params;\n const success = await deleteProject(projectId);\n\n if (!success) {\n return Response.json({ error: '项目不存在' }, { status: 404 });\n }\n\n return Response.json({ success: true });\n } catch (error) {\n console.error('删除项目出错:', error);\n return Response.json({ error: error.message }, { status: 500 });\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/api/projects/unmigrated/route.js", "import { getProjectRoot } from '@/lib/db/base';\nimport { db } from '@/lib/db/index';\nimport fs from 'fs';\nimport path from 'path';\nimport { NextResponse } from 'next/server';\n\n/**\n * 获取未迁移的项目列表\n * @returns {Promise} 包含未迁移项目列表的响应\n */\nexport async function GET(request) {\n // 获取当前请求的 URL,从中提取查询参数\n const { searchParams } = new URL(request.url);\n // 这行代码是关键,强制每次请求都是不同的\n const timestamp = searchParams.get('_t') || Date.now();\n try {\n // 获取项目根目录\n const projectRoot = await getProjectRoot();\n\n // 读取根目录下的所有文件夹(每个文件夹代表一个项目)\n const files = await fs.promises.readdir(projectRoot, { withFileTypes: true });\n\n // 过滤出目录类型的条目\n const projectDirs = files.filter(file => file.isDirectory());\n\n // 如果没有项目目录,则直接返回空列表\n if (projectDirs.length === 0) {\n return NextResponse.json({\n success: true,\n data: []\n });\n }\n\n // 获取所有项目ID\n const projectIds = projectDirs.map(dir => dir.name);\n\n // 批量查询已迁移的项目\n const existingProjects = await db.projects.findMany({\n where: {\n id: {\n in: projectIds\n }\n },\n select: {\n id: true\n }\n });\n\n // 转换为集合以便快速查找\n const existingProjectIds = new Set(existingProjects.map(p => p.id));\n\n // 筛选出未迁移的项目\n const unmigratedProjectDirs = projectDirs.filter(dir => !existingProjectIds.has(dir.name));\n\n // 获取未迁移项目的ID列表\n const unmigratedProjects = unmigratedProjectDirs.map(dir => dir.name);\n\n return NextResponse.json({\n success: true,\n data: unmigratedProjects,\n projectRoot,\n number: Date.now(),\n timestamp\n });\n } catch (error) {\n console.error('获取未迁移项目列表出错:', String(error));\n return NextResponse.json(\n {\n success: false,\n error: error.message\n },\n { status: 500 }\n );\n }\n}\n"], ["/easy-dataset/components/text-split/components/FileLoadingProgress.js", "'use client';\n\nimport { Box, Typography, keyframes, Paper } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\nimport { handleLongFileName } from '@/lib/file/file-process';\nimport { useState, useEffect } from 'react';\n\n// 定义动画效果\nconst pulse = keyframes`\n 0% {\n box-shadow: 0 0 0 0 rgba(32, 76, 255, 0.2);\n }\n 70% {\n box-shadow: 0 0 0 15px rgba(32, 76, 255, 0);\n }\n 100% {\n box-shadow: 0 0 0 0 rgba(32, 76, 255, 0);\n }\n`;\n\nconst rotateAnimation = keyframes`\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n`;\n\nconst shimmer = keyframes`\n 0% { background-position: -200% 0; }\n 100% { background-position: 200% 0; }\n`;\n\n/**\n * 文件处理进度展示组件 - 美化版\n *\n * @param {Object} props\n * @param {Object} props.fileTask - 文件处理任务信息\n */\nexport default function FileLoadingProgress({ fileTask }) {\n const { t } = useTranslation();\n const [animationStep, setAnimationStep] = useState(0);\n\n // 创建动态效果\n useEffect(() => {\n const interval = setInterval(() => {\n setAnimationStep(prev => (prev + 1) % 4);\n }, 600);\n return () => clearInterval(interval);\n }, []);\n\n if (!fileTask) {\n return null;\n }\n\n const pageProgress = (fileTask.current.processedPage / fileTask.current.totalPage) * 100;\n const filesProgress = (fileTask.processedFiles / fileTask.totalFiles) * 100;\n\n // 生成进度指示器文本\n const getProgressIndicator = () => {\n const dots = '.';\n return dots.repeat(animationStep + 1);\n };\n\n return (\n \n {/* 背景动画元素 */}\n \n\n {/* 主标题 */}\n \n {t('textSplit.pdfProcessingLoading')}\n {getProgressIndicator()}\n \n\n {/* 处理进度显示区域 */}\n \n {/* 当前文件进度 */}\n \n\n {/* 总文件进度 */}\n \n \n \n );\n}\n\n/**\n * 进度条区域组件\n */\nfunction ProgressSection({ label, progress, color, mt = 0 }) {\n return (\n \n \n \n {label}\n \n \n {Math.round(progress)}%\n \n \n\n {/* 自定义进度条 */}\n \n \n \n \n );\n}\n"], ["/easy-dataset/lib/llm/prompts/question.js", "/**\n * 构建 GA 提示词\n * @param {Object} activeGaPair 当前激活的 GA 组合\n * @returns {String} 构建的 GA 提示词\n */\nfunction buildGaPrompt(activeGaPair = null) {\n if (activeGaPair && activeGaPair.active) {\n return `\n## 特殊要求-体裁与受众视角提问:\n请根据以下体裁与受众组合,调整你的提问角度和问题风格:\n\n**目标体裁**: ${activeGaPair.genre}\n**目标受众**: ${activeGaPair.audience}\n\n请确保:\n1. 问题应完全符合「${activeGaPair.genre}」所定义的风格、焦点和深度等等属性。\n2. 问题应考虑到「${activeGaPair.audience}」的知识水平、认知特点和潜在兴趣点。\n3. 从该受众群体的视角和需求出发提出问题\n4. 保持问题的针对性和实用性,确保问题-答案的风格一致性\n5.问题应具有一定的清晰度和具体性,避免过于宽泛或模糊。\n`;\n }\n\n return '';\n}\n\n/**\n * 问题生成提示模板。\n * @param {string} text - 待处理的文本。\n * @param {number} number - 问题数量。\n * @param {string} language - 问题所使用的语言。\n * @param {string} globalPrompt - LLM 的全局提示。\n * @param {string} questionPrompt - 问题生成的特定提示。\n * @param {Object} activeGaPair - 当前激活的 GA对。\n * @returns {string} - 完整的提示词。\n */\nmodule.exports = function getQuestionPrompt({\n text,\n number = Math.floor(text.length / 240),\n language = '中文',\n globalPrompt = '',\n questionPrompt = '',\n activeGaPair = null\n}) {\n if (globalPrompt) {\n globalPrompt = `在后续的任务中,你务必遵循这样的规则:${globalPrompt}`;\n }\n if (questionPrompt) {\n questionPrompt = `- 在生成问题时,你务必遵循这样的规则:${questionPrompt}`;\n }\n\n // 构建GA pairs相关的提示词\n const gaPrompt = buildGaPrompt(activeGaPair);\n\n return `\n # 角色使命\n 你是一位专业的文本分析专家,擅长从复杂文本中提取关键信息并生成可用于模型微调的结构化数据(仅生成问题)。\n ${globalPrompt}\n\n ## 核心任务\n 根据用户提供的文本(长度:${text.length} 字),生成不少于 ${number} 个高质量问题。\n\n ## 约束条件(重要!!!)\n - 必须基于文本内容直接生成\n - 问题应具有明确答案指向性\n - 需覆盖文本的不同方面\n - 禁止生成假设性、重复或相似问题\n\n ${gaPrompt}\n\n ## 处理流程\n 1. 【文本解析】分段处理内容,识别关键实体和核心概念\n 2. 【问题生成】基于信息密度选择最佳提问点${gaPrompt ? ',并结合指定的体裁受众视角' : ''}\n 3. 【质量检查】确保:\n - 问题答案可在原文中找到依据\n - 标签与问题内容强相关\n - 无格式错误\n ${gaPrompt ? '- 问题风格与指定的体裁受众匹配' : ''}\n \n ## 输出格式\n - JSON 数组格式必须正确\n - 字段名使用英文双引号\n - 输出的 JSON 数组必须严格符合以下结构:\n \\`\\`\\`json\n [\"问题1\", \"问题2\", \"...\"]\n \\`\\`\\`\n\n ## 输出示例\n \\`\\`\\`json\n [ \"人工智能伦理框架应包含哪些核心要素?\",\"民法典对个人数据保护有哪些新规定?\"]\n \\`\\`\\`\n\n ## 待处理文本\n ${text}\n\n ## 限制\n - 必须按照规定的 JSON 格式输出,不要输出任何其他不相关内容\n - 生成不少于${number}个高质量问题\n - 问题不要和材料本身相关,例如禁止出现作者、章节、目录等相关问题\n - 问题不得包含【报告、文章、文献、表格】中提到的这种话术,必须是一个自然的问题\n ${questionPrompt}\n `;\n};\n"], ["/easy-dataset/components/tasks/TaskStatusChip.js", "'use client';\n\nimport React from 'react';\nimport { Chip, CircularProgress, Box } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\n\n// 任务状态显示组件\nexport default function TaskStatusChip({ status }) {\n const { t } = useTranslation();\n\n // 状态映射配置\n const STATUS_CONFIG = {\n 0: {\n label: t('tasks.status.processing'),\n color: 'warning',\n loading: true\n },\n 1: {\n label: t('tasks.status.completed'),\n color: 'success'\n },\n 2: {\n label: t('tasks.status.failed'),\n color: 'error'\n },\n 3: {\n label: t('tasks.status.aborted'),\n color: 'default'\n }\n };\n\n const statusInfo = STATUS_CONFIG[status] || {\n label: t('tasks.status.unknown'),\n color: 'default'\n };\n\n // 处理中状态显示加载动画\n if (status === 0) {\n return (\n \n \n \n \n );\n }\n\n return ;\n}\n"], ["/easy-dataset/app/api/projects/[projectId]/chunks/route.js", "import { NextResponse } from 'next/server';\nimport { deleteChunkById, getChunkByFileIds, getChunkById, getChunksByFileIds, updateChunkById } from '@/lib/db/chunks';\n\n// 获取文本块内容\nexport async function POST(request, { params }) {\n try {\n const { projectId } = params;\n // 验证参数\n if (!projectId) {\n return NextResponse.json({ error: 'Project ID cannot be empty' }, { status: 400 });\n }\n const { array } = await request.json();\n // 获取文本块内容\n const chunk = await getChunksByFileIds(array);\n\n return NextResponse.json(chunk);\n } catch (error) {\n console.error('Failed to get text block content:', String(error));\n return NextResponse.json({ error: String(error) || 'Failed to get text block content' }, { status: 500 });\n }\n}\n"], ["/easy-dataset/lib/llm/prompts/labelReviseEn.js", "/**\n * Incremental domain tree revision prompt template (English version)\n * Used to incrementally adjust the domain tree based on added/deleted literature content\n */\nfunction getLabelReviseEnPrompt({ text, existingTags, deletedContent, newContent, globalPrompt, domainTreePrompt }) {\n const prompt = `${globalPrompt ? globalPrompt : ''}\n\nI need your help to revise an existing domain tree structure to adapt to content changes.\n${domainTreePrompt ? domainTreePrompt : ''}\n\n【Existing Domain Tree Structure】\nHere is the current domain tree structure (JSON format):\n\\`\\`\\`json\n${JSON.stringify(existingTags, null, 2)}\n\\`\\`\\`\n\n${\n deletedContent\n ? `【Deleted Content】\nHere are the table of contents from the deleted literature:\n\\`\\`\\`\n${deletedContent}\n\\`\\`\\`\n`\n : ''\n}\n\n${\n newContent\n ? `【New Content】\nHere are the table of contents from the newly added literature:\n\\`\\`\\`\n${newContent}\n\\`\\`\\`\n`\n : ''\n}\n\n【All Existing Literature TOC】\nBelow is an overview of the table of contents from all current literature in the system:\n\\`\\`\\`\n${text}\n\\`\\`\\`\n\nPlease analyze the above information and revise the existing domain tree structure according to the following principles:\n1. Maintain the overall structure of the domain tree, avoiding large-scale reconstruction\n2. For domain tags related to deleted content:\n - If a tag is only related to the deleted content and no supporting content can be found in the existing literature, remove the tag\n - If a tag is also related to other retained content, keep the tag\n3. For newly added content:\n - If new content can be classified into existing tags, prioritize using existing tags\n - If new content introduces new domains or concepts not present in the existing tag system, create new tags\n4. Each tag must correspond to actual content in the table of contents, do not create empty tags without corresponding content support\n5. Ensure that the revised domain tree still has a good hierarchical structure with reasonable parent-child relationships between tags\n\n## Constraints\n1. The number of primary domain labels should be between 5 and 10.\n2. The number of secondary domain labels ≤ 5 per primary label.\n3. There should be at most two classification levels.\n4. The classification must be relevant to the original catalog content.\n5. The output must conform to the specified JSON format.\n6. The names of the labels should not exceed 6 characters.\n7. Do not output any content other than the JSON.\n8. Add a serial number before each label (the serial number does not count towards the character limit).\n\nOutput the complete revised domain tree structure using the JSON format below:\n\n\\`\\`\\`json\n[\n {\n \"label\": \"1 Primary Domain Label\",\n \"child\": [\n {\"label\": \"1.1 Secondary Domain Label 1\"},\n {\"label\": \"1.2 Secondary Domain Label 2\"}\n ]\n },\n {\n \"label\": \"2 Primary Domain Label (No Sub - labels)\"\n }\n]\n\\`\\`\\`\n\nEnsure that your answer only contains the domain tree in JSON format without any explanatory text.`;\n\n return prompt;\n}\n\nmodule.exports = getLabelReviseEnPrompt;\n"], ["/easy-dataset/lib/file/file-process/pdf/default.js", "import pdf2md from '@opendocsg/pdf2md';\nimport { getProjectRoot } from '@/lib/db/base';\nimport fs from 'fs';\nimport path from 'path';\n\nexport async function defaultProcessing(projectId, fileName) {\n console.log('executing default pdf conversion strategy......');\n\n // 获取项目根目录\n const projectRoot = await getProjectRoot();\n const projectPath = path.join(projectRoot, projectId);\n\n // 获取文件路径\n const filePath = path.join(projectPath, 'files', fileName);\n\n // 读取文件\n const pdfBuffer = fs.readFileSync(filePath);\n\n // 转换后文件名\n const convertName = fileName.replace(/\\.([^.]*)$/, '') + '.md';\n\n try {\n const text = await pdf2md(pdfBuffer);\n const outputFile = path.join(projectPath, 'files', convertName);\n console.log(`Writing to ${outputFile}...`);\n fs.writeFileSync(path.resolve(outputFile), text);\n console.log('pdf conversion completed!');\n\n // 返回转换后的文件名\n return { success: true, fileName: convertName };\n } catch (err) {\n console.error('pdf conversion failed:', err);\n throw err;\n }\n}\n\nexport default {\n defaultProcessing\n};\n"], ["/easy-dataset/electron/util.js", "const path = require('path');\nconst fs = require('fs');\n\n// 获取应用版本\nconst getAppVersion = () => {\n try {\n const packageJsonPath = path.join(__dirname, '../package.json');\n if (fs.existsSync(packageJsonPath)) {\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));\n return packageJson.version;\n }\n return '1.0.0';\n } catch (error) {\n console.error('读取版本信息失败:', error);\n return '1.0.0';\n }\n};\n\nmodule.exports = { getAppVersion };\n"], ["/easy-dataset/components/common/MessageAlert.js", "'use client';\n\nimport { Snackbar, Alert } from '@mui/material';\n\nexport default function MessageAlert({ message, onClose }) {\n if (!message) return null;\n\n const severity = message.severity || 'error';\n const text = typeof message === 'string' ? message : message.message;\n\n return (\n \n \n {text}\n \n \n );\n}\n"], ["/easy-dataset/components/dataset-square/DatasetSiteCard.js", "'use client';\n\nimport { Card, CardActionArea, CardContent, CardMedia, Typography, Box, Chip, useTheme, alpha } from '@mui/material';\nimport LaunchIcon from '@mui/icons-material/Launch';\nimport StorageIcon from '@mui/icons-material/Storage';\nimport { useTranslation } from 'react-i18next';\n\nexport function DatasetSiteCard({ site }) {\n const { name, link, description, image, labels } = site;\n const theme = useTheme();\n\n // 处理图片路径,如果没有图片则使用默认图片\n const imageUrl = image || `/imgs/default-dataset.png`;\n const { t } = useTranslation();\n\n // 处理卡片点击\n const handleCardClick = () => {\n window.open(link, '_blank');\n };\n\n return (\n \n \n {/* 网站截图 */}\n \n \n \n }\n label={t('datasetSquare.dataset')}\n size=\"small\"\n sx={{\n position: 'absolute',\n top: 10,\n right: 10,\n zIndex: 2,\n backgroundColor: alpha(theme.palette.background.paper, 0.8),\n backdropFilter: 'blur(4px)',\n border: `1px solid ${alpha(theme.palette.primary.main, 0.2)}`,\n '& .MuiChip-icon': {\n color: theme.palette.primary.main\n }\n }}\n />\n \n\n {/* 网站信息 */}\n \n \n \n {name}\n \n \n \n\n \n {description}\n \n\n \n {/* 标签显示 */}\n {labels && labels.length > 0 && (\n \n {labels.map((label, index) => (\n \n ))}\n \n )}\n\n \n \n \n \n \n \n \n );\n}\n"], ["/easy-dataset/lib/llm/prompts/labelRevise.js", "/**\n * 领域树增量修订提示词\n * 用于在已有领域树的基础上,针对新增/删除的文献内容,对领域树进行增量调整\n */\nfunction getLabelRevisePrompt({ text, existingTags, deletedContent, newContent, globalPrompt, domainTreePrompt }) {\n const prompt = `\n \n${globalPrompt ? `- 在后续的任务中,你务必遵循这样的规则:${globalPrompt}` : ''}\n\n我需要你帮我修订一个已有的领域树结构,使其能够适应内容的变化。\n${domainTreePrompt ? domainTreePrompt : ''}\n\n## 之前的领域树结构\n以下是之前完整的领域树结构(JSON格式):\n\\`\\`\\`json\n${JSON.stringify(existingTags, null, 2)}\n\\`\\`\\`\n\n\n## 之前完整文献的目录\n以下是当前系统中所有文献的目录结构总览:\n\\`\\`\\`\n${text}\n\\`\\`\\`\n\n${\n deletedContent\n ? `## 被删除的内容\n以下是本次要删除的文献目录信息:\n\\`\\`\\`\n${deletedContent}\n\\`\\`\\`\n`\n : ''\n}\n\n${\n newContent\n ? `## 新增的内容\n以下是本次新增的文献目录信息:\n\\`\\`\\`\n${newContent}\n\\`\\`\\`\n`\n : ''\n}\n\n## 要求\n请分析上述信息,修订现有的领域树结构,遵循以下原则:\n1. 保持领域树的总体结构稳定,避免大规模重构\n2. 对于删除的内容相关的领域标签:\n - 如果某个标签仅与删除的内容相关,且在现有文献中找不到相应内容支持,则移除该标签\n - 如果某个标签同时与其他保留的内容相关,则保留该标签\n3. 对于新增的内容:\n - 如果新内容可以归类到现有的标签中,优先使用现有标签\n - 如果新内容引入了现有标签体系中没有的新领域或概念,再创建新的标签\n4. 每个标签必须对应目录结构中的实际内容,不要创建没有对应内容支持的空标签\n5. 确保修订后的领域树仍然符合良好的层次结构,标签间具有合理的父子关系\n\n## 限制\n1. 一级领域标签数量5-10个\n2. 二级领域标签数量1-10个\n3. 最多两层分类层级\n4. 分类必须与原始目录内容相关\n5. 输出必须符合指定 JSON 格式,不要输出 JSON 外其他任何不相关内容\n6. 标签的名字最多不要超过 6 个字\n7. 在每个标签前加入序号(序号不计入字数)\n\n## 输出格式\n最终输出修订后的完整领域树结构,使用下面的JSON格式:\n\n\\`\\`\\`json\n[\n {\n \"label\": \"1 一级领域标签\",\n \"child\": [\n {\"label\": \"1.1 二级领域标签1\"},\n {\"label\": \"1.2 二级领域标签2\"}\n ]\n },\n {\n \"label\": \"2 一级领域标签(无子标签)\"\n }\n]\n\\`\\`\\`\n\n确保你的回答中只包含JSON格式的领域树,不要有其他解释性文字。`;\n\n return prompt;\n}\n\nmodule.exports = getLabelRevisePrompt;\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/api/projects/delete-directory/route.js", "import { getProjectRoot } from '@/lib/db/base';\nimport { NextResponse } from 'next/server';\nimport path from 'path';\nimport fs from 'fs';\nimport { promisify } from 'util';\n\nconst rmdir = promisify(fs.rm);\n\n/**\n * 删除项目目录\n * @returns {Promise} 操作结果响应\n */\nexport async function POST(request) {\n try {\n const { projectId } = await request.json();\n\n if (!projectId) {\n return NextResponse.json(\n {\n success: false,\n error: '项目ID不能为空'\n },\n { status: 400 }\n );\n }\n\n // 获取项目根目录\n const projectRoot = await getProjectRoot();\n const projectPath = path.join(projectRoot, projectId);\n\n // 检查目录是否存在\n if (!fs.existsSync(projectPath)) {\n return NextResponse.json(\n {\n success: false,\n error: '项目目录不存在'\n },\n { status: 404 }\n );\n }\n\n // 递归删除目录\n await rmdir(projectPath, { recursive: true, force: true });\n\n return NextResponse.json({\n success: true,\n message: '项目目录已删除'\n });\n } catch (error) {\n console.error('删除项目目录出错:', String(error));\n return NextResponse.json(\n {\n success: false,\n error: error.message\n },\n { status: 500 }\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/lib/llm/prompts/labelEn.js", "module.exports = function getLabelPrompt({ text, globalPrompt, domainTreePrompt }) {\n if (globalPrompt) {\n globalPrompt = `- In subsequent tasks, you must follow this rule: ${globalPrompt}`;\n }\n if (domainTreePrompt) {\n domainTreePrompt = `- In generating labels, you must follow this rule: ${domainTreePrompt}`;\n }\n return `\n# Role: Domain Classification Expert & Knowledge Graph Expert\n- Description: As a senior domain classification expert and knowledge graph expert, you are skilled at extracting core themes from text content, constructing classification systems, and performing knowledge categorization and labeling.\n${globalPrompt}\n\n## Skills:\n1. Proficient in text theme analysis and keyword extraction.\n2. Good at constructing hierarchical knowledge systems.\n3. Skilled in domain classification methodologies.\n4. Capable of building knowledge graphs.\n5. Proficient in JSON data structures.\n\n## Goals:\n1. Analyze the content of the book catalog.\n2. Identify core themes and key domains.\n3. Construct a two - level classification system.\n4. Ensure the classification logic is reasonable.\n5. Generate a standardized JSON output.\n\n## Workflow:\n1. Carefully read the entire content of the book catalog.\n2. Extract key themes and core concepts.\n3. Group and categorize the themes.\n4. Construct primary domain labels (ensure no more than 10).\n5. Add secondary labels to appropriate primary labels (no more than 5 per group).\n6. Check the rationality of the classification logic.\n7. Generate a JSON output that conforms to the format.\n\n## Catalog to be analyzed\n ${text}\n\n## Constraints\n1. The number of primary domain labels should be between 5 and 10.\n2. The number of secondary domain labels ≤ 5 per primary label.\n3. There should be at most two classification levels.\n4. The classification must be relevant to the original catalog content.\n5. The output must conform to the specified JSON format.\n6. The names of the labels should not exceed 6 characters.\n7. Do not output any content other than the JSON.\n8. Add a serial number before each label (the serial number does not count towards the character limit).\n9. Use English\n${domainTreePrompt}\n\n\n## OutputFormat:\n\\`\\`\\`json\n[\n {\n \"label\": \"1 Primary Domain Label\",\n \"child\": [\n {\"label\": \"1.1 Secondary Domain Label 1\"},\n {\"label\": \"1.2 Secondary Domain Label 2\"}\n ]\n },\n {\n \"label\": \"2 Primary Domain Label (No Sub - labels)\"\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/app/api/update/route.js", "import { NextResponse } from 'next/server';\nimport { exec } from 'child_process';\nimport path from 'path';\nimport fs from 'fs';\n\n// 执行更新脚本\nexport async function POST() {\n try {\n // 检查是否在客户端环境中运行\n const desktopDir = path.join(process.cwd(), 'desktop');\n const updaterPath = path.join(desktopDir, 'scripts', 'updater.js');\n\n if (!fs.existsSync(updaterPath)) {\n return NextResponse.json(\n {\n success: false,\n message: '更新功能仅在客户端环境中可用'\n },\n { status: 400 }\n );\n }\n\n // 执行更新脚本\n return new Promise(resolve => {\n const updaterProcess = exec(`node \"${updaterPath}\"`, { cwd: process.cwd() });\n\n let output = '';\n\n updaterProcess.stdout.on('data', data => {\n output += data.toString();\n console.log(`Update output: ${data}`);\n });\n\n updaterProcess.stderr.on('data', data => {\n output += data.toString();\n console.error(`Update error: ${data}`);\n });\n\n updaterProcess.on('close', code => {\n console.log(`Update process exit, exit code: ${code}`);\n\n if (code === 0) {\n resolve(\n NextResponse.json({\n success: true,\n message: 'Update successful, application will restart'\n })\n );\n } else {\n resolve(\n NextResponse.json(\n {\n success: false,\n message: `Update failed, exit code: ${code}, output: ${output}`\n },\n { status: 500 }\n )\n );\n }\n });\n });\n } catch (error) {\n console.error('Failed to execute update:', String(error));\n return NextResponse.json(\n {\n success: false,\n message: `Failed to execute update: ${error.message}`\n },\n { status: 500 }\n );\n }\n}\n"], ["/easy-dataset/lib/file/file-process/check-file.js", "import { FILE } from '@/constant';\n\n/**\n * 检查文件大小\n */\nexport function checkMaxSize(files) {\n const oversizedFiles = files.filter(file => file.size > FILE.MAX_FILE_SIZE);\n if (oversizedFiles.length > 0) {\n throw new Error(`Max 50MB: ${oversizedFiles.map(f => f.name).join(', ')}`);\n }\n}\n\n/**\n * 获取可以上传的文件\n * @param {*} files\n * @returns\n */\nexport function getvalidFiles(files) {\n return files.filter(\n file =>\n file.name.endsWith('.md') ||\n file.name.endsWith('.txt') ||\n file.name.endsWith('.docx') ||\n file.name.endsWith('.pdf')\n );\n}\n\n/**\n * 检查不能上传的文件\n * @param {*} files\n * @returns\n */\nexport function checkInvalidFiles(files) {\n const invalidFiles = files.filter(\n file =>\n !file.name.endsWith('.md') &&\n !file.name.endsWith('.txt') &&\n !file.name.endsWith('.docx') &&\n !file.name.endsWith('.pdf')\n );\n if (invalidFiles.length > 0) {\n throw new Error(`Unsupported File Format: ${invalidFiles.map(f => f.name).join(', ')}`);\n }\n return invalidFiles;\n}\n"], ["/easy-dataset/app/api/projects/[projectId]/distill/tags/all/route.js", "import { NextResponse } from 'next/server';\nimport { db } from '@/lib/db';\n\n/**\n * 获取项目的所有蒸馏标签\n */\nexport async function GET(request, { params }) {\n try {\n const { projectId } = params;\n\n // 验证项目ID\n if (!projectId) {\n return NextResponse.json({ error: '项目ID不能为空' }, { status: 400 });\n }\n\n // 获取所有标签\n const tags = await db.tags.findMany({\n where: {\n projectId\n },\n orderBy: {\n label: 'asc'\n }\n });\n\n return NextResponse.json(tags);\n } catch (error) {\n console.error('获取蒸馏标签失败:', String(error));\n return NextResponse.json({ error: error.message || '获取蒸馏标签失败' }, { status: 500 });\n }\n}\n"], ["/easy-dataset/components/home/HeroSection.js", "'use client';\n\nimport { Box, Container, Typography, Button, useMediaQuery } from '@mui/material';\nimport AddCircleOutlineIcon from '@mui/icons-material/AddCircleOutline';\nimport SearchIcon from '@mui/icons-material/Search';\nimport { styles } from '@/styles/home';\nimport { useTheme } from '@mui/material';\nimport { motion } from 'framer-motion';\nimport ParticleBackground from './ParticleBackground';\nimport { useTranslation } from 'react-i18next';\n\nexport default function HeroSection({ onCreateProject }) {\n const { t } = useTranslation();\n const theme = useTheme();\n const isMobile = useMediaQuery(theme.breakpoints.down('sm'));\n\n return (\n \n {/* 添加粒子背景 */}\n \n\n \n \n\n \n \n \n {t('home.title')}\n \n\n \n {t('home.subtitle')}\n \n\n \n }\n sx={{\n ...styles.createButton(theme),\n fontWeight: 600,\n transition: 'all 0.3s ease',\n transform: 'translateY(0)',\n px: 4,\n py: 1.5,\n borderRadius: '12px',\n '&:hover': {\n transform: 'translateY(-3px)',\n boxShadow: '0 10px 25px rgba(0, 0, 0, 0.2)'\n }\n }}\n >\n {t('home.createProject')}\n \n {\n window.location.href = '/dataset-square';\n }}\n startIcon={}\n sx={{\n ...styles.createButton(theme),\n fontWeight: 600,\n transition: 'all 0.3s ease',\n transform: 'translateY(0)',\n px: 4,\n py: 1.5,\n borderRadius: '12px',\n '&:hover': {\n transform: 'translateY(-3px)',\n boxShadow: '0 10px 25px rgba(0, 0, 0, 0.2)'\n }\n }}\n >\n {t('home.searchDataset')}\n \n \n \n \n \n );\n}\n"], ["/easy-dataset/app/api/projects/[projectId]/chunks/name/route.js", "import { NextResponse } from 'next/server';\nimport { getChunkByName } from '@/lib/db/chunks';\n\n/**\n * 根据文本块名称获取文本块\n * @param {Request} request 请求对象\n * @param {object} context 上下文,包含路径参数\n * @returns {Promise} 响应对象\n */\nexport async function GET(request, { params }) {\n try {\n const { projectId } = params;\n\n // 从查询参数中获取 chunkName\n const { searchParams } = new URL(request.url);\n const chunkName = searchParams.get('chunkName');\n\n if (!chunkName) {\n return NextResponse.json({ error: '文本块名称不能为空' }, { status: 400 });\n }\n\n // 根据名称和项目ID查询文本块\n const chunk = await getChunkByName(projectId, chunkName);\n\n if (!chunk) {\n return NextResponse.json({ error: '未找到指定的文本块' }, { status: 404 });\n }\n\n // 返回文本块信息\n return NextResponse.json(chunk);\n } catch (error) {\n console.error('根据名称获取文本块失败:', String(error));\n return NextResponse.json({ error: '获取文本块失败: ' + error.message }, { status: 500 });\n }\n}\n"], ["/easy-dataset/lib/db/model-config.js", "'use server';\nimport { db } from '@/lib/db/index';\nimport { nanoid } from 'nanoid';\n\nexport async function getModelConfigByProjectId(projectId) {\n try {\n return await db.modelConfig.findMany({ where: { projectId } });\n } catch (error) {\n console.error('Failed to get modelConfig by projectId in database');\n throw error;\n }\n}\n\nexport async function createInitModelConfig(data) {\n try {\n return await db.modelConfig.createManyAndReturn({ data });\n } catch (error) {\n console.error('Failed to create init modelConfig list in database');\n throw error;\n }\n}\n\nexport async function getModelConfigById(id) {\n try {\n return await db.modelConfig.findUnique({ where: { id } });\n } catch (error) {\n console.error('Failed to get modelConfig by id in database');\n throw error;\n }\n}\n\nexport async function deleteModelConfigById(id) {\n try {\n return await db.modelConfig.delete({ where: { id } });\n } catch (error) {\n console.error('Failed to delete modelConfig by id in database');\n throw error;\n }\n}\n\nexport async function saveModelConfig(models) {\n try {\n if (!models.id) {\n models.id = nanoid(12);\n }\n return await db.modelConfig.upsert({ create: models, update: models, where: { id: models.id } });\n } catch (error) {\n console.error('Failed to create modelConfig in database');\n throw error;\n }\n}\n"], ["/easy-dataset/lib/llm/prompts/addLabelEn.js", "module.exports = function getAddLabelPrompt(label, question) {\n return `\n# Role: Label Matching Expert\n - Description: You are a label matching expert, proficient in assigning the most appropriate domain labels to questions based on the given label array and question array.You are familiar with the hierarchical structure of labels and can prioritize matching secondary labels according to the content of the questions.If a secondary label cannot be matched, you will match a primary label.Finally, if no match is found, you will assign the \"Other\" label.\n\n### Skill:\n1. Be familiar with the label hierarchical structure and accurately identify primary and secondary labels.\n2. Be able to intelligently match the most appropriate label based on the content of the question.\n3. Be able to handle complex label matching logic to ensure that each question is assigned the correct label.\n4. Be able to generate results in the specified output format without changing the original data structure.\n5. Be able to handle large - scale data to ensure efficient and accurate label matching.\n\n## Goals:\n1. Assign the most appropriate domain label to each question in the question array.\n2. Prioritize matching secondary labels.If no secondary label can be matched, match a primary label.Finally, assign the \"Other\" label.\n3. Ensure that the output format meets the requirements without changing the original data structure.\n4. Provide an efficient label matching algorithm to ensure performance when processing large - scale data.\n5. Ensure the accuracy and consistency of label matching.\n\n## OutputFormat:\n1. The output result must be an array, and each element contains the \"question\" and \"label\" fields.\n2. The \"label\" field must be the label matched from the label array.If no match is found, assign the \"Other\" label.\n3. Do not change the original data structure, only add the \"label\" field.\n\n## Label Array:\n\n${label}\n\n## Question Array:\n\n${question}\n\n\n## Workflow:\n1. Take a deep breath and work on this problem step - by - step.\n2. First, read the label array and the question array.\n3. Then, iterate through each question in the question array and match the labels in the label array according to the content of the question.\n4. Prioritize matching secondary labels.If no secondary label can be matched, match a primary label.Finally, assign the \"Other\" label.\n5. Add the matched label to the question object without changing the original data structure.\n6. Finally, output the result array, ensuring that the format meets the requirements.\n\n\n## Constrains:\n1. Only add one \"label\" field without changing any other format or data.\n2. Must return the result in the specified format.\n3. Prioritize matching secondary labels.If no secondary label can be matched, match a primary label.Finally, assign the \"Other\" label.\n4. Ensure the accuracy and consistency of label matching.\n5. The matched label must exist in the label array.If it does not exist, assign the \"Other\" label.\n7. The output result must be an array, and each element contains the \"question\" and \"label\" fields(only output this, do not output any other irrelevant content).\n\n ## Output Example:\n\\`\\`\\`json\n [\n {\n \"question\": \"XSS为什么会在2003年后引起人们更多关注并被OWASP列为威胁榜首?\",\n \"label\": \"2.2 XSS攻击\"\n }\n ]\n \\`\\`\\`\n\n `;\n};\n"], ["/easy-dataset/prisma/generate-template.js", "/**\n * 此脚本用于生成空的模板数据库文件(template.sqlite)\n * 该文件将在应用打包时被包含,并在用户首次启动应用时作为初始数据库\n */\n\nconst fs = require('fs');\nconst path = require('path');\nconst { execSync } = require('child_process');\n\nconst templatePath = path.join(__dirname, 'template.sqlite');\nconst sqlitePath = path.join(__dirname, 'empty.db.sqlite');\n\n// 如果存在旧的模板文件,先删除\nif (fs.existsSync(templatePath)) {\n console.log('删除旧的模板数据库...');\n fs.unlinkSync(templatePath);\n}\n\n// 如果存在临时数据库文件,先删除\nif (fs.existsSync(sqlitePath)) {\n console.log('删除临时数据库文件...');\n fs.unlinkSync(sqlitePath);\n}\n\ntry {\n console.log('设置临时数据库路径...');\n // 设置 DATABASE_URL 环境变量\n process.env.DATABASE_URL = `file:${sqlitePath}`;\n\n console.log('执行 prisma db push 创建新的数据库架构...');\n // 执行 prisma db push 创建数据库架构\n execSync('npx prisma db push', { stdio: 'inherit' });\n\n console.log('将生成的数据库文件复制为模板...');\n // 复制生成的数据库文件为模板\n fs.copyFileSync(sqlitePath, templatePath);\n\n console.log(`✅ 模板数据库已成功生成: ${templatePath}`);\n} catch (error) {\n console.error('❌ 生成模板数据库失败:', error);\n process.exit(1);\n} finally {\n // 清理: 删除临时数据库文件\n if (fs.existsSync(sqlitePath)) {\n console.log('清理临时数据库文件...');\n fs.unlinkSync(sqlitePath);\n }\n}\n"], ["/easy-dataset/lib/i18n.js", "import i18n from 'i18next';\nimport { initReactI18next } from 'react-i18next';\nimport LanguageDetector from 'i18next-browser-languagedetector';\n\n// 导入翻译文件\nimport enTranslation from '../locales/en/translation.json';\nimport zhCNTranslation from '../locales/zh-CN/translation.json';\n\n// 避免在服务器端重复初始化\nconst isServer = typeof window === 'undefined';\nconst i18nInstance = i18n.createInstance();\n\n// 仅在客户端初始化 i18next\nif (!isServer && !i18n.isInitialized) {\n i18nInstance\n // 检测用户语言\n .use(LanguageDetector)\n // 将 i18n 实例传递给 react-i18next\n .use(initReactI18next)\n // 初始化\n .init({\n resources: {\n en: {\n translation: enTranslation\n },\n 'zh-CN': {\n translation: zhCNTranslation\n }\n },\n fallbackLng: 'en',\n debug: process.env.NODE_ENV === 'development',\n\n interpolation: {\n escapeValue: false // 不转义 HTML\n },\n\n // 检测用户语言的选项\n detection: {\n order: ['localStorage', 'navigator'],\n lookupLocalStorage: 'i18nextLng',\n caches: ['localStorage']\n }\n });\n}\n\nexport default i18nInstance;\n"], ["/easy-dataset/lib/llm/prompts/ga-generation.js", "/**\n * Genre-Audience (GA) 对生成提示词 (中文版)\n * 基于 MGA (Massive Genre-Audience) 数据增强方法\n */\n\nexport const GA_GENERATION_PROMPT = `#身份与能力#\n你是一位内容创作专家,擅长文本分析和根据不同的知识背景和学习目标,设计多样化的提问方式和互动场景,以产出多样化且高质量的文本。你的设计总能将原文转化为引人注目的内容,赢得了读者和行业专业人士的一致好评!\n\n#工作流程#\n请发挥你的想象力和创造力,为原始文本生成5对[体裁]和[受众]的组合。你的分析应遵循以下要求:\n1. 首先,分析源文本的特点,包括写作风格、信息含量和价值。\n2. 然后,基于上下文内容,设想5种不同的学习或探究场景。\n3. 其次,要思考如何在保留主要内容和信息的同时,探索更广泛的受众参与和替代体裁的可能性。\n3. 注意,禁止生成重复或相似的[体裁]和[受众]。\n4. 最后,为每个场景生成一对独特的 [体裁] 和 [受众] 组合。\n\n\n#详细要求#\n确保遵循上述工作流程要求,然后根据以下规范生成5对[体裁]和[受众]组合(请记住您必须严格遵循#回复#部分中提供的格式要求):\n您提供的[体裁]应满足以下要求:\n1. 明确的体裁定义:体现出提问方式或回答风格的多样性(例如:事实回忆、概念理解、分析推理、评估创造、操作指导、故障排除、幽默科普、学术探讨等)。要表现出强烈的多样性;包括您遇到过的、阅读过的或能够想象的提问体裁\n2. 详细的体裁描述:提供2-3句描述每种体裁的话,考虑但不限于类型、风格、情感基调、形式、冲突、节奏和氛围。强调多样性以指导针对特定受众的知识适应,促进不同背景的理解。注意:排除视觉格式(图画书、漫画、视频);使用纯文本体裁。\n## 示例:\n体裁:“深究原因型”\n描述:这类问题旨在探究现象背后的根本原因或机制。通常以“为什么...”或“...的原理是什么?”开头,鼓励进行深度思考和解释。回答时应侧重于逻辑链条和根本原理的阐述。\n\n您提供的[受众]应满足以下要求:\n1. 明确的受众定义:表现出强烈的多样性;包括感兴趣和不感兴趣的各方,喜欢和不喜欢内容的人,克服仅偏向积极受众的偏见(例如:不同年龄段、知识水平、学习动机、特定职业背景、遇到的具体问题等)\n2. 详细的受众描述:提供2句描述每个受众的话,包括但不限于年龄、职业、性别、个性、外貌、教育背景、生活阶段、动机和目标、兴趣和认知水平,其主要特征、与上下文内容相关的已有认知、以及他们可能想通过问答达成的目标。\n## 示例:\n受众:“对技术细节好奇的工程师预备生”\n描述:这是一群具备一定理工科基础,但对特定技术领域细节尚不熟悉的大学生。他们学习主动性强,渴望理解技术背后的“如何实现”和“为何如此设计”。\n\n#重要提示:你必须仅以有效的JSON数组格式回应,格式如下:#\n\n[\n {\n \"genre\": {\n \"title\": \"体裁标题\",\n \"description\": \"详细的体裁描述\"\n },\n \"audience\": {\n \"title\": \"受众标题\",\n \"description\": \"详细的受众描述\"\n }\n },\n {\n \"genre\": {\n \"title\": \"体裁标题\",\n \"description\": \"详细的体裁描述\"\n },\n \"audience\": {\n \"title\": \"受众标题\",\n \"description\": \"详细的受众描述\"\n }\n }\n // ... 另外3对 (总共5对)\n]\n\n**请勿包含任何解释性文本、Markdown格式或其他额外内容。仅返回JSON数组。**\n\n#待分析的源文本#\n{text_content}`;\n"], ["/easy-dataset/electron/modules/ipc-handlers.js", "const { ipcMain } = require('electron');\nconst { checkUpdate, downloadUpdate, installUpdate } = require('./updater');\n\n/**\n * 设置 IPC 处理程序\n * @param {Object} app Electron app 对象\n * @param {boolean} isDev 是否为开发环境\n */\nfunction setupIpcHandlers(app, isDev) {\n // 获取用户数据路径\n ipcMain.on('get-user-data-path', event => {\n event.returnValue = app.getPath('userData');\n });\n\n // 检查更新\n ipcMain.handle('check-update', async () => {\n return await checkUpdate(isDev);\n });\n\n // 下载更新\n ipcMain.handle('download-update', async () => {\n return await downloadUpdate();\n });\n\n // 安装更新\n ipcMain.handle('install-update', () => {\n return installUpdate();\n });\n}\n\nmodule.exports = {\n setupIpcHandlers\n};\n"], ["/easy-dataset/app/api/projects/[projectId]/model-config/[modelConfigId]/route.js", "import { NextResponse } from 'next/server';\nimport { deleteModelConfigById } from '@/lib/db/model-config';\n\n// 删除模型配置\nexport async function DELETE(request, { params }) {\n try {\n const { projectId, modelConfigId } = params;\n // 验证项目 ID\n if (!projectId) {\n return NextResponse.json({ error: 'The project ID cannot be empty' }, { status: 400 });\n }\n await deleteModelConfigById(modelConfigId);\n return NextResponse.json(true);\n } catch (error) {\n console.error('Error obtaining model configuration:', String(error));\n return NextResponse.json({ error: 'Failed to obtain model configuration' }, { status: 500 });\n }\n}\n"], ["/easy-dataset/components/datasets/EditableField.js", "'use client';\n\nimport { useState } from 'react';\nimport { Box, Typography, Button, TextField, IconButton, Switch, FormControlLabel } from '@mui/material';\nimport EditIcon from '@mui/icons-material/Edit';\nimport AutoFixHighIcon from '@mui/icons-material/AutoFixHigh';\nimport ReactMarkdown from 'react-markdown';\nimport { useTranslation } from 'react-i18next';\nimport { useTheme } from '@mui/material/styles';\n\n/**\n * 可编辑字段组件,支持 Markdown 和原始文本两种展示方式\n */\nexport default function EditableField({\n label,\n value,\n multiline = true,\n editing,\n onEdit,\n onChange,\n onSave,\n onCancel,\n onOptimize,\n tokenCount\n}) {\n const { t } = useTranslation();\n const theme = useTheme();\n const [useMarkdown, setUseMarkdown] = useState(false);\n\n const toggleMarkdown = () => {\n setUseMarkdown(!useMarkdown);\n };\n\n return (\n \n \n \n {label}\n \n {!editing && value && (\n <>\n {/* 字符数标签 */}\n \n {value.length} Characters\n \n\n {/* Token 标签 */}\n {tokenCount > 0 && (\n \n {tokenCount} Tokens\n \n )}\n \n )}\n {!editing && (\n <>\n \n \n \n {onOptimize && (\n \n \n \n )}\n }\n label={{useMarkdown ? 'Markdown' : 'Text'}}\n sx={{ ml: 1 }}\n />\n \n )}\n \n {editing ? (\n <>\n \n \n \n \n \n \n ) : (\n \n {value ? (\n useMarkdown ? (\n {value}\n ) : (\n {value}\n )\n ) : (\n \n {t('common.noData')}\n \n )}\n \n )}\n \n );\n}\n"], ["/easy-dataset/lib/file/split-markdown/output/formatter.js", "/**\n * 输出格式化模块\n */\n\n/**\n * 将分割后的文本重新组合成Markdown文档\n * @param {Array} splitResult - 分割结果数组\n * @returns {string} - 组合后的Markdown文档\n */\nfunction combineMarkdown(splitResult) {\n let result = '';\n\n for (let i = 0; i < splitResult.length; i++) {\n const part = splitResult[i];\n\n // 添加分隔线和摘要\n if (i > 0) {\n result += '\\n\\n---\\n\\n';\n }\n\n result += `> **📑 Summarization:** *${part.summary}*\\n\\n---\\n\\n${part.content}`;\n }\n\n return result;\n}\n\nmodule.exports = {\n combineMarkdown\n};\n"], ["/easy-dataset/components/playground/PlaygroundHeader.js", "'use client';\n\nimport React from 'react';\nimport { Grid, Button, Divider, FormControl, InputLabel, Select, MenuItem } from '@mui/material';\nimport DeleteIcon from '@mui/icons-material/Delete';\nimport { useTheme } from '@mui/material/styles';\nimport ModelSelector from './ModelSelector';\nimport { playgroundStyles } from '@/styles/playground';\nimport { useTranslation } from 'react-i18next';\n\nconst PlaygroundHeader = ({\n availableModels,\n selectedModels,\n handleModelSelection,\n handleClearConversations,\n conversations,\n outputMode,\n handleOutputModeChange\n}) => {\n const theme = useTheme();\n const styles = playgroundStyles(theme);\n const { t } = useTranslation();\n\n const isClearDisabled = selectedModels.length === 0 || Object.values(conversations).every(conv => conv.length === 0);\n\n return (\n <>\n \n \n \n \n \n \n {t('playground.outputMode')}\n \n {t('playground.normalOutput')}\n {t('playground.streamingOutput')}\n \n \n \n \n }\n onClick={handleClearConversations}\n disabled={isClearDisabled}\n sx={styles.clearButton}\n >\n {t('playground.clearConversation')}\n \n \n \n\n \n \n );\n};\n\nexport default PlaygroundHeader;\n"], ["/easy-dataset/app/api/projects/[projectId]/questions/[questionId]/route.js", "import { NextResponse } from 'next/server';\nimport { deleteQuestion } from '@/lib/db/questions';\n\n// 删除单个问题\nexport async function DELETE(request, { params }) {\n try {\n const { projectId, questionId } = params;\n\n // 验证参数\n if (!projectId) {\n return NextResponse.json({ error: 'Project ID is required' }, { status: 400 });\n }\n\n if (!questionId) {\n return NextResponse.json({ error: 'Question ID is required' }, { status: 400 });\n }\n\n // 删除问题\n await deleteQuestion(questionId);\n\n return NextResponse.json({ success: true, message: 'Delete successful' });\n } catch (error) {\n console.error('Delete failed:', String(error));\n return NextResponse.json({ error: error.message || 'Delete failed' }, { status: 500 });\n }\n}\n"], ["/easy-dataset/lib/llm/prompts/label.js", "module.exports = function getLabelPrompt({ text, globalPrompt, domainTreePrompt }) {\n if (globalPrompt) {\n globalPrompt = `- 在后续的任务中,你务必遵循这样的规则:${globalPrompt}`;\n }\n if (domainTreePrompt) {\n domainTreePrompt = `- 在生成标签时,你务必遵循这样的规则:${domainTreePrompt}`;\n }\n return `\n# Role: 领域分类专家 & 知识图谱专家\n- Description: 作为一名资深的领域分类专家和知识图谱专家,擅长从文本内容中提取核心主题,构建分类体系,并输出规定 JSON 格式的标签树。\n${globalPrompt}\n\n## Skills:\n1. 精通文本主题分析和关键词提取\n2. 擅长构建分层知识体系\n3. 熟练掌握领域分类方法论\n4. 具备知识图谱构建能力\n5. 精通JSON数据结构\n\n## Goals:\n1. 分析书籍目录内容\n2. 识别核心主题和关键领域\n3. 构建两级分类体系\n4. 确保分类逻辑合理\n5. 生成规范的JSON输出\n\n## Workflow:\n1. 仔细阅读完整的书籍目录内容\n2. 提取关键主题和核心概念\n3. 对主题进行分组和归类\n4. 构建一级领域标签\n5. 为适当的一级标签添加二级标签\n6. 检查分类逻辑的合理性\n7. 生成符合格式的JSON输出\n\n ## 需要分析的目录\n ${text}\n\n ## 限制\n1. 一级领域标签数量5-10个\n2. 二级领域标签数量1-10个\n3. 最多两层分类层级\n4. 分类必须与原始目录内容相关\n5. 输出必须符合指定 JSON 格式,不要输出 JSON 外其他任何不相关内容\n6. 标签的名字最多不要超过 6 个字\n7. 在每个标签前加入序号(序号不计入字数)\n${domainTreePrompt}\n\n## OutputFormat:\n\\`\\`\\`json\n[\n {\n \"label\": \"1 一级领域标签\",\n \"child\": [\n {\"label\": \"1.1 二级领域标签1\"},\n {\"label\": \"1.2 二级领域标签2\"}\n ]\n },\n {\n \"label\": \"2 一级领域标签(无子标签)\"\n }\n]\n\\`\\`\\`\n `;\n};\n"], ["/easy-dataset/app/api/projects/[projectId]/questions/batch-delete/route.js", "import { NextResponse } from 'next/server';\nimport { batchDeleteQuestions } from '@/lib/db/questions';\n\n// 批量删除问题\nexport async function DELETE(request) {\n try {\n const body = await request.json();\n const { questionIds } = body;\n\n // 验证参数\n if (questionIds.length === 0) {\n return NextResponse.json({ error: 'Question ID is required' }, { status: 400 });\n }\n\n // 删除问题\n await batchDeleteQuestions(questionIds);\n\n return NextResponse.json({ success: true, message: 'Delete successful' });\n } catch (error) {\n console.error('Delete failed:', String(error));\n return NextResponse.json({ error: error.message || 'Delete failed' }, { status: 500 });\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/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/lib/llm/prompts/optimizeCot.js", "module.exports = function optimizeCotPrompt(originalQuestion, answer, originalCot) {\n return `\n# Role: 思维链优化专家\n## Profile:\n- Description: 你是一位擅长优化思维链的专家,能够对给定的思维链进行处理,去除其中的参考引用相关话术,使其呈现为一个正常的推理过程。\n\n## Skills:\n1. 准确识别并去除思维链中的参考引用话术。\n2. 确保优化后的思维链逻辑连贯、推理合理。\n3. 维持思维链与原始问题和答案的相关性。\n\n## Workflow:\n1. 仔细研读原始问题、答案和优化前的思维链。\n2. 识别思维链中所有参考引用相关的表述,如“参考 XX 资料”“文档中提及 XX”“参考内容中提及 XXX”等。\n3. 去除这些引用话术,同时调整语句,保证思维链的逻辑连贯性。\n4. 检查优化后的思维链是否仍然能够合理地推导出答案,并且与原始问题紧密相关。\n\n## 原始问题\n${originalQuestion}\n\n## 答案\n${answer}\n\n## 优化前的思维链\n${originalCot}\n\n## Constrains:\n1. 优化后的思维链必须去除所有参考引用相关话术。\n2. 思维链的逻辑推理过程必须完整且合理。\n3. 优化后的思维链必须与原始问题和答案保持紧密关联。\n4. 给出的答案不要包含 “优化后的思维链” 这样的话术,直接给出优化后的思维链结果。\n5. 思维链应按照正常的推理思路返回,如:先分析理解问题的本质,按照 \"首先、然后、接着、另外、最后\" 等步骤逐步思考,展示一个完善的推理过程。\n `;\n};\n"], ["/easy-dataset/components/tasks/TaskFilters.js", "'use client';\n\nimport React from 'react';\nimport {\n Box,\n FormControl,\n InputLabel,\n Select,\n MenuItem,\n OutlinedInput,\n IconButton,\n Tooltip,\n CircularProgress\n} from '@mui/material';\nimport RefreshIcon from '@mui/icons-material/Refresh';\nimport { useTranslation } from 'react-i18next';\n\n// 任务筛选组件\nexport default function TaskFilters({ statusFilter, setStatusFilter, typeFilter, setTypeFilter, loading, onRefresh }) {\n const { t } = useTranslation();\n\n return (\n \n {/* 状态筛选 */}\n \n {t('tasks.filters.status')}\n setStatusFilter(e.target.value)}\n input={}\n >\n {t('datasets.filterAll')}\n {t('tasks.status.processing')}\n {t('tasks.status.completed')}\n {t('tasks.status.failed')}\n {t('tasks.status.aborted')}\n \n \n\n {/* 类型筛选 */}\n \n {t('tasks.filters.type')}\n setTypeFilter(e.target.value)}\n input={}\n >\n {t('datasets.filterAll')}\n {t('tasks.types.text-processing')}\n {t('tasks.types.question-generation')}\n {t('tasks.types.answer-generation')}\n {t('tasks.types.data-distillation')}\n {t('tasks.types.pdf-processing')}\n \n \n\n {/* 刷新按钮 */}\n \n \n {loading ? : }\n \n \n \n );\n}\n"], ["/easy-dataset/lib/util/file.js", "import { createHash } from 'crypto';\nimport { createReadStream } from 'fs';\n\nexport async function getFileMD5(filePath) {\n return new Promise((resolve, reject) => {\n const hash = createHash('md5');\n const stream = createReadStream(filePath);\n\n stream.on('data', chunk => hash.update(chunk));\n stream.on('end', () => resolve(hash.digest('hex')));\n stream.on('error', reject);\n });\n}\n\nexport function filterDomainTree(tree = []) {\n for (let i = 0; i < tree.length; i++) {\n const { child } = tree[i];\n delete tree[i].id;\n delete tree[i].projectId;\n delete tree[i].parentId;\n delete tree[i].questionCount;\n filterDomainTree(child);\n }\n return tree;\n}\n"], ["/easy-dataset/app/projects/[projectId]/page.js", "'use client';\n\nimport { useEffect } from 'react';\nimport { useRouter } from 'next/navigation';\nimport axios from 'axios';\nimport { toast } from 'sonner';\nimport { useSetAtom } from 'jotai/index';\nimport { modelConfigListAtom, selectedModelInfoAtom } from '@/lib/store';\n\nexport default function ProjectPage({ params }) {\n const router = useRouter();\n const setConfigList = useSetAtom(modelConfigListAtom);\n const setSelectedModelInfo = useSetAtom(selectedModelInfoAtom);\n const { projectId } = params;\n\n // 默认重定向到文本分割页面\n useEffect(() => {\n getModelConfigList(projectId);\n router.push(`/projects/${projectId}/text-split`);\n }, [projectId, router]);\n\n const getModelConfigList = projectId => {\n axios\n .get(`/api/projects/${projectId}/model-config`)\n .then(response => {\n setConfigList(response.data.data);\n if (response.data.defaultModelConfigId) {\n setSelectedModelInfo(response.data.data.find(item => item.id === response.data.defaultModelConfigId));\n } else {\n setSelectedModelInfo('');\n }\n })\n .catch(error => {\n toast.error('get model list error');\n });\n };\n\n return null;\n}\n"], ["/easy-dataset/app/layout.js", "import './globals.css';\nimport ThemeRegistry from '@/components/ThemeRegistry';\nimport I18nProvider from '@/components/I18nProvider';\nimport { Toaster } from 'sonner';\nimport { Provider } from 'jotai';\n\nexport const metadata = {\n title: 'Easy Dataset',\n description: '一个强大的 LLM 数据集生成工具',\n icons: {\n icon: '/imgs/logo.ico' // 更新为正确的文件名\n }\n};\n\nexport default function RootLayout({ children }) {\n return (\n \n \n \n \n \n {children}\n \n \n \n \n \n \n );\n}\n"], ["/easy-dataset/components/LanguageSwitcher.js", "'use client';\n\nimport { useTranslation } from 'react-i18next';\nimport { IconButton, Tooltip, useTheme, Typography } from '@mui/material';\n\nexport default function LanguageSwitcher() {\n const { i18n } = useTranslation();\n const theme = useTheme();\n\n const toggleLanguage = () => {\n const newLang = i18n.language === 'zh-CN' ? 'en' : 'zh-CN';\n i18n.changeLanguage(newLang);\n };\n\n return (\n \n \n \n {i18n.language === 'zh-CN' ? 'EN' : '中'}\n \n \n \n );\n}\n"], ["/easy-dataset/lib/util/async.js", "// 并行处理数组的辅助函数,限制并发数\nexport const processInParallel = async (items, processFunction, concurrencyLimit, onProgress) => {\n const results = [];\n const inProgress = new Set();\n const queue = [...items];\n let completedCount = 0;\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 onProgress && onProgress(++completedCount, items.length);\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"], ["/easy-dataset/lib/file/split-markdown/utils/common.js", "/**\n * 通用工具函数模块\n */\n\nconst fs = require('fs');\nconst path = require('path');\n\n/**\n * 检查并创建目录\n * @param {string} directory - 目录路径\n */\nfunction ensureDirectoryExists(directory) {\n if (!fs.existsSync(directory)) {\n fs.mkdirSync(directory, { recursive: true });\n }\n}\n\n/**\n * 从文件路径获取不带扩展名的文件名\n * @param {string} filePath - 文件路径\n * @returns {string} - 不带扩展名的文件名\n */\nfunction getFilenameWithoutExt(filePath) {\n return path.basename(filePath).replace(/\\.[^/.]+$/, '');\n}\n\nmodule.exports = {\n ensureDirectoryExists,\n getFilenameWithoutExt\n};\n"], ["/easy-dataset/lib/llm/prompts/addLabel.js", "module.exports = function getAddLabelPrompt(label, question) {\n return `\n# Role: 标签匹配专家\n- Description: 你是一名标签匹配专家,擅长根据给定的标签数组和问题数组,将问题打上最合适的领域标签。你熟悉标签的层级结构,并能根据问题的内容优先匹配二级标签,若无法匹配则匹配一级标签,最后打上“其他”标签。\n\n### Skill:\n1. 熟悉标签层级结构,能够准确识别一级和二级标签。\n2. 能够根据问题的内容,智能匹配最合适的标签。\n3. 能够处理复杂的标签匹配逻辑,确保每个问题都能被打上正确的标签。\n4. 能够按照规定的输出格式生成结果,确保不改变原有数据结构。\n5. 能够处理大规模数据,确保高效准确的标签匹配。\n\n## Goals:\n1. 将问题数组中的每个问题打上最合适的领域标签。\n2. 优先匹配二级标签,若无法匹配则匹配一级标签,最后打上“其他”标签。\n3. 确保输出格式符合要求,不改变原有数据结构。\n4. 提供高效的标签匹配算法,确保处理大规模数据时的性能。\n5. 确保标签匹配的准确性和一致性。\n\n## OutputFormat:\n1. 输出结果必须是一个数组,每个元素包含 question、和 label 字段。\n2. label 字段必须是根据标签数组匹配到的标签,若无法匹配则打上“其他”标签。\n3. 不改变原有数据结构,只新增 label 字段。\n\n## 标签数组:\n\n${label}\n\n## 问题数组:\n\n${question}\n\n\n## Workflow:\n1. Take a deep breath and work on this problem step-by-step.\n2. 首先,读取标签数组和问题数组。\n3. 然后,遍历问题数组中的每个问题,根据问题的内容匹配标签数组中的标签。\n4. 优先匹配二级标签,若无法匹配则匹配一级标签,最后打上“其他”标签。\n5. 将匹配到的标签添加到问题对象中,确保不改变原有数据结构。\n6. 最后,输出结果数组,确保格式符合要求。\n\n\n## Constrains:\n1. 只新增一个 label 字段,不改变其他任何格式和数据。\n2. 必须按照规定格式返回结果。\n3. 优先匹配二级标签,若无法匹配则匹配一级标签,最后打上“其他”标签。\n4. 确保标签匹配的准确性和一致性。\n5. 匹配的标签必须在标签数组中存在,如果不存在,就打上 其他 \n7. 输出结果必须是一个数组,每个元素包含 question、label 字段(只输出这个,不要输出任何其他无关内容)\n\n## Output Example:\n \\`\\`\\`json\n [\n {\n \"question\": \"XSS为什么会在2003年后引起人们更多关注并被OWASP列为威胁榜首?\",\n \"label\": \"2.2 XSS攻击\"\n }\n ]\n \\`\\`\\`\n\n `;\n};\n"], ["/easy-dataset/components/text-split/components/DomainTreeView.js", "'use client';\n\nimport { Box } from '@mui/material';\nimport { TreeView, TreeItem } from '@mui/lab';\nimport ExpandMoreIcon from '@mui/icons-material/ExpandMore';\nimport ChevronRightIcon from '@mui/icons-material/ChevronRight';\n\n/**\n * 领域知识树组件\n * @param {Object} props\n * @param {Array} props.nodes - 树节点数组\n */\nexport default function DomainTreeView({ nodes = [] }) {\n if (!nodes || nodes.length === 0) return null;\n\n const renderTreeItems = nodes => {\n return nodes.map((node, index) => (\n \n {node.children && node.children.length > 0 && renderTreeItems(node.children)}\n \n ));\n };\n\n return (\n }\n defaultExpandIcon={}\n sx={{ flexGrow: 1, overflowY: 'auto' }}\n >\n {renderTreeItems(nodes)}\n \n );\n}\n"], ["/easy-dataset/electron/modules/cache.js", "const { clearLogs } = require('./logger');\nconst { clearDatabaseCache } = require('./database');\n\n/**\n * 清除缓存函数 - 清理logs和local-db目录\n * @param {Object} app Electron app 对象\n * @returns {Promise} 操作是否成功\n */\nasync function clearCache(app) {\n // 清理日志目录\n await clearLogs(app);\n\n // 清理数据库缓存\n await clearDatabaseCache(app);\n\n return true;\n}\n\nmodule.exports = {\n clearCache\n};\n"], ["/easy-dataset/hooks/useFileProcessingStatus.js", "import { useState, useEffect } from 'react';\n\n// 存储文件处理状态的共享对象\nconst fileProcessingSubscribers = {\n value: false,\n listeners: new Set()\n};\n\n// 存储文件任务信息的共享对象\nconst fileTaskSubscribers = {\n value: null,\n listeners: new Set()\n};\n\n/**\n * 自定义hook,用于在组件间共享文件处理任务的状态\n */\nexport default function useFileProcessingStatus() {\n const [taskFileProcessing, setTaskFileProcessing] = useState(fileProcessingSubscribers.value);\n const [task, setTask] = useState(fileTaskSubscribers.value);\n\n useEffect(() => {\n // 添加当前组件为订阅者\n const updateProcessingState = newValue => setTaskFileProcessing(newValue);\n const updateTaskState = newTask => setTask(newTask);\n\n fileProcessingSubscribers.listeners.add(updateProcessingState);\n fileTaskSubscribers.listeners.add(updateTaskState);\n\n // 组件卸载时清理\n return () => {\n fileProcessingSubscribers.listeners.delete(updateProcessingState);\n fileTaskSubscribers.listeners.delete(updateTaskState);\n };\n }, []);\n\n // 共享的setState函数\n const setSharedFileProcessing = newValue => {\n fileProcessingSubscribers.value = newValue;\n // 通知所有订阅者\n fileProcessingSubscribers.listeners.forEach(listener => listener(newValue));\n };\n\n // 共享的setTask函数\n const setSharedTask = newTask => {\n fileTaskSubscribers.value = newTask;\n // 通知所有订阅者\n fileTaskSubscribers.listeners.forEach(listener => listener(newTask));\n };\n\n return {\n taskFileProcessing,\n task,\n setTaskFileProcessing: setSharedFileProcessing,\n setTask: setSharedTask\n };\n}\n"], ["/easy-dataset/lib/llm/prompts/distillTags.js", "/**\n * 根据标签构造子标签的提示词\n * @param {string} tagPath - 标签链路,例如 “知识库->体育”\n * @param {string} parentTag - 主题标签名称,例如“体育”\n * @param {Array} existingTags - 该标签下已经创建的子标签(避免重复),例如 [\"足球\", \"乒乓球\"]\n * @param {number} count - 希望生成子标签的数量,例如:10\n * @param {string} globalPrompt - 项目全局提示词\n * @returns {string} 提示词\n */\nexport function distillTagsPrompt(tagPath, parentTag, existingTags = [], count = 10, globalPrompt = '') {\n const existingTagsText =\n existingTags.length > 0 ? `已有的子标签包括:${existingTags.join('、')},请不要生成与这些重复的标签。` : '';\n\n // 构建全局提示词部分\n const globalPromptText = globalPrompt ? `你必须遵循这个要求:${globalPrompt}` : '';\n\n return `\n你是一个专业的知识标签生成助手。我需要你帮我为主题\"${parentTag}\"生成${count}个子标签。\n\n标签完整链路是:${tagPath || parentTag}\n\n请遵循以下规则:\n${globalPromptText}\n1. 生成的标签应该是\"${parentTag}\"领域内的专业子类别或子主题\n2. 每个标签应该简洁、明确,通常为2-6个字\n3. 标签之间应该有明显的区分,覆盖不同的方面\n4. 标签应该是名词或名词短语,不要使用动词或形容词\n5. 标签应该具有实用性,能够作为问题生成的基础\n6. 标签应该有明显的序号,主题为 1 汽车,子标签应该为 1.1 汽车品牌,1.2 汽车型号,1.3 汽车价格等\n7. 若主题没有序号,如汽车,说明当前在生成顶级标签,子标签应为 1 汽车品牌 2 汽车型号 3 汽车价格等\n\n${existingTagsText}\n\n请直接以JSON数组格式返回标签,不要有任何额外的解释或说明,格式如下:\n[\"序号 标签1\", \"序号 标签2\", \"序号 标签3\", ...]\n`;\n}\n"], ["/easy-dataset/styles/home.js", "// styles/home.js\nexport const styles = {\n heroSection: {\n pt: { xs: 6, md: 10 },\n pb: { xs: 6, md: 8 },\n position: 'relative',\n overflow: 'hidden',\n transition: 'all 0.3s ease-in-out'\n },\n heroBackground: theme => ({\n background:\n theme.palette.mode === 'dark'\n ? 'linear-gradient(135deg, rgba(42, 92, 170, 0.25) 0%, rgba(139, 92, 246, 0.25) 100%)'\n : 'linear-gradient(135deg, rgba(42, 92, 170, 0.08) 0%, rgba(139, 92, 246, 0.08) 100%)',\n '&::before': {\n content: '\"\"',\n position: 'absolute',\n top: 0,\n left: 0,\n right: 0,\n bottom: 0,\n background: 'url(\"/imgs/grid-pattern.png\") repeat',\n opacity: theme.palette.mode === 'dark' ? 0.05 : 0.03,\n zIndex: 0\n }\n }),\n decorativeCircle: {\n position: 'absolute',\n width: '800px',\n height: '800px',\n borderRadius: '50%',\n background: 'radial-gradient(circle, rgba(139, 92, 246, 0.15) 0%, rgba(42, 92, 170, 0) 70%)',\n top: '-300px',\n right: '-200px',\n zIndex: 0,\n animation: 'pulse 15s infinite ease-in-out',\n '@keyframes pulse': {\n '0%': { transform: 'scale(1)' },\n '50%': { transform: 'scale(1.05)' },\n '100%': { transform: 'scale(1)' }\n }\n },\n decorativeCircleSecond: {\n position: 'absolute',\n width: '500px',\n height: '500px',\n borderRadius: '50%',\n background: 'radial-gradient(circle, rgba(42, 92, 170, 0.1) 0%, rgba(139, 92, 246, 0) 70%)',\n bottom: '-200px',\n left: '-100px',\n zIndex: 0,\n animation: 'pulse2 20s infinite ease-in-out',\n '@keyframes pulse2': {\n '0%': { transform: 'scale(1)' },\n '50%': { transform: 'scale(1.08)' },\n '100%': { transform: 'scale(1)' }\n }\n },\n gradientTitle: theme => ({\n mb: 2,\n background: theme.palette.gradient.primary,\n WebkitBackgroundClip: 'text',\n WebkitTextFillColor: 'transparent',\n backgroundClip: 'text',\n textFillColor: 'transparent'\n }),\n createButton: theme => ({\n mt: 3,\n px: 4,\n py: 1.2,\n borderRadius: '12px',\n fontSize: '1rem',\n background: theme.palette.gradient.primary,\n '&:hover': {\n boxShadow: '0 8px 16px rgba(0, 0, 0, 0.1)'\n }\n }),\n statsCard: theme => ({\n mt: 6,\n p: { xs: 2, md: 4 },\n borderRadius: '16px',\n boxShadow: theme.palette.mode === 'dark' ? '0 8px 24px rgba(0, 0, 0, 0.2)' : '0 8px 24px rgba(0, 0, 0, 0.05)',\n background: theme.palette.mode === 'dark' ? 'rgba(30, 30, 30, 0.6)' : 'rgba(255, 255, 255, 0.8)',\n backdropFilter: 'blur(8px)'\n }),\n projectCard: {\n height: '100%',\n display: 'flex',\n flexDirection: 'column',\n overflow: 'visible',\n position: 'relative'\n },\n projectAvatar: {\n position: 'absolute',\n top: -16,\n left: 24,\n zIndex: 1\n },\n projectDescription: {\n mb: 2,\n display: '-webkit-box',\n WebkitBoxOrient: 'vertical',\n WebkitLineClamp: 2,\n overflow: 'hidden',\n textOverflow: 'ellipsis',\n height: '40px'\n }\n};\n"], ["/easy-dataset/constant/setting.js", "// 默认项目任务配置\nexport const DEFAULT_SETTINGS = {\n textSplitMinLength: 1500,\n textSplitMaxLength: 2000,\n questionGenerationLength: 240,\n questionMaskRemovingProbability: 60,\n huggingfaceToken: '',\n concurrencyLimit: 5,\n visionConcurrencyLimit: 5\n};\n"], ["/easy-dataset/components/tasks/TaskProgress.js", "'use client';\n\nimport React from 'react';\nimport { Stack, LinearProgress, Typography } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\n\n// 任务进度组件\nexport default function TaskProgress({ task }) {\n const { t } = useTranslation();\n\n // 如果没有总数,则不显示进度条\n if (task.totalCount === 0) return '-';\n\n // 计算进度百分比\n const progress = (task.completedCount / task.totalCount) * 100;\n\n return (\n \n \n \n {task.completedCount} / {task.totalCount} ({Math.round(progress)}%)\n \n \n );\n}\n"], ["/easy-dataset/components/text-split/LoadingBackdrop.js", "'use client';\n\nimport { Backdrop, Paper, CircularProgress, Typography, Box, LinearProgress } from '@mui/material';\n\nexport default function LoadingBackdrop({ open, title, description, progress = null }) {\n return (\n theme.zIndex.drawer + 1,\n position: 'fixed',\n backdropFilter: 'blur(5px)',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center'\n }}\n open={open}\n >\n \n theme.palette.primary.main\n }}\n />\n\n \n {title}\n \n\n \n {description}\n \n\n {progress && progress.total > 0 && (\n \n \n \n {progress.completed}/{progress.total} ({progress.percentage}%)\n \n\n {progress.questionCount > 0 && (\n \n 已生成问题数: {progress.questionCount}\n \n )}\n \n\n \n \n )}\n \n \n );\n}\n"], ["/easy-dataset/styles/playground.js", "// 模型测试页面样式\nimport { alpha } from '@mui/material/styles';\n\nexport const playgroundStyles = theme => ({\n container: {\n p: 3,\n height: 'calc(100vh - 64px)',\n display: 'flex',\n flexDirection: 'column'\n },\n mainPaper: {\n p: 3,\n flex: 1,\n display: 'flex',\n flexDirection: 'column',\n mb: 2,\n borderRadius: 2\n },\n controlsContainer: {\n mb: 2\n },\n clearButton: {\n height: '56px'\n },\n divider: {\n mb: 2\n },\n emptyStateBox: {\n flex: 1,\n display: 'flex',\n justifyContent: 'center',\n alignItems: 'center',\n mb: 2,\n p: 2,\n bgcolor: theme.palette.mode === 'dark' ? 'rgba(255,255,255,0.03)' : 'rgba(0,0,0,0.02)',\n borderRadius: 1\n },\n chatContainer: {\n flex: 1,\n mb: 2\n },\n modelPaper: {\n height: '100%',\n display: 'flex',\n flexDirection: 'column',\n border: `1px solid ${theme.palette.divider}`,\n borderRadius: 1,\n overflow: 'hidden'\n },\n modelHeader: {\n p: 1,\n bgcolor: theme.palette.mode === 'dark' ? 'rgba(255,255,255,0.05)' : 'primary.light',\n color: theme.palette.mode === 'dark' ? 'white' : 'white',\n fontWeight: 'medium',\n textAlign: 'center',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center'\n },\n modelChatBox: {\n flex: 1,\n overflowY: 'auto',\n p: 2,\n bgcolor: theme.palette.mode === 'dark' ? 'rgba(255,255,255,0.03)' : 'rgba(0,0,0,0.02)'\n },\n emptyChatBox: {\n display: 'flex',\n justifyContent: 'center',\n alignItems: 'center',\n height: '100%'\n },\n inputContainer: {\n display: 'flex',\n gap: 1,\n mt: 2\n },\n sendButton: {\n minWidth: '120px',\n height: '56px',\n marginLeft: '20px'\n }\n});\n"], ["/easy-dataset/lib/llm/prompts/optimizeCotEn.js", "module.exports = function optimizeCotPrompt(originalQuestion, answer, originalCot) {\n return `\n# Role: Chain of Thought Optimization Expert\n## Profile:\n- Description: You are an expert in optimizing the chain of thought. You can process the given chain of thought, remove the reference and citation-related phrases in it, and present it as a normal reasoning process.\n\n## Skills:\n1. Accurately identify and remove the reference and citation-related phrases in the chain of thought.\n2. Ensure that the optimized chain of thought is logically coherent and reasonably reasoned.\n3. Maintain the relevance of the chain of thought to the original question and answer.\n\n## Workflow:\n1. Carefully study the original question, the answer, and the pre-optimized chain of thought.\n2. Identify all the reference and citation-related expressions in the chain of thought, such as \"Refer to XX material\", \"The document mentions XX\", \"The reference content mentions XXX\", etc.\n3. Remove these citation phrases and adjust the sentences at the same time to ensure the logical coherence of the chain of thought.\n4. Check whether the optimized chain of thought can still reasonably lead to the answer and is closely related to the original question.\n\n## Original Question\n${originalQuestion}\n\n## Answer\n${answer}\n\n## Pre-optimized Chain of Thought\n${originalCot}\n\n## Constrains:\n1. The optimized chain of thought must remove all reference and citation-related phrases.\n2. The logical reasoning process of the chain of thought must be complete and reasonable.\n3. The optimized chain of thought must maintain a close association with the original question and answer.\n4. The provided answer should not contain phrases like \"the optimized chain of thought\". Directly provide the result of the optimized chain of thought.\n5. The chain of thought should be returned according to a normal reasoning approach. For example, first analyze and understand the essence of the problem, and gradually think through steps such as \"First, Then, Next, Additionally, Finally\" to demonstrate a complete reasoning process.\n `;\n};\n"], ["/easy-dataset/lib/llm/prompts/pdfToMarkdown.js", "module.exports = function convertPrompt() {\n return `\n 使用markdown语法,将图片中识别到的文字转换为markdown格式输出。你必须做到:\n 1. 输出和使用识别到的图片的相同的语言,例如,识别到英语的字段,输出的内容必须是英语。\n 2. 不要解释和输出无关的文字,直接输出图片中的内容。\n 3. 内容不要包含在\\`\\`\\`markdown \\`\\`\\`中、段落公式使用 $$ $$ 的形式、行内公式使用 $ $ 的形式。\n 4. 忽略掉页眉页脚里的内容\n 5. 请不要对图片的标题进行markdown的格式化,直接以文本形式输出到内容中。\n 6. 有可能每页都会出现期刊名称,论文名称,会议名称或者书籍名称,请忽略他们不要识别成标题\n 7. 请精确分析当前PDF页面的文本结构和视觉布局,按以下要求处理:\n 1. 识别所有标题文本,并判断其层级(根据字体大小、加粗、位置等视觉特征)\n 2. 输出为带层级的Markdown格式,严格使用以下规则:\n - 一级标题:字体最大/顶部居中,前面加 # \n - 二级标题:字体较大/左对齐加粗,有可能是数字开头也有可能是罗马数组开头,前面加 ## \n - 三级标题:字体稍大/左对齐加粗,前面加 ### \n - 正文文本:直接转换为普通段落\n 3. 不确定层级的标题请标记[?]\n 4. 如果是中文文献,但是有英文标题和摘要可以省略不输出\n 示例输出:\n ## 4研究方法\n ### 4.1数据收集\n 本文采用问卷调查...\n `;\n};\n"], ["/easy-dataset/components/text-split/PdfSettings.js", "'use client';\n\nimport { Box, Select, MenuItem, Typography, FormControl, InputLabel } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\n\nexport default function PdfSettings({ pdfStrategy, setPdfStrategy, selectedViosnModel, setSelectedViosnModel }) {\n const { t } = useTranslation();\n\n return (\n \n \n {t('textSplit.pdfStrategy')}\n setPdfStrategy(e.target.value)}\n label={t('textSplit.pdfStrategy')}\n size=\"small\"\n >\n {t('textSplit.defaultStrategy')}\n {t('textSplit.visionStrategy')}\n \n \n\n {pdfStrategy === 'vision' && (\n \n {t('textSplit.visionModel')}\n setSelectedViosnModel(e.target.value)}\n label={t('textSplit.visionModel')}\n size=\"small\"\n >\n GPT-4 Vision\n Claude-3 Opus\n Claude-3 Sonnet\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