Spaces:
Running
Running
File size: 8,289 Bytes
6059028 2e740d5 6059028 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 | #!/usr/bin/env python3
"""make_sample_docx.py β build samples/sample_questions.docx, the Word template
SMEs download and type over.
The file holds ONLY the four line kinds the parser needs:
question -> options (unless numerical) -> answer -> solution
No headings, no title page, no "Question Type:"/"Difficulty Level:" lines β an SME
replaces the sample questions in place and uploads. Option markers may be a) b) c) d)
or 1) 2) 3) 4); both are shown, and either may be used throughout.
python make_sample_docx.py # -> samples/sample_questions.docx
python make_sample_docx.py --out x.docx
python make_sample_docx.py --check # regenerate, then parse it back
Format rules: samples/WORD_FORMAT.md.
"""
import argparse
import io
import sys
from pathlib import Path
from docx import Document
from docx.shared import Inches, Pt
from lxml import etree
HERE = Path(__file__).resolve().parent
M_NS = 'http://schemas.openxmlformats.org/officeDocument/2006/math'
# ββ Word equations (OMML), written the way Word's equation editor writes them ββ
def _r(text):
return f'<m:r><m:t>{text}</m:t></m:r>'
def _omath(inner):
return etree.fromstring(f'<m:oMath xmlns:m="{M_NS}">{inner}</m:oMath>')
def _sqrt(inner):
# degHide is what makes the converter emit <msqrt> rather than an empty <mroot>
return (f'<m:rad><m:radPr><m:degHide m:val="1"/></m:radPr><m:deg/>'
f'<m:e>{inner}</m:e></m:rad>')
def _frac(num, den):
return f'<m:f><m:num>{num}</m:num><m:den>{den}</m:den></m:f>'
def _sup(base, sup):
return f'<m:sSup><m:e>{base}</m:e><m:sup>{sup}</m:sup></m:sSup>'
EQ_SQRT_2GH = _sqrt(_r('2gh')) # β(2gh)
EQ_HALF_MV2 = f'{_frac(_r("1"), _r("2"))}{_r("m")}{_sup(_r("v"), _r("2"))}' # Β½mvΒ²
EQ_G_FORMULA = _frac(f'{_r("4")}{_sup(_r("π"), _r("2"))}{_r("L")}',
_sup(_r('T'), _r('2'))) # 4ΟΒ²L/TΒ²
def circuit_png():
"""A small, legible figure β stands in for diagrams SMEs paste from Word."""
from PIL import Image, ImageDraw
im = Image.new('RGB', (420, 200), 'white')
d = ImageDraw.Draw(im)
d.rectangle([30, 40, 390, 160], outline='black', width=3)
d.rectangle([150, 25, 270, 55], fill='white', outline='black', width=3)
d.text((186, 33), 'R = 4 ohm', fill='black')
d.line([30, 100, 8, 100], fill='black', width=3)
d.line([8, 85, 8, 115], fill='black', width=3)
d.line([20, 92, 20, 108], fill='black', width=5)
d.text((36, 105), '12 V', fill='black')
buf = io.BytesIO()
im.save(buf, 'PNG')
return buf.getvalue()
class Paper:
def __init__(self):
self.doc = Document()
style = self.doc.styles['Normal']
style.font.name = 'Calibri'
style.font.size = Pt(11)
def para(self, text=''):
return self.doc.add_paragraph(text)
def mixed(self, *parts):
"""A paragraph of interleaved text / ('math', omml) / ('img', bytes)."""
p = self.doc.add_paragraph()
for part in parts:
if isinstance(part, str):
p.add_run(part)
elif part[0] == 'math':
p._p.append(_omath(part[1]))
elif part[0] == 'img':
p.add_run().add_picture(io.BytesIO(part[1]), width=Inches(2.2))
return p
def gap(self):
self.doc.add_paragraph()
def save(self, path):
Path(path).parent.mkdir(parents=True, exist_ok=True)
self.doc.save(str(path))
def build(path):
d = Paper()
# The very first line must be a question β any other opening line would be
# parsed as one. So the file starts here, with no title and no headings.
# ββ Q1 β options lettered a) b) c) d), equation in the stem ββββββββββββββ
d.mixed('1. A body is released from rest at a height h. Its speed on reaching the '
'ground is v = ', ('math', EQ_SQRT_2GH),
'. Find the speed after falling 20 m. (Take g = 10 m/sΒ²)')
d.para('a) 10 m/s')
d.para('b) 20 m/s')
d.para('c) 30 m/s')
d.para('d) 40 m/s')
d.para('Answer: b')
d.mixed('Using v = ', ('math', EQ_SQRT_2GH), ' with h = 20 m and g = 10 m/sΒ², '
'v = square root of (2 Γ 10 Γ 20) = square root of 400 = 20 m/s.')
d.para('Hence option b is correct.')
d.gap()
# ββ Q2 β options numbered 1) 2) 3) 4) on one line, with a figure βββββββββ
d.para('2. For the circuit shown below, find the current through the resistor R.')
d.mixed(('img', circuit_png()))
d.para('1) 1 A 2) 2 A 3) 3 A 4) 4 A')
d.para('Answer: 3')
d.para("By Ohm's law, I = V / R = 12 / 4 = 3 A.")
d.para('Hence option 3 is correct.')
d.gap()
# ββ Q3 β numerical: NO options at all βββββββββββββββββββββββββββββββββββ
d.mixed('3. A simple pendulum of length L = 1 m has a time period of 2 s. '
'Using g = ', ('math', EQ_G_FORMULA), ', find g in m/sΒ².')
d.para('Answer: 9.87')
d.mixed('Substituting L = 1 m and T = 2 s into g = ', ('math', EQ_G_FORMULA),
' gives g = 4 Γ 9.8696 Γ 1 / 4.')
d.para('So g = 9.8696 β 9.87 m/sΒ².')
d.gap()
# ββ Q4 β numerical with an accepted band (hyphen form is the one that parses) ββ
d.para('4. A 2 kg block moving at 3 m/s is brought to rest by friction over 1.5 m. '
'Find the coefficient of friction. (g = 10 m/sΒ²)')
d.para('Answer: 0.28-0.32')
d.mixed('By the work-energy theorem ', ('math', EQ_HALF_MV2),
' = ΞΌmgs, so ΞΌ = vΒ² / (2gs).')
d.para('ΞΌ = 9 / (2 Γ 10 Γ 1.5) = 0.30, so any value from 0.28 to 0.32 is accepted.')
d.gap()
# ββ Q5 β options lettered (A) (B) (C) (D), equations as the options ββββββ
d.para('5. Which expression gives the kinetic energy of a body of mass m moving '
'with speed v?')
d.mixed('(A) ', ('math', _r('mgh')))
d.mixed('(B) ', ('math', EQ_HALF_MV2))
d.mixed('(C) ', ('math', EQ_SQRT_2GH))
d.mixed('(D) ', ('math', _r('mv')))
d.para('Answer: B')
d.mixed('Kinetic energy is ', ('math', EQ_HALF_MV2),
'. Option A is potential energy and the others are not energies at all.')
d.para('Hence option B is correct.')
d.save(path)
return path
def check(path):
"""Parse the generated file back and report what the uploader would show."""
sys.path.insert(0, str(HERE))
import app
qs = app.parse_word(str(path))
app.validate_questions(qs)
print(f'\nparsed {len(qs)} question(s) from {Path(path).name}')
warn = app.omml_support_warning()
if warn:
print(f'WARNING: {warn}')
ok = True
for i, q in enumerate(qs, 1):
opts = [q.get(f'option_{k}', '') for k in 'abcd']
filled = sum(1 for o in opts if app._option_filled(o))
maths = sum(o.count('<math') for o in opts) + q['question_text'].count('<math')
imgs = q['question_text'].count('<img')
band = f' band={q["answer_range"]}' if q.get('answer_range') else ''
print(f' Q{i}: type={app.normalise_qtype(q["question_type"]):<24} '
f'ans={q["correct_answer"]!r:<12} opts={filled} math={maths} img={imgs} '
f'sol={"yes" if q["solution"].strip() else "NO":<3} '
f'{q["confidence"]}{band}')
if q['issues']:
print(f' issues: {q["issues"]}')
if q['confidence'] != 'ok' or not q['solution'].strip():
ok = False
print('\nEvery question parsed cleanly with an answer and a solution.' if ok
else '\nSome questions did NOT parse cleanly β see above.')
return ok
def main():
ap = argparse.ArgumentParser(description='Build the Word sample paper')
ap.add_argument('--out', default=str(HERE.parent / 'samples' / 'sample_questions.docx'))
ap.add_argument('--check', action='store_true',
help='parse the generated file back and report')
args = ap.parse_args()
path = build(args.out)
print(f'wrote {path}')
if args.check and not check(path):
raise SystemExit(1)
if __name__ == '__main__':
main()
|