| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338 |
- 'use strict'
- /**
- * 授课数据分析器
- * --------------
- * 输入:平台导出的「作业数据.xlsx」
- * 输出:结构化统计 JSON(stdout),供技能据此写报告。
- *
- * 设计原则:能算的都算准,算不准的**明确标成"无法判断"**,绝不用 0 冒充。
- * 每一条统计都带分母和口径,报告里直接引用。
- */
- const fs = require('node:fs')
- const { readXlsx } = require('./xlsx-read.js')
- const TYPE_H5 = 'h5网页'
- const TYPE_CHOICE = '选择题'
- const TYPE_QA = '问答题'
- const TYPE_APP = '应用中心'
- function tryJson (text) {
- const s = String(text || '').trim()
- if (!s.startsWith('{') && !s.startsWith('[')) return null
- try { return JSON.parse(s) } catch { return null }
- }
- /** "A,C" / "A、C" / "C,A" 统一成 "A,C";多选题答案是多字母,不能只取第一个 */
- function normAnswers (raw) {
- const letters = String(raw || '').toUpperCase().match(/[A-Z]/g)
- if (!letters) return null
- return [...new Set(letters)].sort().join(',')
- }
- function parseChoiceSheet (text) {
- const blocks = String(text || '')
- .split(/\n(?=\s*\d+\s*[..、])/)
- .map((b) => b.trim())
- .filter(Boolean)
- return blocks.map((block, idx) => {
- const lines = block.split('\n').map((l) => l.trim()).filter(Boolean)
- const stem = (lines[0] || '').replace(/^\d+\s*[..、]\s*/, '')
- const options = []
- let correct = null
- let student = null
- for (const line of lines.slice(1)) {
- const opt = line.match(/^([A-Z])\s*[..、]\s*(.+)$/)
- if (opt && correct === null && student === null) { options.push({ key: opt[1], text: opt[2].trim() }); continue }
- const c = line.match(/正确答案\s*[::]\s*([A-Z](?:\s*[,,、]\s*[A-Z])*)/)
- if (c) { correct = normAnswers(c[1]); continue }
- const s = line.match(/学生答案\s*[::]\s*([A-Z](?:\s*[,,、]\s*[A-Z])*)/)
- if (s) { student = normAnswers(s[1]); continue }
- }
- const answered = student !== null && student !== ''
- return {
- index: idx + 1,
- stem,
- options,
- correct,
- student,
- answered,
- isCorrect: answered && correct !== null ? student === correct : null,
- comparable: correct !== null && answered
- }
- })
- }
- function stripHtml (html) {
- return String(html || '')
- .replace(/<br\s*\/?>/gi, '\n')
- .replace(/<\/p>/gi, '\n')
- .replace(/<[^>]+>/g, '')
- .replace(/ /g, ' ')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/"/g, '"')
- .replace(/&/g, '&')
- .replace(/\n{2,}/g, '\n')
- .trim()
- }
- function normName (s) {
- return String(s || '').replace(/\s+/g, '').trim()
- }
- /** 班级成员:classid 可能是逗号分隔的多班 id,必须按元素匹配而不是按字符串相等 */
- function rosterSize (members, classId) {
- const list = Array.isArray(members) ? members : []
- if (!classId) return { total: list.length, matched: list.length, loose: true }
- const matched = list.filter((m) => String(m.classid || '').split(',').map((x) => x.trim()).includes(classId))
- return { total: list.length, matched: matched.length, loose: false }
- }
- function analyze (file, opts = {}) {
- const { sheets } = readXlsx(file)
- const dataSheet = sheets.find((s) => /作业数据/.test(s.name)) || sheets[0]
- const infoSheet = sheets.find((s) => /课程信息/.test(s.name))
- const rows = dataSheet.rows
- if (!rows.length) throw new Error('作业数据工作表是空的')
- const header = rows[0].map((h) => String(h || '').trim())
- const col = (name) => header.findIndex((h) => h.includes(name))
- const iName = col('学生姓名')
- const iClass = col('学生班级')
- const iCourse = col('所属课程')
- const iPage = col('页码')
- const iType = col('题型')
- const iContent = col('作业内容')
- const iTime = col('提交时间')
- for (const [label, idx] of [['学生姓名', iName], ['题型', iType], ['作业内容', iContent], ['提交时间', iTime]]) {
- if (idx < 0) throw new Error(`表头里找不到「${label}」列,这份导出可能结构变了`)
- }
- const records = rows.slice(1)
- .filter((r) => r.some((c) => String(c).trim() !== ''))
- .map((r) => ({
- student: String(r[iName] || '').trim(),
- className: String(r[iClass] || '').trim(),
- course: String(r[iCourse] || '').trim(),
- page: Number(String(r[iPage] || '').trim()) || null,
- type: String(r[iType] || '').trim(),
- content: String(r[iContent] || ''),
- time: String(r[iTime] || '').trim()
- }))
- .filter((r) => r.student)
- const students = [...new Set(records.map((r) => r.student))]
- const classes = [...new Set(records.map((r) => r.className).filter(Boolean))]
- const courses = [...new Set(records.map((r) => r.course).filter(Boolean))]
- const byType = {}
- for (const r of records) byType[r.type] = (byType[r.type] || 0) + 1
- // ---------- 选择题 ----------
- const choiceStudents = records.filter((r) => r.type === TYPE_CHOICE)
- const perQuestion = new Map()
- for (const r of choiceStudents) {
- for (const q of parseChoiceSheet(r.content)) {
- if (!perQuestion.has(q.stem)) {
- perQuestion.set(q.stem, { stem: q.stem, options: q.options, correct: q.correct, total: 0, answered: 0, correctCount: 0, choices: {} })
- }
- const agg = perQuestion.get(q.stem)
- agg.total += 1
- if (q.answered) {
- agg.answered += 1
- agg.choices[q.student] = (agg.choices[q.student] || 0) + 1
- if (q.correct !== null && q.student === q.correct) agg.correctCount += 1
- }
- }
- }
- const choiceQuestions = [...perQuestion.values()].map((q) => ({
- stem: q.stem,
- options: q.options,
- correct: q.correct,
- submitted: q.total,
- answered: q.answered,
- correctCount: q.correctCount,
- correctRate: q.correct !== null && q.answered ? +(q.correctCount / q.answered).toFixed(4) : null,
- choices: q.choices,
- mostWrongOption: Object.entries(q.choices)
- .filter(([k]) => k !== q.correct)
- .sort((a, b) => b[1] - a[1])[0]?.[0] || null
- }))
- const choiceAnswerable = choiceQuestions.filter((q) => q.correct !== null).length
- // ---------- 问答题 ----------
- const qaRows = records.filter((r) => r.type === TYPE_QA)
- const qaByQuestion = new Map()
- for (const r of qaRows) {
- const j = tryJson(r.content)
- const question = j && j.answerQ ? stripHtml(j.answerQ) : '(题干未能解析)'
- const answer = j && j.answer ? stripHtml(j.answer) : stripHtml(r.content)
- if (!qaByQuestion.has(question)) qaByQuestion.set(question, { question, answers: [] })
- qaByQuestion.get(question).answers.push({
- student: r.student,
- answer,
- length: answer.replace(/\s/g, '').length,
- empty: answer.trim() === ''
- })
- }
- const qaQuestions = [...qaByQuestion.values()].map((q) => ({
- question: q.question,
- answered: q.answers.filter((a) => !a.empty).length,
- submitted: q.answers.length,
- avgLength: q.answers.length ? Math.round(q.answers.reduce((s, a) => s + a.length, 0) / q.answers.length) : 0,
- answers: q.answers
- }))
- // ---------- H5 / 应用中心 ----------
- const h5 = records.filter((r) => r.type === TYPE_H5)
- const app = records.filter((r) => r.type === TYPE_APP)
- const pageCount = {}
- for (const r of records) if (r.page !== null) pageCount[r.page] = (pageCount[r.page] || 0) + 1
- // ---------- 课程信息 ----------
- let courseTitle = courses[0] || ''
- let courseContent = ''
- if (infoSheet) {
- const kv = Object.fromEntries(infoSheet.rows.map((r) => [String(r[0] || '').trim(), String(r[1] || '')]))
- if (kv['课程标题']) courseTitle = kv['课程标题']
- courseContent = kv['课程内容'] || ''
- }
- const pageOutline = {}
- for (const m of courseContent.matchAll(/第(\d+)页的内容[::]\s*([^\n]*)/g)) {
- pageOutline[Number(m[1])] = m[2].trim()
- }
- // ---------- 参与度 ----------
- // 分母来源优先级:--class-size 显式传入 > --roster-json 名单文件 > 无法计算
- let classSize = Number(opts.classSize) || null
- let rosterNote = ''
- if (!classSize && opts.rosterFile) {
- try {
- const roster = JSON.parse(fs.readFileSync(opts.rosterFile, 'utf8'))
- const members = Array.isArray(roster) ? roster : (roster.members || [])
- const r = rosterSize(members, roster.classId || opts.classId)
- if (r.matched > 0) {
- classSize = r.matched
- rosterNote = r.loose ? `名单文件里共 ${r.total} 人(未指定班级)` : `名单里属于该班的 ${r.matched} 人(名单总共 ${r.total} 人)`
- }
- } catch { /* 名单文件坏了就当没给 */ }
- }
- const participation = {
- exportingStudents: students.length,
- classSize,
- absentStudents: classSize ? Math.max(0, classSize - students.length) : null,
- participationRate: classSize ? +(students.length / classSize).toFixed(4) : null,
- submittedNames: students,
- absentNames: null,
- source: classSize ? (rosterNote || '老师提供的班级人数') : '',
- note: classSize
- ? `按班级 ${classSize} 人计算`
- : '导出表和名单都没有给到班级总人数;参与率、未提交人数无法计算,不能写"只有 N 人参与"'
- }
- // 有名单成员对象时才敢列"谁没交"——导出里的姓名和名单姓名要做规范化比对
- const rosterMembers = opts.rosterFile
- ? (() => {
- try {
- const roster = JSON.parse(fs.readFileSync(opts.rosterFile, 'utf8'))
- return Array.isArray(roster) ? roster : (roster.members || [])
- } catch { return null }
- })()
- : null
- if (rosterMembers && classSize) {
- const classId = opts.classId
- const inClass = classId
- ? rosterMembers.filter((m) => String(m.classid || '').split(',').map((x) => x.trim()).includes(classId))
- : rosterMembers
- const submittedSet = new Set(students.map(normName))
- participation.absentNames = inClass
- .map((m) => String(m.name || m.username || ''))
- .filter((n) => n && !submittedSet.has(normName(n)))
- }
- const perStudent = students.map((name) => {
- const mine = records.filter((r) => r.student === name)
- const choice = mine.filter((r) => r.type === TYPE_CHOICE).flatMap((r) => parseChoiceSheet(r.content))
- const comparable = choice.filter((q) => q.comparable)
- return {
- student: name,
- submissions: mine.length,
- types: [...new Set(mine.map((r) => r.type))],
- pages: [...new Set(mine.map((r) => r.page).filter((p) => p !== null))].sort((a, b) => a - b),
- firstAt: mine.map((r) => r.time).sort()[0] || '',
- lastAt: mine.map((r) => r.time).sort().slice(-1)[0] || '',
- choiceAnswered: comparable.length,
- choiceCorrect: comparable.filter((q) => q.isCorrect).length,
- hasChoice: comparable.length > 0,
- hasQA: mine.some((r) => r.type === TYPE_QA),
- hasH5: mine.some((r) => r.type === TYPE_H5),
- hasApp: mine.some((r) => r.type === TYPE_APP)
- }
- })
- return {
- file,
- generatedFor: opts.label || '',
- course: { title: courseTitle, classes, pages: Object.keys(pageOutline).length || null, pageOutline },
- scope: {
- records: records.length,
- students: students.length,
- students_list: students,
- dateRange: [records.map((r) => r.time).sort()[0] || '', records.map((r) => r.time).sort().slice(-1)[0] || ''],
- typeCounts: byType
- },
- participation,
- choice: {
- studentsWithChoice: choiceStudents.length,
- distinctQuestions: choiceQuestions.length,
- questions: choiceQuestions,
- note: choiceAnswerable ? '' : '所有选择题都没有解析出标准答案,不能算正确率'
- },
- shortAnswer: { questions: qaQuestions },
- h5: { submissions: h5.length, students: [...new Set(h5.map((r) => r.student))] },
- appWorks: { submissions: app.length, students: [...new Set(app.map((r) => r.student))] },
- pageActivities: pageCount,
- perStudent,
- limitations: [
- '导出表只含提交记录:没有班级名单就算不出未提交名单,名单要从平台班级成员接口另取',
- 'H5 和应用中心只给链接,内容是图片/JSON 附件,本次分析未读取其内容',
- '问答题没有标准答案,只能描述作答情况,不能判对错',
- '一条记录 = 一次提交;同一学生可能对同一页多次提交',
- '平台看板上 AI 生成的"参与率"文字不可直接引用,分母口径需自己核对'
- ]
- }
- }
- module.exports = { analyze, parseChoiceSheet, stripHtml, normName, rosterSize }
- if (require.main === module) {
- const args = process.argv.slice(2)
- const file = args.find((a) => !a.startsWith('--'))
- const getOpt = (k) => {
- const i = args.indexOf(k)
- return i >= 0 ? args[i + 1] : undefined
- }
- if (!file) {
- console.error('用法:node scripts/analyze-export.js <作业数据.xlsx> [--class-size 40] [--roster-json members.json --class-id <班级id>] [--label 六年级1班]')
- process.exit(2)
- }
- if (!fs.existsSync(file)) {
- console.error(`找不到文件:${file}`)
- process.exit(2)
- }
- try {
- const result = analyze(file, {
- classSize: getOpt('--class-size'),
- rosterFile: getOpt('--roster-json'),
- classId: getOpt('--class-id'),
- label: getOpt('--label')
- })
- process.stdout.write(JSON.stringify(result, null, 2))
- } catch (err) {
- console.error(`解析失败:${err.message}`)
- process.exit(1)
- }
- }
|