mayankjoin3

m2 no filename

Feb 24th, 2026
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.91 KB | None | 0 0
  1. import re
  2.  
  3. start = 111705
  4.  
  5. ans = {
  6.     'Q01': 'C', 'Q02': 'B', 'Q03': 'A', 'Q04': 'A', 'Q05': 'B',
  7.     'Q06': 'A', 'Q07': 'A', 'Q08': 'A', 'Q09': 'C', 'Q10': 'A',
  8.     'Q11': 'B', 'Q12': 'A', 'Q13': 'A', 'Q14': 'D', 'Q15': 'A',
  9.     'Q16': 'B', 'Q17': 'C', 'Q18': 'A', 'Q19': 'C', 'Q20': 'A',
  10.     'Q21': 'B', 'Q22': 'B', 'Q23': 'A', 'Q24': 'B', 'Q25': 'C'
  11. }
  12.  
  13. IN_XML_WITH_B64 = "input_with_base64.xml"   # <-- your existing XML that contains base64 blocks
  14. OUT_XML = "moodle_questions.xml"
  15.  
  16. FILENAME_PREFIX = "microtk_jan-apr_q2_2025_"  # <-- will generate _001.png ... _025.png
  17. EXT = ".png"
  18.  
  19. # Extract base64 blocks from any <file ... encoding="base64"> ... </file>
  20. # (Works even if name/path differ, as long as encoding="base64" is present.)
  21. file_b64_pattern = re.compile(
  22.     r'<file\b[^>]*\bencoding="base64"[^>]*>(.*?)</file>',
  23.     re.IGNORECASE | re.DOTALL
  24. )
  25.  
  26. def extract_base64_list(xml_text: str) -> list[str]:
  27.     blocks = file_b64_pattern.findall(xml_text)
  28.     # Normalize whitespace; base64 should be a continuous string
  29.     cleaned = ["".join(b.split()) for b in blocks]
  30.     # Remove empties
  31.     cleaned = [b for b in cleaned if b]
  32.     return cleaned
  33.  
  34. def answer_block(letter: str, correct_letter: str) -> str:
  35.     frac = "100" if letter == correct_letter else "-25"
  36.     return f'''    <answer fraction="{frac}" format="html">
  37.      <text><![CDATA[<p>Option {letter}</p>]]></text>
  38.      <feedback format="html">
  39.        <text></text>
  40.      </feedback>
  41.    </answer>'''
  42.  
  43. QUESTION_TEMPLATE = """<!-- question: {qid}  -->
  44.  <question type="multichoice">
  45.    <name>
  46.      <text>{qname}</text>
  47.    </name>
  48.    <questiontext format="html">
  49.      <text><![CDATA[<p><img src="@@PLUGINFILE@@/{fname}"></p>]]></text>
  50. <file name="{fname}" path="/" encoding="base64">{b64}</file>
  51.    </questiontext>
  52.    <generalfeedback format="html">
  53.      <text></text>
  54.    </generalfeedback>
  55.    <defaultgrade>1.0000000</defaultgrade>
  56.    <penalty>0.0000000</penalty>
  57.    <hidden>0</hidden>
  58.    <idnumber></idnumber>
  59.    <single>true</single>
  60.    <shuffleanswers>false</shuffleanswers>
  61.    <answernumbering>ABCD</answernumbering>
  62.    <showstandardinstruction>0</showstandardinstruction>
  63.    <correctfeedback format="html">
  64.      <text><![CDATA[<p>Your answer is correct.</p>]]></text>
  65.    </correctfeedback>
  66.    <incorrectfeedback format="html">
  67.      <text><![CDATA[<p>Your answer is incorrect.</p>]]></text>
  68.    </incorrectfeedback>
  69.    <shownumcorrect/>
  70. {answers}
  71.  </question>
  72. """
  73.  
  74. def main():
  75.     with open(IN_XML_WITH_B64, "r", encoding="utf-8") as f:
  76.         src_xml = f.read()
  77.  
  78.     b64_list = extract_base64_list(src_xml)
  79.  
  80.     if len(b64_list) < 25:
  81.         raise SystemExit(f"Found only {len(b64_list)} base64 <file> blocks. Need at least 25.")
  82.     if len(b64_list) > 25:
  83.         # If your file has more than 25, we’ll use the first 25 by default.
  84.         b64_list = b64_list[:25]
  85.  
  86.     xml_parts = ['<?xml version="1.0" encoding="UTF-8"?>\n<quiz>\n\n']
  87.  
  88.     qid = start
  89.     for i in range(1, 26):
  90.         qname = f"Q{i:02d}"
  91.         correct = ans[qname].upper()
  92.         if correct not in ("A", "B", "C", "D"):
  93.             raise SystemExit(f"Invalid correct option for {qname}: {correct}")
  94.  
  95.         fname = f"{FILENAME_PREFIX}{i:03d}{EXT}"
  96.         b64 = b64_list[i - 1]
  97.  
  98.         answers = "\n".join([
  99.             answer_block("A", correct),
  100.             answer_block("B", correct),
  101.             answer_block("C", correct),
  102.             answer_block("D", correct),
  103.         ])
  104.  
  105.         xml_parts.append(QUESTION_TEMPLATE.format(
  106.             qid=qid, qname=qname, fname=fname, b64=b64, answers=answers
  107.         ))
  108.         xml_parts.append("\n\n")
  109.         qid += 1
  110.  
  111.     xml_parts.append("</quiz>\n")
  112.  
  113.     with open(OUT_XML, "w", encoding="utf-8") as f:
  114.         f.write("".join(xml_parts))
  115.  
  116.     print(f" Wrote {OUT_XML} using 25 base64 blocks from {IN_XML_WITH_B64}")
  117.  
  118. if __name__ == "__main__":
  119.     main()
Add Comment
Please, Sign In to add comment