#!/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'{text}'
def _omath(inner):
return etree.fromstring(f'{inner}')
def _sqrt(inner):
# degHide is what makes the converter emit rather than an empty
return (f''
f'{inner}')
def _frac(num, den):
return f'{num}{den}'
def _sup(base, sup):
return f'{base}{sup}'
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('