Spaces:
Running
Running
Sahil Kumar
Claude Opus 5
deploy: split the tree into backend/frontend/database and centralise hosts
2e740d5 Download backend/make_sample_docx.py from sahil-12kumar/IL_CMS_Tools: direct link, hf CLI and curl.
- Browser
- Download file 8.29 kB
-
https://huggingface.co/spaces/sahil-12kumar/IL_CMS_Tools/resolve/main/backend/make_sample_docx.py
- Command line
-
hf download hf://spaces/sahil-12kumar/IL_CMS_Tools/backend/make_sample_docx.py
-
curl -L -o make_sample_docx.py https://huggingface.co/spaces/sahil-12kumar/IL_CMS_Tools/resolve/main/backend/make_sample_docx.py
8.29 kB
| #!/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() | |