"""
IL_PPT_API.py — FAST Quiz PPT generator (API, no browser scraping)
--------------------------------------------------------------------
For each QID it:
1. Logs into the CMS over HTTP (no browser navigation)
2. Fetches the question JSON via /questions/findone
3. Renders the question + options (HTML + MathML) locally with MathJax
in ONE persistent headless page → white text on transparent PNG
4. Drops each render onto your branded template slide (logo + header kept)
Run:
python IL_PPT_API.py
Then paste QIDs (comma / newline separated) and press Enter on a blank line.
Optional command-line form:
python IL_PPT_API.py ILQ-123 ILQ-456 --template "C:\\path\\tpl.pptx" --out out.pptx
"""
import os, sys, io, json, time, copy, re, argparse, threading
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime
import requests
import PIL.Image
# Make console output UTF-8 safe (Windows cp1252 chokes on ✓ → etc.)
try:
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
except Exception:
pass
from pptx import Presentation
from pptx.util import Inches, Pt
from pptx.oxml.ns import qn
from pptx.dml.color import RGBColor
_WHITE = RGBColor(0xFF, 0xFF, 0xFF)
# ── Credentials (CLI fallback only; the web app passes the SME's own session
# token via generate(headers=...). Set via env so no secret lives in source). ─
CRED_PHONE = os.environ.get("PPT_CRED_PHONE", "")
CRED_PASSWORD = os.environ.get("PPT_CRED_PASSWORD", "")
# ── Defaults ──────────────────────────────────────────────────────────────────
DEFAULT_TEMPLATE = os.environ.get(
"PPT_TEMPLATE",
os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
"database", "ppt_template.pptx"),
)
import il_endpoints
LOGIN_URL = f"{il_endpoints.GATEWAY_API}/api/v1/user/agents/login"
FINDONE = il_endpoints.QB_API + "/questions/findone/{qid}"
# ══════════════════════════════════════════════════════════════════════════════
# API
# ══════════════════════════════════════════════════════════════════════════════
def api_login(log=print):
h = {"tenant": "infinitylearn", "tenant-id": "1", "product-id": "1000",
"platform": "web", "content-type": "application/json"}
body = {"admission_number": CRED_PHONE, "isd_code": "+91", "phone": CRED_PHONE,
"password": CRED_PASSWORD, "product_id": 7, "tenant_id": 1}
r = requests.post(LOGIN_URL, headers=h, json=body, timeout=30)
r.raise_for_status()
d = r.json()
tok = d.get("accessToken") or d.get("data", {}).get("accessToken")
if not tok:
raise RuntimeError("Login succeeded but no accessToken in response")
import base64
p = tok.split(".")[1]; p += "=" * (-len(p) % 4)
dbid = str(json.loads(base64.urlsafe_b64decode(p)).get("DBId", ""))
log(f" ✓ Logged in (userid {dbid})")
return {"authorization": "Bearer " + tok, "tenant": "infinitylearn",
"x-tenant": "infinitylearn", "userid": dbid, "content-type": "application/json"}
def fetch_question(headers, qid, log=print):
r = requests.post(FINDONE.format(qid=qid), headers=headers, timeout=30)
if r.status_code not in (200, 201):
raise RuntimeError(f"findone HTTP {r.status_code}")
return r.json().get("data", r.json())
# ══════════════════════════════════════════════════════════════════════════════
# Local HTML/MathML renderer (one persistent headless page)
# ══════════════════════════════════════════════════════════════════════════════
HTML_TMPL = """
"""
# ── CMS HTML clean-up before rendering ────────────────────────────────────────
# CMS content is authored in the editor at ~14-16px, and some of it hard-codes
# that size: MathType/ChemType math saved with mathsize="12px".."16px", inline
# font-size styles, tables fixed at width:400px, and small pasted bitmaps. On the
# 30px slide card those all come out tiny or cramped, so strip the fixed sizes
# and scale images by the same editor->card ratio.
IMG_SCALE = 2.0 # card text (30px) / CMS editor text (~15px)
IMG_MAX_W = 1000 # px; the card is 1180 wide minus padding and labels
# The card is shrunk onto an ~2:1 slide box (_add_question), so anything much
# taller than ~600px makes the WHOLE question tiny. Cap image heights so one tall
# diagram — or four stacked option structures — can't do that.
STEM_IMG_MAX_H = 380 # px, images in the question body
OPT_IMG_MAX_H = 210 # px, images inside an option
_WHITE_CUTOFF = 235 # a pixel this bright on every channel counts as background
_EMPTY_P = re.compile(r']*>(?:\s| | | |
)*
', re.I)
# Line breaks / non-breaking spaces at the very start or end of a paragraph (CMS
# options often end "20 J
"): each one drew an extra blank
# line under that option only, so the gaps between options looked random.
_BLANK_RUN = r'(?:\s| | | |
)+'
_P_TRAILING_BLANK = re.compile(_BLANK_RUN + r'(?=)', re.I)
_P_LEADING_BLANK = re.compile(r'(]*>)' + _BLANK_RUN, re.I)
_EDGE_BLANK = re.compile(r'^' + _BLANK_RUN + r'|' + _BLANK_RUN + r'$', re.I)
# A table row whose every cell is blank (CMS tables often end with one).
_EMPTY_TR = re.compile(
r'
]*>(?:\s*]*>(?:\s| | | |
)*)*\s*
',
re.I)
_MATH_SIZE = re.compile(r'\s(?:mathsize|fontsize)="[^"]*"', re.I)
_STYLE_ATTR = re.compile(r'\sstyle="([^"]*)"', re.I)
_IMG_TAG = re.compile(r'
]*>', re.I)
_TABLE_TAG = re.compile(r'<(figure|table|td|th|col)\b[^>]*>', re.I)
_ENTITY = re.compile(r'&(#?\w+);')
def _drop_css(style, props):
"""Remove the given CSS properties from an inline style string.
The CMS writes quotes inside style values as entities
(font-family:"Aptos"), whose own ';' must not split a declaration,
so entities are masked while splitting and restored afterwards."""
masked = _ENTITY.sub(lambda m: "\x00" + m.group(1) + "\x01", style)
kept = [d for d in masked.split(";")
if d.strip() and d.split(":", 1)[0].strip().lower() not in props]
return re.sub("\x00(.*?)\x01", r"&\1;", ";".join(kept))
def _restyle(tag, props):
"""Strip `props` from a tag's style attribute (drop the attribute if empty)."""
def fix(m):
s = _drop_css(m.group(1), props)
return f' style="{s}"' if s else ""
return _STYLE_ATTR.sub(fix, tag)
def _load_image(src):
"""src (data: URI or http URL) -> PIL image, or None if it can't be read."""
import base64
try:
if src.startswith("data:"):
raw = base64.b64decode(src.split(",", 1)[1])
elif src.startswith("http"):
r = requests.get(src, timeout=15)
r.raise_for_status()
raw = r.content
else:
return None
im = PIL.Image.open(io.BytesIO(raw))
im.load()
return im
except Exception:
return None
def _clear_white_background(im):
"""Opaque image on a white background -> the white made transparent, so the
card's invert filter turns the ink white instead of drawing a black box.
Returns None when the image isn't white-backed (left untouched)."""
from PIL import ImageChops
rgba = im.convert("RGBA")
w, h = rgba.size
if rgba.getchannel("A").getextrema()[0] < 255:
return None # already has transparency
corners = [rgba.getpixel(p) for p in ((0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1))]
if not all(min(c[:3]) >= _WHITE_CUTOFF for c in corners):
return None # photo / coloured backdrop
ink = rgba.convert("L").point(lambda v: 0 if v >= _WHITE_CUTOFF else 255)
rgba.putalpha(ImageChops.multiply(rgba.getchannel("A"), ink))
return rgba
def _fix_img(tag, max_h=None):
m = re.search(r'\ssrc="([^"]+)"', tag)
if not m:
return tag
src = m.group(1)
im = _load_image(src)
if im is None:
return tag
# Width as the editor showed it: an explicit width (resized in the editor)
# wins over the bitmap's own size.
wm = (re.search(r'\swidth="(\d+)', tag)
or re.search(r'width\s*:\s*(\d+(?:\.\d+)?)px', tag))
shown = float(wm.group(1)) if wm else float(im.size[0])
width = int(min(shown * IMG_SCALE, IMG_MAX_W))
if max_h and im.size[0]:
# Keep the aspect ratio: a tall image gets narrower, never squashed.
height = width * im.size[1] / im.size[0]
if height > max_h:
width = max(1, int(width * max_h / height))
cleared = _clear_white_background(im)
if cleared is not None:
import base64
buf = io.BytesIO()
cleared.save(buf, "PNG")
src = "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode()
tag = re.sub(r'\s(?:width|height)="[^"]*"', "", tag)
tag = _restyle(tag, {"width", "height", "max-width"})
tag = tag.replace(m.group(0), f' src="{src}"', 1)
return tag[:-1].rstrip("/").rstrip() + f' style="width:{width}px">'
def normalize_cms_html(html, img_max_h=None):
"""Make CMS question HTML render at slide size (see the block comment above).
`img_max_h` caps each image's rendered height in px (aspect kept)."""
if not html or not isinstance(html, str):
return html
html = _P_TRAILING_BLANK.sub("", html)
html = _P_LEADING_BLANK.sub(r"\1", html)
html = _EDGE_BLANK.sub("", html)
html = _EMPTY_P.sub("", html)
html = _EMPTY_TR.sub("", html)
html = _MATH_SIZE.sub("", html)
html = _STYLE_ATTR.sub(
# font-family too: pasted Word text carries e.g. "Aptos" on some lines
# only, which mixed two typefaces inside one question on the slide.
lambda m: (f' style="{s}"' if (s := _drop_css(m.group(1), {"font-size", "font-family"}))
else ""),
html)
html = _TABLE_TAG.sub(
lambda m: re.sub(r'\swidth="[^"]*"', "", _restyle(m.group(0), {"width"})), html)
html = _IMG_TAG.sub(lambda m: _fix_img(m.group(0), img_max_h), html)
return html
def _normalize_question(q):
"""A copy of the question dict with its stem and options normalised
(matrix options are lists of columns, so recurse one level)."""
q = dict(q)
q["question_text"] = normalize_cms_html(q.get("question_text") or "",
img_max_h=STEM_IMG_MAX_H)
q["answer_options"] = [
[normalize_cms_html(x, img_max_h=OPT_IMG_MAX_H) for x in o]
if isinstance(o, (list, tuple))
else normalize_cms_html(o, img_max_h=OPT_IMG_MAX_H)
for o in (q.get("answer_options") or [])]
return q
def _matrix_columns_html(q):
"""None unless answer_options is matrix-style (one inner list per column);
otherwise the labeled columns as a side-by-side HTML table."""
from cms_text import _col_labels, _ROMAN
opts = q.get("answer_options") or []
if not (len(opts) >= 2 and all(isinstance(o, (list, tuple)) for o in opts)):
return None
fmt_keys = ("matrix_column1_label_format", "matrix_column2_label_format",
"matrix_column3_label_format")
defaults = ("capital_alpha", "capital_roman", "capital_alpha")
cols = []
for ci, col in enumerate(opts):
fmt = (q.get(fmt_keys[ci]) if ci < len(fmt_keys) else None) \
or (defaults[ci] if ci < len(defaults) else "capital_alpha")
labs = _col_labels(fmt, len(col))
cells = "".join(
f'({labs[i]}){x}
'
for i, x in enumerate(col))
head = _ROMAN[ci] if ci < len(_ROMAN) else str(ci + 1)
cols.append(''
f'Column {head}{cells} | ')
return '"
def expand_questions(data):
"""One findone payload -> [(slide_suffix, data)] — passage questions yield
one slide per child_question (passage + that child's stem/options)."""
q = (data or {}).get("question", {}) or {}
kids = q.get("child_questions") or []
if not kids:
return [("", data)]
passage = q.get("question_text") or ""
out = []
for n, child in enumerate(kids, 1):
child = child or {}
stem = (passage + ''
f'({n})
' + (child.get("question_text") or ""))
out.append((f"#{n}", {**data, "question": {**child, "question_text": stem}}))
return out
def build_html(data):
q = _normalize_question(data.get("question", {}))
qtext = q.get("question_text") or ""
matrix = _matrix_columns_html(q)
if matrix is not None:
return HTML_TMPL.format(question=qtext, options=matrix)
opts = q.get("answer_options") or []
nums = [str(i + 1) for i in range(8)]
parts = []
is_tf = len(opts) == 2 and all(str(o).strip() in ("True", "False") for o in opts)
for i, o in enumerate(opts):
lbl = "" if is_tf else f"({nums[i]})"
parts.append(f'{lbl}{o}
')
# Picture options (structures, circuits) stacked one per row make the card
# several times taller than the slide; two per row halves that.
grid = len(opts) >= 3 and any("
{options}'
return HTML_TMPL.format(question=qtext, options=options)
def correct_option_indices(q):
"""0-based indices of the correct options of a plain choice question — the
CMS stores them 1-based (["2"], ["1", "3"]); letters are accepted too.
[] for matrix / numerical / unanswered questions (nothing to tick)."""
opts = (q or {}).get("answer_options") or []
if not opts or any(isinstance(o, (list, tuple)) for o in opts):
return []
ca = q.get("correct_answer")
if not isinstance(ca, (list, tuple)):
ca = re.split(r"[,\s]+", str(ca or ""))
out = []
for a in ca:
s = str(a).strip()
if s.isdigit():
i = int(s) - 1
elif len(s) == 1 and s.isalpha():
i = ord(s.upper()) - 65
else:
continue
if 0 <= i < len(opts) and i not in out:
out.append(i)
return out
# Where each correct option landed on the rendered card, in CSS px from the
# card's top-left, plus the card width and an option's line height so
# _add_reveal can scale them onto the placed picture.
_MEASURE_JS = """(idx) => {
const card = document.querySelector('#card').getBoundingClientRect();
const opts = [...document.querySelectorAll('#card .opts .opt')];
const lh = opts.length ? parseFloat(getComputedStyle(opts[0]).lineHeight) : 45;
return {card_w: card.width, line_h: lh || 45,
ticks: idx.filter(i => i < opts.length).map(i => {
const r = opts[i].getBoundingClientRect();
return [r.left - card.left, r.top - card.top];
})};
}"""
def _reveal_marks(page, data):
"""What the Question + Answer deck reveals on click: a tick beside each
correct option, or — when there is no option to tick (numerical, integer,
matrix) — the answer as text."""
from cms_text import correct_to_readable
q = data.get("question", {}) or {}
idx = correct_option_indices(q)
if idx:
marks = page.evaluate(_MEASURE_JS, idx)
if marks.get("ticks"):
marks["answer"] = ""
return marks
return {"ticks": [], "answer": correct_to_readable(q)}
def _render_page(page, data, log, reveal=False):
"""Render question data to PNG on a given Playwright page (thread-safe).
reveal=True returns (png, marks) — see _reveal_marks."""
page.set_content(build_html(data), wait_until="load")
try:
page.wait_for_function(
"() => window.MathJax && MathJax.startup && MathJax.startup.promise",
timeout=15000)
page.evaluate(
"async () => { await MathJax.startup.promise;"
" if (MathJax.typesetPromise) await MathJax.typesetPromise(); }")
except Exception as e:
log(f" ⚠ MathJax: {str(e)[:70]}")
page.wait_for_timeout(120)
png = page.locator("#card").screenshot(omit_background=True)
return (png, _reveal_marks(page, data)) if reveal else png
class RendererPool:
"""Creates one Playwright browser per thread (greenlet-safe)."""
def __init__(self, count, log=print):
self._log = log
self._local = threading.local()
self._all = []
self._lock = threading.Lock()
def _get(self):
if not hasattr(self._local, 'rend'):
r = Renderer(self._log)
self._local.rend = r
with self._lock:
self._all.append(r)
return self._local.rend
def render(self, data, reveal=False):
return self._get().render(data, reveal=reveal)
def close(self):
for r in list(self._all):
r.close()
class Renderer:
"""Legacy single-page renderer (used by CLI)."""
def __init__(self, log=print):
from playwright.sync_api import sync_playwright
self._pw = sync_playwright().start()
self.browser = self._pw.chromium.launch(headless=True)
self.page = self.browser.new_page(
viewport={"width": 1240, "height": 900}, device_scale_factor=2)
self.log = log
def render(self, data, reveal=False):
return _render_page(self.page, data, self.log, reveal=reveal)
def close(self):
try: self.browser.close()
except Exception: pass
try: self._pw.stop()
except Exception: pass
# ══════════════════════════════════════════════════════════════════════════════
# Branded-template PPT assembly (same logic as ppt_w_gg.py)
# ══════════════════════════════════════════════════════════════════════════════
def _duplicate_slide(prs, src):
new = prs.slides.add_slide(src.slide_layout)
for shp in list(new.shapes):
shp._element.getparent().remove(shp._element)
rId_map = {}
for rId, rel in src.part.rels.items():
if "notesSlide" in rel.reltype:
continue
if rel.is_external:
rId_map[rId] = new.part.rels.get_or_add_ext_rel(rel.reltype, rel._target_ref)
else:
rId_map[rId] = new.part.relate_to(rel._target, rel.reltype)
for shp in src.shapes:
el = copy.deepcopy(shp._element)
for attr in (qn("r:embed"), qn("r:link")):
for node in el.iter():
if node.get(attr) in rId_map:
node.set(attr, rId_map[node.get(attr)])
new.shapes._spTree.append(el)
return new
def _remove_slide(prs, index):
lst = prs.slides._sldIdLst
lst.remove(list(lst)[index])
def _drop_q_marker(slide):
for shp in list(slide.shapes):
if shp.has_text_frame and shp.text_frame.text.strip().rstrip(".") == "Q":
shp._element.getparent().remove(shp._element)
def _add_blank(slide, qid):
"""The Question + Blank deck's second slide: the same template slide with no
question on it (room to work it). Notes say which question it belongs to."""
_drop_q_marker(slide)
slide.notes_slide.notes_text_frame.text = f"{qid} (blank)"
def _add_question(slide, prs, img_bytes, qid):
_drop_q_marker(slide)
img = PIL.Image.open(io.BytesIO(img_bytes))
aspect = img.size[1] / img.size[0]
box_left, box_top = Inches(1.30), Inches(1.35)
box_w = prs.slide_width - box_left - Inches(0.45)
box_h = prs.slide_height - box_top - Inches(0.35)
w = box_w; h = int(w * aspect)
if h > box_h:
h = box_h; w = int(h / aspect)
pic = slide.shapes.add_picture(io.BytesIO(img_bytes), box_left, box_top, width=w, height=h)
slide.notes_slide.notes_text_frame.text = qid
return pic
# ── Question + Answer PPT (/ppt_reveal): answer appears on click ──────────────
_TICK_CLR = RGBColor(0x00, 0xB0, 0x50)
def _add_reveal(slide, prs, pic, marks):
"""Add the answer marks (hidden until a click) to a question slide: a ✔ just
left of each correct option, else an "Ans: …" line under the picture."""
if not marks:
return
scale = pic.width / max(marks.get("card_w") or 1, 1) # EMU per card px
shapes = []
size = int(marks.get("line_h", 45) * scale) # one option line
for x, y in marks.get("ticks") or []:
left = max(int(pic.left + x * scale) - size, 0)
tb = _add_text(slide, left, int(pic.top + y * scale), size, size, "✔",
max(size / 12700 * 0.8, 8), _TICK_CLR, align=2, ins=0)
tb.text_frame.margin_top = tb.text_frame.margin_bottom = 0
tb.text_frame.word_wrap = False
shapes.append(tb)
if not shapes and marks.get("answer"):
top = min(pic.top + pic.height + Inches(0.05), prs.slide_height - Inches(0.6))
shapes.append(_add_text(slide, pic.left, top, pic.width, Inches(0.5),
f"Ans: {marks['answer']}", 24, _TICK_CLR))
if shapes:
_add_click_appear(slide, [s.shape_id for s in shapes])
# One "Appear" entrance effect (PowerPoint's preset 1) on a shape.
_APPEAR_XML = (
''
''
''
'style.visibility'
'')
def _add_click_appear(slide, shape_ids):
"""Give the slide one click that makes every shape in shape_ids appear
together (the first is the click effect, the rest run "with previous").
python-pptx has no animation API, so this writes the slide's ."""
from pptx.oxml import parse_xml
effects = "".join(
_APPEAR_XML.format(id=5 + 2 * i, id2=6 + 2 * i, spid=sid,
node="clickEffect" if i == 0 else "withEffect")
for i, sid in enumerate(shape_ids))
builds = "".join(f'' for sid in shape_ids)
timing = parse_xml(
''
''
''
''
f'{effects}'
''
''
''
f'{builds}')
sld = slide._element
for old in sld.findall(qn("p:timing")):
sld.remove(old)
# Schema order: cSld, clrMapOvr, transition, timing, extLst.
ext = sld.find(qn("p:extLst"))
if ext is not None:
ext.addprevious(timing)
else:
sld.append(timing)
def _find_topic_shape(slide):
for shp in slide.shapes:
if shp.has_text_frame and "Topic Name" in shp.text_frame.text:
return shp
return None
def _set_rounded_box_text(box, lines, align=2):
from pptx.enum.text import PP_ALIGN
align = {1: PP_ALIGN.LEFT, 2: PP_ALIGN.CENTER, 3: PP_ALIGN.RIGHT}[align]
tf = box.text_frame
tf.word_wrap = True
tf.clear()
for i, (txt, color, bold) in enumerate(lines):
p = tf.paragraphs[0] if i == 0 else tf.add_paragraph()
p.alignment = align
r = p.add_run()
r.text = txt
_style_run(r, 16, color, bold)
def _add_meta_boxes(slide, year_label="", chapter="", topic=""):
"""Reference question-slide layout (table mode).
- top-left rounded box: the year (cyan)
- bottom-right rounded box: chapter (muted) on line 1, topic (cyan) on line 2
- the template's top-centre 'Topic Name' placeholder is removed.
"""
from pptx.enum.shapes import MSO_SHAPE
# Remove the template's top-centre 'Topic Name' placeholder.
target = _find_topic_shape(slide)
if target is not None:
target._element.getparent().remove(target._element)
# Year box — top-left, no fill / no line, cyan text.
if year_label:
year_box = slide.shapes.add_shape(
MSO_SHAPE.ROUNDED_RECTANGLE, Inches(0.31), Inches(0.27),
Inches(2.56), Inches(0.78))
year_box.adjustments[0] = 0.5
year_box.fill.background()
year_box.line.fill.background()
year_box.shadow.inherit = False
_set_rounded_box_text(year_box,
[(year_label, _CYAN, False)], align=1)
# Chapter + topic box — bottom-right, right-aligned two lines.
if chapter or topic:
bt = slide.shapes.add_shape(
MSO_SHAPE.ROUNDED_RECTANGLE, Inches(8.76), Inches(6.37),
Inches(4.18), Inches(0.78))
bt.adjustments[0] = 0.5
bt.fill.background()
bt.line.fill.background()
bt.shadow.inherit = False
lines = []
if chapter:
lines.append((chapter, _MUTED, False))
if topic:
lines.append((topic, _CYAN, False))
_set_rounded_box_text(bt, lines, align=2)
def _update_topic_box(slide, topic_name="", year_label=""):
"""Flat-mode (non-outline) fallback: keep the old top-centre topic box.
Purely for the backward-compatible plain-QID path, which has no
chapter/topic grouping. The reference two/one-box layout only applies to
the table (outline) mode via _add_meta_boxes.
"""
target = _find_topic_shape(slide)
if target is None:
return
text = ""
if topic_name and year_label:
text = f"{topic_name} \u2014 {year_label}"
elif topic_name:
text = topic_name
elif year_label:
text = year_label
else:
return
target.text_frame.text = text
for p in target.text_frame.paragraphs:
p.alignment = 2 # CENTER
for run in p.runs:
run.font.size = Pt(16)
run.font.bold = False
# ══════════════════════════════════════════════════════════════════════════════
# Orchestrator
# ══════════════════════════════════════════════════════════════════════════════
# ── Tabular outline parsing ─────────────────────────────────────────────────
# The SME pastes spreadsheet rows. Two shapes are supported, per line:
#
# TAB-separated (what Excel/Sheets actually put on the clipboard) — columns
# are read positionally, so names may contain spaces, commas and digits:
# Chapter Topic QID Year
# Chapter ch_no Topic topic_no QID q_no Year
# Integer-only cells (the optional ch_no/topic_no/q_no indices) are ignored,
# a header row has no ILQ cell and drops out on its own.
#
# SPACE-separated (hand-typed, or a paste that lost its tabs) — there are no
# column boundaries, so we anchor on the ILQ token and the integer index
# columns, which is why those indices are REQUIRED in this shape:
# Chapter... Topic... QID Year...
# - the integer just before the QID is the topic_no; just before that is ch_no
# - chapter = tokens before ch_no; topic = tokens between ch_no and topic_no
# - q_no = the integer right after the QID; year = everything after that
_QID_RE = re.compile(r"ILQ-\d+", re.I)
_INT_RE = re.compile(r"^\d+$")
def _row_from_cells(cells):
"""One TAB-separated row -> (chapter, topic, qid, year), or None.
Columns are positional, so the only thing we look for is which cell holds
the ILQ id. Integer-only cells around it are the optional ch_no/topic_no/
q_no indices and are discarded; the first two remaining cells to the left
are the chapter and the topic, and what is left to the right is the year.
"""
cells = [c.strip() for c in cells]
hit = next(((i, _QID_RE.search(c)) for i, c in enumerate(cells)
if _QID_RE.search(c)), None)
if hit is None:
return None # header row, or a line with no id
qi, m = hit
qid = m.group(0)
names = [c for c in cells[:qi] if c and not _INT_RE.match(c)]
chapter = names[0] if names else ""
topic = names[1] if len(names) > 1 else ""
rest = [c for c in cells[qi + 1:] if c]
# A lone leading integer is the q_no — unless it is the only cell left, in
# which case it is a bare year ("2024") and must be kept.
if len(rest) > 1 and _INT_RE.match(rest[0]):
rest = rest[1:]
return (chapter, topic, qid, " ".join(rest))
def _rows(raw):
"""Yield (chapter, topic, qid, year) per logical row of the pasted table."""
rows = []
for ln in (raw or "").splitlines():
# A tabbed line came from a spreadsheet and has real column boundaries;
# only fall back to token-walking when there are none to use.
if "\t" in ln:
row = _row_from_cells(ln.split("\t"))
if row is not None:
rows.append(row)
continue
toks = ln.split()
if not toks:
continue
qi = next((i for i, t in enumerate(toks) if _QID_RE.match(t)), None)
if qi is None:
continue
qid = toks[qi]
def prev_int(start):
"""Index of nearest integer token at or before `start` (walk left)."""
for i in range(start, -1, -1):
if _INT_RE.match(toks[i]):
return i
return -1
def next_int(start):
"""Index of nearest integer token at or after `start` (walk right)."""
for i in range(start, len(toks)):
if _INT_RE.match(toks[i]):
return i
return -1
# q_no = first integer after the QID; year = tokens after it.
qn = next_int(qi + 1)
year = " ".join(toks[qn + 1:]) if qn >= 0 else ""
# topic_no = nearest integer before the QID; ch_no = nearest before that.
tn = prev_int(qi - 1)
cn = prev_int(tn - 1) if tn > 0 else -1
if cn >= 0:
chapter = " ".join(toks[:cn])
topic = " ".join(toks[cn + 1:tn])
elif tn >= 0:
chapter = ""
topic = " ".join(toks[:tn])
else:
chapter = ""
topic = " ".join(toks[:qi])
rows.append((chapter, topic, qid, year))
return rows
def parse_tabular(raw):
"""Raw pasted table -> [{title, topics: [{title, units: [(qid, year), ...]}]}].
Grouping is by exact chapter then topic name, in first-seen order. Years are
carried per QID. A QID with no chapter/topic lands under a blank fallback so
it is never silently dropped.
"""
chapters, ch_by_name = [], {}
for chapter, topic, qid, year in _rows(raw):
# chapter == "" happens for bare-QID rows (no chapter/topic columns);
# keep it empty so no title slide is emitted for that group.
if chapter not in ch_by_name:
ch_by_name[chapter] = {"title": chapter, "topics": [], "_tmap": {}}
chapters.append(ch_by_name[chapter])
ch = ch_by_name[chapter]
if topic not in ch["_tmap"]:
ch["_tmap"][topic] = {"title": topic, "units": []}
ch["topics"].append(ch["_tmap"][topic])
ch["_tmap"][topic]["units"].append((qid, year))
for ch in chapters:
ch.pop("_tmap", None)
return chapters
def _flatten_outline(chapters):
"""Structured outline -> flat ordered units [(qid, year, topic_title)].
Used only when no explicit grouping is supplied (backward-compat flat path).
"""
out = []
for ch in chapters:
for tp in ch.get("topics", []):
for qid, year in tp.get("units", []):
out.append((qid, year, tp["title"]))
return out
_BRAND = "Arial Rounded MT Bold"
_ACCENT = RGBColor(0x18, 0x90, 0xFF) # IL indigo-blue accent (eyebrow, NEET PYQ)
_LINE_CLR = RGBColor(0x00, 0xB0, 0xF0) # light-blue divider under the title
_CYAN = RGBColor(0x00, 0xCC, 0xFF) # cyan for the year box + topic line
_MUTED = RGBColor(0x66, 0x99, 0xCC) # muted accent2-tone for the chapter line
_PYQ_X = Inches(1.33)
_PYQ_Y = Inches(0.75)
_PYQ_SIZE = 38
# Exam tag printed on every chapter/topic title slide. The SME picks this per
# run on the /ppt page; AIPMT questions ride under "NEET PYQ" (AIPMT is NEET's
# predecessor), so there is no separate AIPMT tag.
DEFAULT_PYQ_TAG = "NEET PYQ"
def _style_run(run, size, color=_WHITE, bold=True, spc=None):
run.font.name = _BRAND
run.font.size = Pt(size)
run.font.bold = bold
run.font.color.rgb = color
if spc:
run.font._rPr.set('spc', str(spc))
def _add_text(slide, left, top, width, height, text, size, color=_WHITE,
align=1, bold=True, spc=None, ins=Inches(0.1)):
"""Add a word-wrapped textbox with the given alignment/inset, return it.
align: 1=LEFT, 2=CENTER, 3=RIGHT (python-pptx PP_ALIGN values)."""
tb = slide.shapes.add_textbox(left, top, width, height)
tf = tb.text_frame
tf.word_wrap = True
tf.margin_left = ins
tf.margin_right = ins
tf.margin_top = Inches(0.02)
tf.margin_bottom = Inches(0.02)
if isinstance(align, int):
from pptx.enum.text import PP_ALIGN
align = {1: PP_ALIGN.LEFT, 2: PP_ALIGN.CENTER,
3: PP_ALIGN.RIGHT}[align]
tf.text = text
para = tf.paragraphs[0]
para.alignment = align
for r in para.runs:
_style_run(r, size, color, bold, spc)
return tb
def _add_accent_rule(slide, left, top, width, height=Inches(0.02)):
"""A thin accent-colored separator bar (matching the reference divider)."""
from pptx.enum.shapes import MSO_SHAPE
bar = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, left, top, width, height)
bar.fill.solid()
bar.fill.fore_color.rgb = _LINE_CLR
bar.line.fill.background()
bar.shadow.inherit = False
return bar
def _add_title_slide(prs, text, kind="topic", tag=DEFAULT_PYQ_TAG):
"""Build a branded chapter/topic title slide showing `text`.
Keeps the template's logo; removes the 'Q.' + small 'Topic Name' shapes;
then draws the reference layout (left-aligned, with the exam tag on top):
(top-left tag label)
CHAPTER / TOPIC (eyebrow, left-aligned caps)
── (white title + light-blue rule)
kind: 'chapter' → larger title + 'CHAPTER' eyebrow; 'topic' → smaller.
tag: exam label, e.g. 'NEET PYQ' / 'JEE Main PYQ'; falsy omits the label.
"""
if len(prs.slides) < 1:
slide = prs.slides.add_slide(prs.slide_layouts[6])
tb = slide.shapes.add_textbox(0, 0, prs.slide_width, prs.slide_height)
tb.text_frame.word_wrap = True
tb.text_frame.text = text
para = tb.text_frame.paragraphs[0]
para.alignment = 2 # CENTER
for r in para.runs:
_style_run(r, 40)
return slide
slide = _duplicate_slide(prs, prs.slides[0])
# Remove the "Q." text box and the small "Topic Name" placeholder so we can
# draw the fresh designed divider. Keep the logo.
for shp in list(slide.shapes):
try:
txt = shp.text_frame.text.strip()
except Exception:
txt = ""
if txt.rstrip(".") == "Q" or "Topic Name" in txt:
shp._element.getparent().remove(shp._element)
w = prs.slide_width
is_ch = kind == "chapter"
eyebrow = "CHAPTER" if is_ch else "TOPIC"
title_size = 38 if is_ch else 32
ink = Inches(0.79) # left text inset (matches reference)
full_w = w - ink - Inches(0.5)
# 1) Exam tag — top-left, bold, muted accent, centred in its box.
if tag:
tag_w = w - _PYQ_X - Inches(0.5)
_add_text(slide, _PYQ_X, _PYQ_Y, tag_w, Inches(0.68), tag,
_PYQ_SIZE, color=_MUTED, align=1)
# 2) Eyebrow (left-aligned letter-spaced caps) + 3) title + 4) accent rule.
eye_y = Inches(2.50)
title_y = Inches(2.79)
_add_text(slide, 0, eye_y, full_w, Inches(0.40), eyebrow, 15,
color=_ACCENT, align=1, bold=True, spc=300, ins=ink)
tb = _add_text(slide, 0, title_y, full_w, Inches(1.2), text, title_size,
color=_WHITE, align=1, ins=ink)
# Auto-shrink so long names stay on one left-aligned line.
run = tb.text_frame.paragraphs[0].runs[0]
est_w = len(text) * title_size * 0.62 * 12700 # pt→EMU roughly
avail = full_w - ink - Inches(0.3)
if est_w > avail:
run.font.size = Pt(max(int(title_size * avail / est_w), 18))
# Light-blue rule under the title (chapter longer than topic).
_add_accent_rule(slide, Inches(0.81), title_y + Inches(0.60),
Inches(1.25 if is_ch else 0.75))
return slide
def parse_qids(raw):
seen, out = set(), []
for tok in re.split(r"[\s,;]+", raw.strip()):
tok = tok.strip()
if tok and tok not in seen:
seen.add(tok); out.append(tok)
return out
def _chapter_safe_name(title):
"""Chapter title -> safe filename stem (no FS-unsafe chars, no blanks)."""
name = re.sub(r'[\\/:*?"<>|]+', ' ', title)
name = re.sub(r'\s+', ' ', name).strip(' .')
return name or 'Untitled'
def generate_chapter_wise(outline, template_path=None, out_dir=None, log=print,
headers=None, workers=5, zip_path=None,
pyq_tag=DEFAULT_PYQ_TAG, blank_after=False, reveal=False):
"""Build ONE branded .pptx per chapter and zip them together.
`outline` is the grouped table outline. QIDs are fetched/rendered once and
shared across every chapter they appear in. Returns
{zip_path, chapter_files: [(chapter_title, path), ...]}
"""
import zipfile
if out_dir is None:
out_dir = os.path.dirname(os.path.abspath(__file__))
os.makedirs(out_dir, exist_ok=True)
chapters = [ch for ch in outline if ch.get("title")]
if not chapters:
raise ValueError("chapter-wise output needs an outline with chapter titles")
# ── Phase 1 once: fetch + render every unique QID, shared across chapters ─
rendered, errors = _fetch_render_all(chapters, headers=headers,
workers=workers, log=log, reveal=reveal)
chapter_files = []
used_names = set()
for i, ch in enumerate(chapters):
stem = _chapter_safe_name(ch["title"])
if stem in used_names:
stem = f"{stem}_{i+1}"
used_names.add(stem)
path = os.path.join(out_dir, f"{stem}.pptx")
log(f"\n════ Deck {i+1}/{len(chapters)}: {ch['title']} ({stem}.pptx) ════")
generate([q for tp in ch.get("topics", []) for q, _ in tp.get("units", [])],
template_path=template_path, out_path=path, log=log,
headers=headers, workers=workers, pyq_tag=pyq_tag,
outline=[ch], _rendered=rendered, _errors=errors,
blank_after=blank_after, reveal=reveal)
chapter_files.append((ch["title"], path))
if zip_path is None:
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
zip_path = os.path.join(out_dir, f"quiz_chapters_{stamp}.zip")
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
for title, path in chapter_files:
arc = _chapter_safe_name(title) + ".pptx"
zf.write(path, arcname=arc)
log(f"\n✅ Zipped {len(chapter_files)} deck(s) → {zip_path}")
return {"zip_path": zip_path, "chapter_files": chapter_files}
def _fetch_render(pool, qid, log=print, headers=None, reveal=False):
"""(qid, [(suffix, png, marks)], error) — marks is None unless reveal."""
try:
data = fetch_question(headers, qid, log)
slides_data = expand_questions(data)
if reveal:
pngs = [(suffix, *pool.render(d, reveal=True)) for suffix, d in slides_data]
else:
pngs = [(suffix, pool.render(d), None) for suffix, d in slides_data]
return (qid, pngs, None)
except Exception as e:
return (qid, [], e)
def _collect_unique_qids(outline):
seen, out = set(), []
for ch in outline:
for tp in ch.get("topics", []):
for qid, _ in tp.get("units", []):
if qid not in seen:
seen.add(qid)
out.append(qid)
return out
def _fetch_render_all(outline, headers=None, workers=5, log=print, reveal=False):
"""Fetch + render every unique QID in the outline. Returns (rendered, errors)."""
headers = headers or api_login(log)
unique_qids = _collect_unique_qids(outline)
rend_pool = RendererPool(min(workers, max(len(unique_qids), 1)), log)
rendered, errors = {}, {}
try:
with ThreadPoolExecutor(max_workers=max(workers, 1)) as pool:
futures = {pool.submit(_fetch_render, rend_pool, qid, log, headers,
reveal): qid
for qid in unique_qids}
for future in as_completed(futures):
qid, pngs, err = future.result()
if err:
errors[qid] = err
else:
rendered[qid] = pngs
finally:
rend_pool.close()
return rendered, errors
def generate(qids=None, template_path=None, out_path=None, log=print, headers=None,
year_labels=None, topic_name="", workers=5, outline=None,
pyq_tag=DEFAULT_PYQ_TAG, _rendered=None, _errors=None,
blank_after=False, reveal=False):
t0 = time.time()
# ── Resolve the structured outline ──────────────────────────────────────
# `outline` is a list of chapters: [{title, topics: [{title, units: [(qid,
# year), ...]}], ...}]. When not supplied we build it from the flat `qids`
# (+ optional year_labels/topic_name) for backward compatibility — each QID
# becomes its own single-unit topic under one generated chapter, i.e. no
# title slides are emitted.
if outline is None:
if year_labels is None:
year_labels = []
units = [(qid, year_labels[i] if i < len(year_labels) else "", "")
for i, qid in enumerate(qids)]
outline = [{"title": "", "topics": [
{"title": "", "units": [(qid, year)]} for qid, year, _ in units]}]
# Backward-compat: single flat list, no title slides.
# Table (grouped) mode whenever a chapter carries a real title; the flat
# backward-compat outline has all-empty titles and keeps the old layout.
grouped = any(ch.get("title") for ch in outline)
flat_units = _flatten_outline(outline)
total_q = len(flat_units)
if template_path is None:
template_path = DEFAULT_TEMPLATE
if out_path is None:
out_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
f"quiz_{datetime.now():%Y%m%d_%H%M%S}.pptx")
branded = bool(template_path) and os.path.exists(template_path)
if branded:
prs = Presentation(template_path)
branded = len(prs.slides) >= 1
if not branded:
prs = Presentation()
prs.slide_width = Inches(13.33); prs.slide_height = Inches(7.5)
log("INFO: No usable template — plain black-on-transparent slides")
log(f"INFO: {total_q} question(s) → {out_path} ({workers} workers)")
headers = headers or api_login(log)
# ── Phase 1: parallel fetch + render (dedupe repeated QIDs) ─────────────
# When a shared cache is supplied (chapter-wise fan out) we only fetch the
# QIDs not already rendered and merge them in.
unique_qids = _collect_unique_qids(outline)
rendered = dict(_rendered or {})
errors = dict(_errors or {})
to_fetch = [q for q in unique_qids if q not in rendered]
if to_fetch:
rend_pool = RendererPool(min(workers, max(len(to_fetch), 1)), log)
try:
with ThreadPoolExecutor(max_workers=max(workers, 1)) as pool:
futures = {pool.submit(_fetch_render, rend_pool, qid, log, headers,
reveal): qid
for qid in to_fetch}
for future in as_completed(futures):
qid, pngs, err = future.result()
if err:
errors[qid] = err
else:
rendered[qid] = pngs
finally:
rend_pool.close()
# ── Phase 2: sequential slide assembly (python-pptx is not thread-safe) ─
ok = 0
failed_q = set()
seq = 0
def _new_q_slide():
if branded:
return _duplicate_slide(prs, prs.slides[0])
return prs.slides.add_slide(prs.slide_layouts[6])
for ch in outline:
# Chapter title slide (skip the blank backward-compat chapter).
if ch.get("title"):
_add_title_slide(prs, ch["title"], kind="chapter", tag=pyq_tag)
log(f" ⛶ Chapter: {ch['title']}")
for tp in ch.get("topics", []):
if tp.get("title"):
_add_title_slide(prs, tp["title"], kind="topic", tag=pyq_tag)
log(f" ⛶ Topic: {tp['title']}")
for qid, year in tp.get("units", []):
seq += 1
pngs = rendered.get(qid, None)
if pngs is None:
failed_q.add(qid)
log(f" ✗ [{seq}/{total_q}] {qid} — {errors.get(qid, 'no result')}")
continue
for suffix, png, marks in pngs:
# blank_after (the /ppt_blank page): each question slide is
# followed by the same slide minus the question.
for blank in ((False, True) if blank_after else (False,)):
slide = _new_q_slide()
if blank:
_add_blank(slide, qid + suffix)
else:
pic = _add_question(slide, prs, png, qid + suffix)
# reveal (the /ppt_reveal page): answer on click.
if reveal:
_add_reveal(slide, prs, pic, marks)
if grouped:
_add_meta_boxes(slide, year_label=year,
chapter=ch.get("title", ""),
topic=tp.get("title", ""))
else:
ttl = tp.get("title", "") or topic_name
_update_topic_box(slide, topic_name=ttl, year_label=year)
ok += 1
extra = f" ({len(pngs)} slides)" if len(pngs) > 1 else ""
log(f" ✓ [{seq}/{total_q}] {qid}{extra}")
if branded and len(prs.slides) > 1:
_remove_slide(prs, 0)
prs.save(out_path)
elapsed = time.time() - t0
ok_q = total_q - len(failed_q)
log(f"\n✅ Saved {ok_q}/{total_q} → {out_path}")
log(f" Total {elapsed:.1f}s ({elapsed/max(ok_q,1):.1f}s per question)")
return out_path
def main():
ap = argparse.ArgumentParser()
ap.add_argument("qids", nargs="*", help="QIDs (or omit to paste interactively)")
ap.add_argument("--template", default=DEFAULT_TEMPLATE)
ap.add_argument("--out", default="")
a = ap.parse_args()
qids = a.qids
if not qids:
print("Paste the tabular outline:\n"
" ChapterTopicQIDYear/Exam\n"
"or just QIDs (comma/newline separated). Blank line to finish:")
buf = []
while True:
try: line = input()
except EOFError: break
if not line.strip(): break
buf.append(line)
raw = "\n".join(buf)
# If it looks like a table (has an ILQ- token), group by chapter/topic;
# otherwise fall back to the flat QID list.
if re.search(r"ILQ-\d+", raw, re.I) and len(raw.split()) > 3:
outline = parse_tabular(raw)
generate(None, a.template, a.out or "", outline=outline)
return
qids = parse_qids(raw)
else:
qids = parse_qids(" ".join(qids))
if not qids:
print("No QIDs given."); return
out = a.out or os.path.join(
os.path.dirname(os.path.abspath(__file__)),
f"quiz_api_{datetime.now():%Y%m%d_%H%M%S}.pptx")
generate(qids, a.template, out)
if __name__ == "__main__":
main()