""" EduClone AI Portal — Login / Register / Admin / User roles Tab 1: Generate MCQs from topic (AI, 4 options, answer always provided) Tab 2: Upload MCQs → smart answer detection → clone with 4 distractors Author: Abdulqayyum MBA """ import gradio as gr import pandas as pd import datetime from auth import (init_db, register_user, login_user, log_activity, get_all_users, toggle_user_active, change_user_role, delete_user, get_activity_log, get_stats) from mcq_engine import ( generate_from_topic, read_and_parse, clone_mcqs, preview_mcqs, make_word, make_pdf, make_excel, BLOOMS ) init_db() # ── CSS ─────────────────────────────────────────────────────────────────────── CSS = """ * { box-sizing: border-box; } body { font-family: 'Inter', sans-serif; margin: 0; } .portal-banner { background: linear-gradient(135deg,#1e3a5f 0%,#1a56db 55%,#059669 100%); padding: 20px 28px 18px; border-radius: 14px; color: white; margin-bottom: 18px; } .portal-banner h1 { margin:0; font-size:1.65rem; letter-spacing:-.3px; font-weight:600; } .portal-banner p { margin:5px 0 0; opacity:.88; font-size:.88rem; } .auth-card { background: var(--color-background-primary); border: 1px solid var(--color-border-primary); border-radius: 14px; padding: 28px 32px; max-width: 460px; margin: 0 auto; box-shadow: 0 4px 24px rgba(0,0,0,.07); } .auth-card h2 { margin:0 0 18px; font-size:1.25rem; color:#1e3a5f; } .auth-divider { text-align:center; color:#9ca3af; margin:10px 0; font-size:.85rem; } .user-bar { background: var(--color-background-secondary); border: 1px solid var(--color-border-tertiary); border-radius: 10px; padding: 12px 18px; display: flex; align-items: center; justify-content: space-between; margin-bottom: 14px; font-size: .9rem; } .role-badge { font-size:.78rem; font-weight:600; padding:3px 10px; border-radius:20px; } .role-admin { background:#dbeafe; color:#1e40af; } .role-user { background:#dcfce7; color:#166534; } .hint-box { background: #fefce8; border: 1px solid #fde68a; border-radius: 8px; padding: 10px 14px; font-size:.85rem; line-height:1.7; margin-bottom: 12px; } .detect-box { background: #f0fdf4; border: 1px solid #a7f3d0; border-radius: 8px; padding: 10px 14px; font-size:.85rem; line-height:1.7; margin-bottom: 12px; } .dl-row { background:#f0fdf4; border:1px solid #a7f3d0; border-radius:8px; padding:12px; margin-top:8px; } footer { display:none !important; } """ BANNER_HTML = """

🎓 EduClone AI — Exam Intelligence Portal

Generate · Upload · Clone MCQs · Download Word / PDF / Excel  |  Abdulqayyum MBA — 18 yrs Academic Assessment · MBA · AI Governance · Azure AI

""" TAB1_HINT = """
📝 Tab 1 — Generate MCQs from a Topic: Enter any subject → choose Bloom's level → AI generates fresh MCQs with 4 options (A B C D) and a correct answer. Download as Word / PDF / Excel.
""" TAB2_HINT = """
🔁 Tab 2 — Upload & Clone your existing MCQs:
Upload .docx / .pdf / .txt file with your questions. The system detects the correct answer using:
  1. Bold option text   2. Underlined option text   3. Coloured (non-black) option text   4. Highlighted option text   5. Answer: X line at the end
If none of these are found, the answer is left as ⚠️ Unknown — no guess is made. Then the AI clones each question with 4 new distractors.
""" SAMPLE_MCQS = """1. Your patient is a 44-year-old female, alert and oriented, in moderate distress, complaining of difficulty breathing. She has a 1-week history of fever and malaise, shortness of breath developing 3 days ago. Left-sided chest pain with deep inspiration and a cough with sputum. Examination: hot, pale, dry skin; rhonchi and rales throughout the left lung. Right lung clear. HR = 134, BP = 88/64, RR = 24, SpO2 = 92%. History of two previous myocardial infarctions. Takes nitroglycerin as needed. Which prehospital management is most appropriate? A. Oxygen via venturi mask 24-35%, nebulized albuterol and ipratropium, IV NS KVO, IV corticosteroids B. Endotracheal intubation, 100% oxygen, IV NS KVO, nebulized albuterol and Atrovent, IV corticosteroids C. Albuterol via nebulizer with 100% oxygen, IV NS KVO D. Oxygen via nonrebreathing mask 15 LPM, IV NS with fluid challenge Answer: D 2. A 60-year-old male presents with sudden crushing chest pain radiating to left arm and jaw. Diaphoretic and pale. BP = 90/60, HR = 110, RR = 22, SpO2 = 94%. Most appropriate prehospital intervention? A. Aspirin 324 mg PO, nitroglycerin 0.4 mg SL, oxygen via NRB mask, IV access, transport immediately B. Morphine IV, 12-lead ECG, transport to nearest hospital without further intervention C. Apply CPAP at 10 cmH2O, furosemide IV, IV access D. Endotracheal intubation, lidocaine IV, transport Code 3 Answer: A """ # ── session helpers ─────────────────────────────────────────────────────────── def _logged_in(s): return s.get("logged_in", False) def _is_admin(s): return s.get("role") == "admin" def _welcome_html(session): role = session.get("role","user") name = session.get("full_name") or session.get("username","") bc = "role-admin" if role=="admin" else "role-user" bl = "🔑 Admin" if role=="admin" else "👤 User" return (f'
' f'👋 Welcome, {name}  | ' f'{bl}' f'' f'{datetime.datetime.now():%d %b %Y %H:%M}
') # ── auth handlers ───────────────────────────────────────────────────────────── def do_login(username, password, session): ok, msg, user = login_user(username, password) if ok: session.update({"logged_in": True, "username": user["username"], "role": user["role"], "full_name": user.get("full_name",""), "user_id": user["id"]}) return (msg, session, gr.update(visible=False), gr.update(visible=True), _welcome_html(session), gr.update(visible=_is_admin(session)), gr.update(visible=True)) return msg, session, gr.update(visible=True), gr.update(visible=False), \ "", gr.update(visible=False), gr.update(visible=False) def do_register(username, email, password, confirm, full_name, institution, session): if password != confirm: return "❌ Passwords do not match.", session ok, msg = register_user(username, email, password, full_name, institution) return msg, session def do_logout(session): if session.get("username"): log_activity(session.get("user_id"), session.get("username"), "logout", "") session.clear() return (session, gr.update(visible=True), gr.update(visible=False), "", gr.update(visible=False), gr.update(visible=False)) # ── Tab 1: generate from topic ──────────────────────────────────────────────── def handle_generate(topic, num_q, blooms, difficulty, want_word, want_pdf, want_excel, session): if not _logged_in(session): return "⚠️ Please log in first.", None, None, None, "" if not topic.strip(): return "⚠️ Please enter a topic name.", None, None, None, "" mcqs, source = generate_from_topic(topic, int(num_q), blooms, difficulty) if not mcqs: return "❌ Could not generate questions. Please try again.", None, None, None, "" log_activity(session.get("user_id"), session.get("username"), "generate_topic", f"{len(mcqs)} Qs · {topic} · {blooms}") note = ("⚡ AI was busy — template questions shown. Re-run for AI results.\n\n" if source == "template" else "✅ AI-generated questions:\n\n") preview = preview_mcqs(mcqs, f"Topic: {topic} | Bloom's: {blooms} | Difficulty: {difficulty}") title = f"MCQs: {topic}" w = make_word(mcqs, title) if want_word else None p = make_pdf(mcqs, title) if want_pdf else None e = make_excel(mcqs, title) if want_excel else None metrics = (f"📊 Questions: **{len(mcqs)}** · Bloom's: **{blooms}** · " f"Difficulty: **{difficulty}** · Source: **{source}**") return note + preview, w, p, e, metrics # ── Tab 2: upload + clone ───────────────────────────────────────────────────── def handle_upload_preview(file_obj, paste_text, session): """Step 1: parse uploaded file, show what was detected.""" if not _logged_in(session): return "⚠️ Please log in first.", session mcqs, err = [], "" if file_obj: mcqs, err = read_and_parse(file_obj) elif paste_text.strip(): from mcq_engine import _parse_plain mcqs = _parse_plain(paste_text.strip()) else: return "⚠️ Please upload a file or paste MCQs.", session if err: return f"❌ {err}", session if not mcqs: return ("❌ Could not detect MCQ structure.\n\n" "Ensure questions start with `1.` or `Q1.` and options with `A.` / `A)`"), session # Store in session for cloning step session["_mcqs"] = mcqs detected = sum(1 for m in mcqs if m.get("answer")) unknown = len(mcqs) - detected summary = f"✅ **{len(mcqs)} question(s) parsed**" if detected: summary += f" · **{detected}** answer(s) detected" if unknown: summary += f" · **{unknown}** answer(s) ⚠️ unknown (no formatting mark or key found)" summary += "\n\n" summary += preview_mcqs(mcqs) return summary, session def handle_clone(num_clones, blooms, want_word, want_pdf, want_excel, exam_title, session): """Step 2: clone the already-parsed MCQs.""" if not _logged_in(session): return "⚠️ Please log in first.", None, None, None, "" originals = session.get("_mcqs", []) if not originals: return "⚠️ Please parse/upload MCQs first (click Preview above).", None, None, None, "" clones = clone_mcqs(originals, int(num_clones), blooms) log_activity(session.get("user_id"), session.get("username"), "clone_mcqs", f"{len(originals)} orig → {len(clones)} clones") title = exam_title.strip() or "Cloned MCQs" w = make_word(clones, title) if want_word else None p = make_pdf(clones, title) if want_pdf else None e = make_excel(clones, title) if want_excel else None metrics = (f"📊 Original: **{len(originals)}** · " f"Clones: **{len(clones)}** · " f"Bloom's: **{blooms}**") return preview_mcqs(clones, "Generated Clones"), w, p, e, metrics # ── admin handlers (unchanged) ──────────────────────────────────────────────── def admin_get_stats(session): if not _is_admin(session): return "❌ Admin only." s = get_stats() return (f"## 📊 Portal Statistics\n|Metric|Value|\n|---|---|\n" f"|Total Users|**{s['total']}**|\n|Admins|**{s['admins']}**|\n" f"|Active|**{s['active']}**|\n|New Today|**{s['new_today']}**|\n" f"|Logins Today|**{s['logins_today']}**|") def admin_get_users(session): if not _is_admin(session): return pd.DataFrame() users = get_all_users() if not users: return pd.DataFrame() df = pd.DataFrame(users)[["id","username","email","full_name","institution", "role","is_active","created_at","last_login"]] df.columns = ["ID","Username","Email","Full Name","Institution", "Role","Active","Registered","Last Login"] df["Active"] = df["Active"].map({1:"✅ Yes", 0:"❌ No"}) df["Last Login"] = df["Last Login"].fillna("Never") return df def admin_toggle(uid_str, activate, session): if not _is_admin(session): return "❌ Admin only.", admin_get_users(session) try: msg = toggle_user_active(int(uid_str), activate) return msg, admin_get_users(session) except ValueError: return "❌ Enter a numeric User ID.", admin_get_users(session) def admin_change_role(uid_str, role, session): if not _is_admin(session): return "❌ Admin only.", admin_get_users(session) try: msg = change_user_role(int(uid_str), role) return msg, admin_get_users(session) except ValueError: return "❌ Enter a numeric User ID.", admin_get_users(session) def admin_delete(uid_str, session): if not _is_admin(session): return "❌ Admin only.", admin_get_users(session) try: msg = delete_user(int(uid_str)) return msg, admin_get_users(session) except ValueError: return "❌ Enter a numeric User ID.", admin_get_users(session) def admin_get_log(session): if not _is_admin(session): return pd.DataFrame() logs = get_activity_log(200) if not logs: return pd.DataFrame() df = pd.DataFrame(logs)[["timestamp","username","action","detail"]] df.columns = ["Timestamp","User","Action","Detail"] df["Timestamp"] = df["Timestamp"].str[:19].str.replace("T"," ") return df # ══════════════════════════════════════════════════════════════════════════════ # GRADIO UI # ══════════════════════════════════════════════════════════════════════════════ def create_app(): with gr.Blocks(css=CSS, title="EduClone AI Portal") as demo: session_state = gr.State({}) gr.HTML(BANNER_HTML) # ── Login / Register ────────────────────────────────────────────────── with gr.Column(visible=True) as login_panel: with gr.Tabs(): with gr.TabItem("🔐 Login"): with gr.Column(elem_classes=["auth-card"]): gr.HTML("

Sign in to EduClone AI

") li_user = gr.Textbox(label="Username or Email") li_pass = gr.Textbox(label="Password", type="password") li_btn = gr.Button("🔐 Login", variant="primary", size="lg") li_msg = gr.Markdown() with gr.TabItem("📝 Register"): with gr.Column(elem_classes=["auth-card"]): gr.HTML("

Create your account

") rg_name = gr.Textbox(label="Full Name") rg_inst = gr.Textbox(label="Institution / Organisation") rg_user = gr.Textbox(label="Username (3–30 chars, no spaces)") rg_email = gr.Textbox(label="Email Address") rg_pass = gr.Textbox(label="Password (8+ chars, 1 uppercase, 1 number)", type="password") rg_conf = gr.Textbox(label="Confirm Password", type="password") rg_btn = gr.Button("📝 Create Account", variant="primary", size="lg") rg_msg = gr.Markdown() # ── Main Portal ─────────────────────────────────────────────────────── with gr.Column(visible=False) as main_portal: welcome_html = gr.HTML() logout_btn = gr.Button("🚪 Logout", size="sm", variant="secondary") # ── Admin Panel ─────────────────────────────────────────────────── with gr.Column(visible=False) as admin_tabs: gr.HTML("

🔑 Admin Panel

") with gr.Tabs(): with gr.TabItem("📊 Dashboard"): dash_btn = gr.Button("🔄 Refresh Stats", variant="secondary") dash_out = gr.Markdown() with gr.TabItem("👥 User Management"): refresh_users_btn = gr.Button("🔄 Refresh List", variant="secondary") users_table = gr.DataFrame(interactive=False, wrap=True) gr.Markdown("**Actions — enter User ID:**") with gr.Row(): action_uid = gr.Textbox(label="User ID", scale=1, placeholder="e.g. 3") action_role = gr.Dropdown(choices=["user","admin"], value="user", label="Set Role", scale=1) with gr.Row(): btn_activate = gr.Button("✅ Activate", variant="secondary") btn_deactivate = gr.Button("❌ Deactivate", variant="secondary") btn_set_role = gr.Button("🔄 Set Role", variant="secondary") btn_del_user = gr.Button("🗑️ Delete", variant="stop") action_msg = gr.Markdown() with gr.TabItem("📋 Activity Log"): refresh_log_btn = gr.Button("🔄 Refresh", variant="secondary") log_table = gr.DataFrame(interactive=False, wrap=True) # ── USER SECTION — Tab 1 & 2 ───────────────────────────────────── with gr.Column(visible=False) as user_tabs: with gr.Tabs(): # ══ TAB 1: Generate from Topic ═══════════════════════════ with gr.TabItem("📝 Generate from Topic"): gr.HTML(TAB1_HINT) with gr.Row(): with gr.Column(scale=1): t1_topic = gr.Textbox( label="Topic / Subject Name", placeholder="e.g. Mitochondria · Supply Chain · Newton's Laws", lines=2) t1_num = gr.Slider(1, 10, value=5, step=1, label="Number of Questions") t1_blooms = gr.Dropdown( choices=list(BLOOMS.keys()), value="Mixed (All)", label="📚 Bloom's Taxonomy Level") t1_diff = gr.Radio( choices=["Easy","Medium","Hard","Mixed"], value="Mixed", label="Difficulty") gr.Markdown("**Download formats:**") with gr.Row(): t1_word = gr.Checkbox(label="📄 Word", value=True) t1_pdf = gr.Checkbox(label="📑 PDF", value=True) t1_excel = gr.Checkbox(label="📊 Excel", value=False) t1_btn = gr.Button("🚀 Generate MCQs", variant="primary", size="lg") with gr.Column(scale=2): t1_preview = gr.Markdown(label="Preview") with gr.Row(elem_classes=["dl-row"]): t1_w = gr.File(label="📄 Word") t1_p = gr.File(label="📑 PDF") t1_e = gr.File(label="📊 Excel") t1_metrics = gr.Markdown() # ══ TAB 2: Upload & Clone ═════════════════════════════════ with gr.TabItem("🔁 Upload & Clone"): gr.HTML(TAB2_HINT) with gr.Row(): with gr.Column(scale=1): gr.Markdown("### Step 1 — Upload your MCQs") t2_file = gr.File( label="Upload File (.docx / .pdf / .txt) — formatting detected from .docx", file_types=[".docx",".doc",".pdf",".txt"]) t2_paste = gr.Textbox( label="Or paste plain-text MCQs here", lines=10, value=SAMPLE_MCQS) t2_preview_btn = gr.Button("🔍 Parse & Preview", variant="secondary", size="lg") gr.Markdown("---\n### Step 2 — Clone settings") t2_clones = gr.Slider(1, 3, value=2, step=1, label="Clones per Question") t2_blooms = gr.Dropdown( choices=list(BLOOMS.keys()), value="Mixed (All)", label="📚 Bloom's Level for Clones") t2_title = gr.Textbox( label="Exam / Output Title", value="Cloned MCQs") gr.Markdown("**Download formats:**") with gr.Row(): t2_word = gr.Checkbox(label="📄 Word", value=True) t2_pdf = gr.Checkbox(label="📑 PDF", value=True) t2_excel = gr.Checkbox(label="📊 Excel", value=False) t2_clone_btn = gr.Button("🔁 Generate Clones", variant="primary", size="lg") with gr.Column(scale=2): t2_preview = gr.Markdown(label="Parsed / Clone Preview") with gr.Row(elem_classes=["dl-row"]): t2_w = gr.File(label="📄 Word") t2_p = gr.File(label="📑 PDF") t2_e = gr.File(label="📊 Excel") t2_metrics = gr.Markdown() # ── Wire events ─────────────────────────────────────────────────────── # Auth li_btn.click(fn=do_login, inputs=[li_user, li_pass, session_state], outputs=[li_msg, session_state, login_panel, main_portal, welcome_html, admin_tabs, user_tabs]) li_pass.submit(fn=do_login, inputs=[li_user, li_pass, session_state], outputs=[li_msg, session_state, login_panel, main_portal, welcome_html, admin_tabs, user_tabs]) rg_btn.click(fn=do_register, inputs=[rg_user, rg_email, rg_pass, rg_conf, rg_name, rg_inst, session_state], outputs=[rg_msg, session_state]) logout_btn.click(fn=do_logout, inputs=[session_state], outputs=[session_state, login_panel, main_portal, welcome_html, admin_tabs, user_tabs]) # Admin dash_btn.click(fn=admin_get_stats, inputs=[session_state], outputs=[dash_out]) refresh_users_btn.click(fn=admin_get_users, inputs=[session_state], outputs=[users_table]) btn_activate.click(fn=lambda u,s: admin_toggle(u,True,s), inputs=[action_uid,session_state], outputs=[action_msg,users_table]) btn_deactivate.click(fn=lambda u,s: admin_toggle(u,False,s), inputs=[action_uid,session_state], outputs=[action_msg,users_table]) btn_set_role.click(fn=admin_change_role, inputs=[action_uid,action_role,session_state], outputs=[action_msg,users_table]) btn_del_user.click(fn=admin_delete, inputs=[action_uid,session_state], outputs=[action_msg,users_table]) refresh_log_btn.click(fn=admin_get_log, inputs=[session_state], outputs=[log_table]) # Tab 1 — Generate t1_btn.click(fn=handle_generate, inputs=[t1_topic, t1_num, t1_blooms, t1_diff, t1_word, t1_pdf, t1_excel, session_state], outputs=[t1_preview, t1_w, t1_p, t1_e, t1_metrics]) # Tab 2 — Parse then Clone (two separate buttons) t2_preview_btn.click(fn=handle_upload_preview, inputs=[t2_file, t2_paste, session_state], outputs=[t2_preview, session_state]) t2_clone_btn.click(fn=handle_clone, inputs=[t2_clones, t2_blooms, t2_word, t2_pdf, t2_excel, t2_title, session_state], outputs=[t2_preview, t2_w, t2_p, t2_e, t2_metrics]) return demo if __name__ == "__main__": app = create_app() app.launch(server_name="0.0.0.0", server_port=7860, share=False, show_error=True)