analyze-export.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. 'use strict'
  2. /**
  3. * 授课数据分析器
  4. * --------------
  5. * 输入:平台导出的「作业数据.xlsx」
  6. * 输出:结构化统计 JSON(stdout),供技能据此写报告。
  7. *
  8. * 设计原则:能算的都算准,算不准的**明确标成"无法判断"**,绝不用 0 冒充。
  9. * 每一条统计都带分母和口径,报告里直接引用。
  10. */
  11. const fs = require('node:fs')
  12. const { readXlsx } = require('./xlsx-read.js')
  13. const TYPE_H5 = 'h5网页'
  14. const TYPE_CHOICE = '选择题'
  15. const TYPE_QA = '问答题'
  16. const TYPE_APP = '应用中心'
  17. function tryJson (text) {
  18. const s = String(text || '').trim()
  19. if (!s.startsWith('{') && !s.startsWith('[')) return null
  20. try { return JSON.parse(s) } catch { return null }
  21. }
  22. /** "A,C" / "A、C" / "C,A" 统一成 "A,C";多选题答案是多字母,不能只取第一个 */
  23. function normAnswers (raw) {
  24. const letters = String(raw || '').toUpperCase().match(/[A-Z]/g)
  25. if (!letters) return null
  26. return [...new Set(letters)].sort().join(',')
  27. }
  28. function parseChoiceSheet (text) {
  29. const blocks = String(text || '')
  30. .split(/\n(?=\s*\d+\s*[..、])/)
  31. .map((b) => b.trim())
  32. .filter(Boolean)
  33. return blocks.map((block, idx) => {
  34. const lines = block.split('\n').map((l) => l.trim()).filter(Boolean)
  35. const stem = (lines[0] || '').replace(/^\d+\s*[..、]\s*/, '')
  36. const options = []
  37. let correct = null
  38. let student = null
  39. for (const line of lines.slice(1)) {
  40. const opt = line.match(/^([A-Z])\s*[..、]\s*(.+)$/)
  41. if (opt && correct === null && student === null) { options.push({ key: opt[1], text: opt[2].trim() }); continue }
  42. const c = line.match(/正确答案\s*[::]\s*([A-Z](?:\s*[,,、]\s*[A-Z])*)/)
  43. if (c) { correct = normAnswers(c[1]); continue }
  44. const s = line.match(/学生答案\s*[::]\s*([A-Z](?:\s*[,,、]\s*[A-Z])*)/)
  45. if (s) { student = normAnswers(s[1]); continue }
  46. }
  47. const answered = student !== null && student !== ''
  48. return {
  49. index: idx + 1,
  50. stem,
  51. options,
  52. correct,
  53. student,
  54. answered,
  55. isCorrect: answered && correct !== null ? student === correct : null,
  56. comparable: correct !== null && answered
  57. }
  58. })
  59. }
  60. function stripHtml (html) {
  61. return String(html || '')
  62. .replace(/<br\s*\/?>/gi, '\n')
  63. .replace(/<\/p>/gi, '\n')
  64. .replace(/<[^>]+>/g, '')
  65. .replace(/&nbsp;/g, ' ')
  66. .replace(/&lt;/g, '<')
  67. .replace(/&gt;/g, '>')
  68. .replace(/&quot;/g, '"')
  69. .replace(/&amp;/g, '&')
  70. .replace(/\n{2,}/g, '\n')
  71. .trim()
  72. }
  73. function normName (s) {
  74. return String(s || '').replace(/\s+/g, '').trim()
  75. }
  76. /** 班级成员:classid 可能是逗号分隔的多班 id,必须按元素匹配而不是按字符串相等 */
  77. function rosterSize (members, classId) {
  78. const list = Array.isArray(members) ? members : []
  79. if (!classId) return { total: list.length, matched: list.length, loose: true }
  80. const matched = list.filter((m) => String(m.classid || '').split(',').map((x) => x.trim()).includes(classId))
  81. return { total: list.length, matched: matched.length, loose: false }
  82. }
  83. function analyze (file, opts = {}) {
  84. const { sheets } = readXlsx(file)
  85. const dataSheet = sheets.find((s) => /作业数据/.test(s.name)) || sheets[0]
  86. const infoSheet = sheets.find((s) => /课程信息/.test(s.name))
  87. const rows = dataSheet.rows
  88. if (!rows.length) throw new Error('作业数据工作表是空的')
  89. const header = rows[0].map((h) => String(h || '').trim())
  90. const col = (name) => header.findIndex((h) => h.includes(name))
  91. const iName = col('学生姓名')
  92. const iClass = col('学生班级')
  93. const iCourse = col('所属课程')
  94. const iPage = col('页码')
  95. const iType = col('题型')
  96. const iContent = col('作业内容')
  97. const iTime = col('提交时间')
  98. for (const [label, idx] of [['学生姓名', iName], ['题型', iType], ['作业内容', iContent], ['提交时间', iTime]]) {
  99. if (idx < 0) throw new Error(`表头里找不到「${label}」列,这份导出可能结构变了`)
  100. }
  101. const records = rows.slice(1)
  102. .filter((r) => r.some((c) => String(c).trim() !== ''))
  103. .map((r) => ({
  104. student: String(r[iName] || '').trim(),
  105. className: String(r[iClass] || '').trim(),
  106. course: String(r[iCourse] || '').trim(),
  107. page: Number(String(r[iPage] || '').trim()) || null,
  108. type: String(r[iType] || '').trim(),
  109. content: String(r[iContent] || ''),
  110. time: String(r[iTime] || '').trim()
  111. }))
  112. .filter((r) => r.student)
  113. const students = [...new Set(records.map((r) => r.student))]
  114. const classes = [...new Set(records.map((r) => r.className).filter(Boolean))]
  115. const courses = [...new Set(records.map((r) => r.course).filter(Boolean))]
  116. const byType = {}
  117. for (const r of records) byType[r.type] = (byType[r.type] || 0) + 1
  118. // ---------- 选择题 ----------
  119. const choiceStudents = records.filter((r) => r.type === TYPE_CHOICE)
  120. const perQuestion = new Map()
  121. for (const r of choiceStudents) {
  122. for (const q of parseChoiceSheet(r.content)) {
  123. if (!perQuestion.has(q.stem)) {
  124. perQuestion.set(q.stem, { stem: q.stem, options: q.options, correct: q.correct, total: 0, answered: 0, correctCount: 0, choices: {} })
  125. }
  126. const agg = perQuestion.get(q.stem)
  127. agg.total += 1
  128. if (q.answered) {
  129. agg.answered += 1
  130. agg.choices[q.student] = (agg.choices[q.student] || 0) + 1
  131. if (q.correct !== null && q.student === q.correct) agg.correctCount += 1
  132. }
  133. }
  134. }
  135. const choiceQuestions = [...perQuestion.values()].map((q) => ({
  136. stem: q.stem,
  137. options: q.options,
  138. correct: q.correct,
  139. submitted: q.total,
  140. answered: q.answered,
  141. correctCount: q.correctCount,
  142. correctRate: q.correct !== null && q.answered ? +(q.correctCount / q.answered).toFixed(4) : null,
  143. choices: q.choices,
  144. mostWrongOption: Object.entries(q.choices)
  145. .filter(([k]) => k !== q.correct)
  146. .sort((a, b) => b[1] - a[1])[0]?.[0] || null
  147. }))
  148. const choiceAnswerable = choiceQuestions.filter((q) => q.correct !== null).length
  149. // ---------- 问答题 ----------
  150. const qaRows = records.filter((r) => r.type === TYPE_QA)
  151. const qaByQuestion = new Map()
  152. for (const r of qaRows) {
  153. const j = tryJson(r.content)
  154. const question = j && j.answerQ ? stripHtml(j.answerQ) : '(题干未能解析)'
  155. const answer = j && j.answer ? stripHtml(j.answer) : stripHtml(r.content)
  156. if (!qaByQuestion.has(question)) qaByQuestion.set(question, { question, answers: [] })
  157. qaByQuestion.get(question).answers.push({
  158. student: r.student,
  159. answer,
  160. length: answer.replace(/\s/g, '').length,
  161. empty: answer.trim() === ''
  162. })
  163. }
  164. const qaQuestions = [...qaByQuestion.values()].map((q) => ({
  165. question: q.question,
  166. answered: q.answers.filter((a) => !a.empty).length,
  167. submitted: q.answers.length,
  168. avgLength: q.answers.length ? Math.round(q.answers.reduce((s, a) => s + a.length, 0) / q.answers.length) : 0,
  169. answers: q.answers
  170. }))
  171. // ---------- H5 / 应用中心 ----------
  172. const h5 = records.filter((r) => r.type === TYPE_H5)
  173. const app = records.filter((r) => r.type === TYPE_APP)
  174. const pageCount = {}
  175. for (const r of records) if (r.page !== null) pageCount[r.page] = (pageCount[r.page] || 0) + 1
  176. // ---------- 课程信息 ----------
  177. let courseTitle = courses[0] || ''
  178. let courseContent = ''
  179. if (infoSheet) {
  180. const kv = Object.fromEntries(infoSheet.rows.map((r) => [String(r[0] || '').trim(), String(r[1] || '')]))
  181. if (kv['课程标题']) courseTitle = kv['课程标题']
  182. courseContent = kv['课程内容'] || ''
  183. }
  184. const pageOutline = {}
  185. for (const m of courseContent.matchAll(/第(\d+)页的内容[::]\s*([^\n]*)/g)) {
  186. pageOutline[Number(m[1])] = m[2].trim()
  187. }
  188. // ---------- 参与度 ----------
  189. // 分母来源优先级:--class-size 显式传入 > --roster-json 名单文件 > 无法计算
  190. let classSize = Number(opts.classSize) || null
  191. let rosterNote = ''
  192. if (!classSize && opts.rosterFile) {
  193. try {
  194. const roster = JSON.parse(fs.readFileSync(opts.rosterFile, 'utf8'))
  195. const members = Array.isArray(roster) ? roster : (roster.members || [])
  196. const r = rosterSize(members, roster.classId || opts.classId)
  197. if (r.matched > 0) {
  198. classSize = r.matched
  199. rosterNote = r.loose ? `名单文件里共 ${r.total} 人(未指定班级)` : `名单里属于该班的 ${r.matched} 人(名单总共 ${r.total} 人)`
  200. }
  201. } catch { /* 名单文件坏了就当没给 */ }
  202. }
  203. const participation = {
  204. exportingStudents: students.length,
  205. classSize,
  206. absentStudents: classSize ? Math.max(0, classSize - students.length) : null,
  207. participationRate: classSize ? +(students.length / classSize).toFixed(4) : null,
  208. submittedNames: students,
  209. absentNames: null,
  210. source: classSize ? (rosterNote || '老师提供的班级人数') : '',
  211. note: classSize
  212. ? `按班级 ${classSize} 人计算`
  213. : '导出表和名单都没有给到班级总人数;参与率、未提交人数无法计算,不能写"只有 N 人参与"'
  214. }
  215. // 有名单成员对象时才敢列"谁没交"——导出里的姓名和名单姓名要做规范化比对
  216. const rosterMembers = opts.rosterFile
  217. ? (() => {
  218. try {
  219. const roster = JSON.parse(fs.readFileSync(opts.rosterFile, 'utf8'))
  220. return Array.isArray(roster) ? roster : (roster.members || [])
  221. } catch { return null }
  222. })()
  223. : null
  224. if (rosterMembers && classSize) {
  225. const classId = opts.classId
  226. const inClass = classId
  227. ? rosterMembers.filter((m) => String(m.classid || '').split(',').map((x) => x.trim()).includes(classId))
  228. : rosterMembers
  229. const submittedSet = new Set(students.map(normName))
  230. participation.absentNames = inClass
  231. .map((m) => String(m.name || m.username || ''))
  232. .filter((n) => n && !submittedSet.has(normName(n)))
  233. }
  234. const perStudent = students.map((name) => {
  235. const mine = records.filter((r) => r.student === name)
  236. const choice = mine.filter((r) => r.type === TYPE_CHOICE).flatMap((r) => parseChoiceSheet(r.content))
  237. const comparable = choice.filter((q) => q.comparable)
  238. return {
  239. student: name,
  240. submissions: mine.length,
  241. types: [...new Set(mine.map((r) => r.type))],
  242. pages: [...new Set(mine.map((r) => r.page).filter((p) => p !== null))].sort((a, b) => a - b),
  243. firstAt: mine.map((r) => r.time).sort()[0] || '',
  244. lastAt: mine.map((r) => r.time).sort().slice(-1)[0] || '',
  245. choiceAnswered: comparable.length,
  246. choiceCorrect: comparable.filter((q) => q.isCorrect).length,
  247. hasChoice: comparable.length > 0,
  248. hasQA: mine.some((r) => r.type === TYPE_QA),
  249. hasH5: mine.some((r) => r.type === TYPE_H5),
  250. hasApp: mine.some((r) => r.type === TYPE_APP)
  251. }
  252. })
  253. return {
  254. file,
  255. generatedFor: opts.label || '',
  256. course: { title: courseTitle, classes, pages: Object.keys(pageOutline).length || null, pageOutline },
  257. scope: {
  258. records: records.length,
  259. students: students.length,
  260. students_list: students,
  261. dateRange: [records.map((r) => r.time).sort()[0] || '', records.map((r) => r.time).sort().slice(-1)[0] || ''],
  262. typeCounts: byType
  263. },
  264. participation,
  265. choice: {
  266. studentsWithChoice: choiceStudents.length,
  267. distinctQuestions: choiceQuestions.length,
  268. questions: choiceQuestions,
  269. note: choiceAnswerable ? '' : '所有选择题都没有解析出标准答案,不能算正确率'
  270. },
  271. shortAnswer: { questions: qaQuestions },
  272. h5: { submissions: h5.length, students: [...new Set(h5.map((r) => r.student))] },
  273. appWorks: { submissions: app.length, students: [...new Set(app.map((r) => r.student))] },
  274. pageActivities: pageCount,
  275. perStudent,
  276. limitations: [
  277. '导出表只含提交记录:没有班级名单就算不出未提交名单,名单要从平台班级成员接口另取',
  278. 'H5 和应用中心只给链接,内容是图片/JSON 附件,本次分析未读取其内容',
  279. '问答题没有标准答案,只能描述作答情况,不能判对错',
  280. '一条记录 = 一次提交;同一学生可能对同一页多次提交',
  281. '平台看板上 AI 生成的"参与率"文字不可直接引用,分母口径需自己核对'
  282. ]
  283. }
  284. }
  285. module.exports = { analyze, parseChoiceSheet, stripHtml, normName, rosterSize }
  286. if (require.main === module) {
  287. const args = process.argv.slice(2)
  288. const file = args.find((a) => !a.startsWith('--'))
  289. const getOpt = (k) => {
  290. const i = args.indexOf(k)
  291. return i >= 0 ? args[i + 1] : undefined
  292. }
  293. if (!file) {
  294. console.error('用法:node scripts/analyze-export.js <作业数据.xlsx> [--class-size 40] [--roster-json members.json --class-id <班级id>] [--label 六年级1班]')
  295. process.exit(2)
  296. }
  297. if (!fs.existsSync(file)) {
  298. console.error(`找不到文件:${file}`)
  299. process.exit(2)
  300. }
  301. try {
  302. const result = analyze(file, {
  303. classSize: getOpt('--class-size'),
  304. rosterFile: getOpt('--roster-json'),
  305. classId: getOpt('--class-id'),
  306. label: getOpt('--label')
  307. })
  308. process.stdout.write(JSON.stringify(result, null, 2))
  309. } catch (err) {
  310. console.error(`解析失败:${err.message}`)
  311. process.exit(1)
  312. }
  313. }