// Offline teaching fixture. Generate predictions from tickets alone, then score a separate file. import { readFileSync, writeFileSync } from 'node:fs'; const ids = Array.from({ length: 12 }, (_, i) => 'R' + String(i + 1).padStart(2, '0')); const queues = ['设备报修', '资料请求', '人工澄清']; function loadRows(path, fields) { const rows = JSON.parse(readFileSync(path, 'utf8').replace(/^\uFEFF/, '')); if (!Array.isArray(rows)) throw new Error(path + ' 需要 JSON 数组'); const byId = new Map(); for (const row of rows) { if (!row || typeof row !== 'object' || Array.isArray(row) || Object.keys(row).length !== fields.length || !fields.every(key => typeof row[key] === 'string' && row[key].trim())) { throw new Error(path + ' 行字段须为非空字符串:' + fields.join(', ')); } if (!ids.includes(row.id)) throw new Error(path + ' 多余 ID ' + row.id); if (byId.has(row.id)) throw new Error(path + ' 重复 ID ' + row.id); if (fields.includes('queue') && !queues.includes(row.queue)) { throw new Error(path + ' 非法队列 ' + row.id + ' ' + row.queue); } byId.set(row.id, row); } const absent = ids.filter(id => !byId.has(id)); if (absent.length) throw new Error(path + ' 缺失 ID ' + absent.join(', ')); return byId; } function guess(text) { if (/报修|派人|漏油|停机|开维修单/.test(text)) return '设备报修'; if (/手册|资料|巡检表|说明书/.test(text)) return '资料请求'; return '人工澄清'; } function saveNew(path, value) { writeFileSync(path, JSON.stringify(value, null, 2) + '\n', { flag: 'wx' }); } function main([mode, ...files]) { if (mode === 'example' && files.length === 2) { const tickets = loadRows(files[0], ['id', 'text']); saveNew(files[1], ids.map(id => ({ id, queue: guess(tickets.get(id).text) }))); console.log('已保存 12 条示范预测:' + files[1]); return; } if (mode !== 'score' || files.length !== 4) { throw new Error('用法:node triage.mjs example tickets.json predictions.json 或 node triage.mjs score tickets.json reference.json predictions.json report.json'); } const [inputs, labels, guesses, output] = files; const tickets = loadRows(inputs, ['id', 'text']); const reference = loadRows(labels, ['id', 'queue', 'reason']); const predictions = loadRows(guesses, ['id', 'queue']); const matrix = queues.map(() => queues.map(() => 0)); const mistakes = []; for (const id of ids) { const { queue: expected, reason } = reference.get(id); const predicted = predictions.get(id).queue; matrix[queues.indexOf(expected)][queues.indexOf(predicted)]++; if (expected !== predicted) { mistakes.push({ id, text: tickets.get(id).text, expected, predicted, reason }); } } const correct = ids.length - mistakes.length; saveNew(output, { total: ids.length, correct, rowsReference: queues, columnsPrediction: queues, matrix, mistakes, }); console.log('按参考队列分对 ' + correct + '/' + ids.length + ',逐条错例见 ' + output); } try { main(process.argv.slice(2)); } catch (error) { console.error(error.code === 'EEXIST' ? '输出文件已存在,请另取文件名' : error.message); process.exitCode = 1; }