Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import re
- start = 111705
- ans = {
- 'Q01': 'C', 'Q02': 'B', 'Q03': 'A', 'Q04': 'A', 'Q05': 'B',
- 'Q06': 'A', 'Q07': 'A', 'Q08': 'A', 'Q09': 'C', 'Q10': 'A',
- 'Q11': 'B', 'Q12': 'A', 'Q13': 'A', 'Q14': 'D', 'Q15': 'A',
- 'Q16': 'B', 'Q17': 'C', 'Q18': 'A', 'Q19': 'C', 'Q20': 'A',
- 'Q21': 'B', 'Q22': 'B', 'Q23': 'A', 'Q24': 'B', 'Q25': 'C'
- }
- IN_XML_WITH_B64 = "input_with_base64.xml" # <-- your existing XML that contains base64 blocks
- OUT_XML = "moodle_questions.xml"
- FILENAME_PREFIX = "microtk_jan-apr_q2_2025_" # <-- will generate _001.png ... _025.png
- EXT = ".png"
- # Extract base64 blocks from any <file ... encoding="base64"> ... </file>
- # (Works even if name/path differ, as long as encoding="base64" is present.)
- file_b64_pattern = re.compile(
- r'<file\b[^>]*\bencoding="base64"[^>]*>(.*?)</file>',
- re.IGNORECASE | re.DOTALL
- )
- def extract_base64_list(xml_text: str) -> list[str]:
- blocks = file_b64_pattern.findall(xml_text)
- # Normalize whitespace; base64 should be a continuous string
- cleaned = ["".join(b.split()) for b in blocks]
- # Remove empties
- cleaned = [b for b in cleaned if b]
- return cleaned
- def answer_block(letter: str, correct_letter: str) -> str:
- frac = "100" if letter == correct_letter else "-25"
- return f''' <answer fraction="{frac}" format="html">
- <text><![CDATA[<p>Option {letter}</p>]]></text>
- <feedback format="html">
- <text></text>
- </feedback>
- </answer>'''
- QUESTION_TEMPLATE = """<!-- question: {qid} -->
- <question type="multichoice">
- <name>
- <text>{qname}</text>
- </name>
- <questiontext format="html">
- <text><![CDATA[<p><img src="@@PLUGINFILE@@/{fname}"></p>]]></text>
- <file name="{fname}" path="/" encoding="base64">{b64}</file>
- </questiontext>
- <generalfeedback format="html">
- <text></text>
- </generalfeedback>
- <defaultgrade>1.0000000</defaultgrade>
- <penalty>0.0000000</penalty>
- <hidden>0</hidden>
- <idnumber></idnumber>
- <single>true</single>
- <shuffleanswers>false</shuffleanswers>
- <answernumbering>ABCD</answernumbering>
- <showstandardinstruction>0</showstandardinstruction>
- <correctfeedback format="html">
- <text><![CDATA[<p>Your answer is correct.</p>]]></text>
- </correctfeedback>
- <incorrectfeedback format="html">
- <text><![CDATA[<p>Your answer is incorrect.</p>]]></text>
- </incorrectfeedback>
- <shownumcorrect/>
- {answers}
- </question>
- """
- def main():
- with open(IN_XML_WITH_B64, "r", encoding="utf-8") as f:
- src_xml = f.read()
- b64_list = extract_base64_list(src_xml)
- if len(b64_list) < 25:
- raise SystemExit(f"Found only {len(b64_list)} base64 <file> blocks. Need at least 25.")
- if len(b64_list) > 25:
- # If your file has more than 25, we’ll use the first 25 by default.
- b64_list = b64_list[:25]
- xml_parts = ['<?xml version="1.0" encoding="UTF-8"?>\n<quiz>\n\n']
- qid = start
- for i in range(1, 26):
- qname = f"Q{i:02d}"
- correct = ans[qname].upper()
- if correct not in ("A", "B", "C", "D"):
- raise SystemExit(f"Invalid correct option for {qname}: {correct}")
- fname = f"{FILENAME_PREFIX}{i:03d}{EXT}"
- b64 = b64_list[i - 1]
- answers = "\n".join([
- answer_block("A", correct),
- answer_block("B", correct),
- answer_block("C", correct),
- answer_block("D", correct),
- ])
- xml_parts.append(QUESTION_TEMPLATE.format(
- qid=qid, qname=qname, fname=fname, b64=b64, answers=answers
- ))
- xml_parts.append("\n\n")
- qid += 1
- xml_parts.append("</quiz>\n")
- with open(OUT_XML, "w", encoding="utf-8") as f:
- f.write("".join(xml_parts))
- print(f" Wrote {OUT_XML} using 25 base64 blocks from {IN_XML_WITH_B64}")
- if __name__ == "__main__":
- main()
Add Comment
Please, Sign In to add comment