Awab-Elsadig commited on
Commit
94b3af8
·
1 Parent(s): ceeaf3d

feat: upload question diagrams as questionFileId before batch save

Browse files

- Upload each question's first image to /question-bank/questions/upload-image
before the batch create, so the returned fileId is set as questionFileId
on the question payload — making images visible in the frontend
- Add model answer rendered view with KaTeX toggle (Edit/Done pattern)
- Fix model answer textarea hidden by q-text CSS class
- Dark-mode styles for answer panel

Files changed (3) hide show
  1. .env.example +4 -8
  2. main.py +617 -113
  3. requirements.txt +2 -0
.env.example CHANGED
@@ -1,8 +1,4 @@
1
- # Choose your AI provider: "groq" or "gemini"
2
- AI_PROVIDER=groq
3
-
4
- # Groq API key (get from console.groq.com)
5
- GROQ_API_KEY=your_groq_api_key_here
6
-
7
- # Google Gemini API key (get from aistudio.google.com — NOT Google Cloud Console)
8
- GOOGLE_API_KEY=your_google_ai_studio_key_here
 
1
+ # EduVerse backend — instructor credentials for dev (will be replaced with proper auth later)
2
+ EDUVERSE_API_URL=https://eduverse-team-eduverse-backend.hf.space
3
+ EDUVERSE_EMAIL=instructor@example.com
4
+ EDUVERSE_PASSWORD=your_password_here
 
 
 
 
main.py CHANGED
@@ -2,6 +2,7 @@ import asyncio
2
  import base64
3
  import io
4
  import json
 
5
  import re
6
  import shutil
7
  import tempfile
@@ -10,7 +11,11 @@ from datetime import datetime, timezone
10
  from pathlib import Path
11
  from typing import Optional
12
 
 
 
13
  from fastapi import FastAPI, File, Form, HTTPException, Request, UploadFile
 
 
14
  from fastapi.middleware.cors import CORSMiddleware
15
  from fastapi.responses import FileResponse, HTMLResponse, Response
16
 
@@ -28,6 +33,12 @@ SAVED_PDF_NAME = OUTPUT_DIR / "saved_textbook_name.txt"
28
  BUNDLED_PDF = (Path(__file__).parent / "../../Reference and Solution Manual/Modern Control Systems-12 Edition.pdf").resolve()
29
  BUNDLED_PDF_NAME = "Modern Control Systems-12 Edition.pdf"
30
 
 
 
 
 
 
 
31
 
32
  def _active_pdf() -> Optional[Path]:
33
  """Return the PDF to use: user-uploaded first, then the bundled textbook."""
@@ -37,19 +48,44 @@ def _active_pdf() -> Optional[Path]:
37
  return BUNDLED_PDF
38
  return None
39
 
40
- GEMINI_PROMPT = """\
41
- You are extracting end-of-chapter problems from a Control Systems textbook (Modern Control Systems, 12th edition).
42
 
43
- The text was extracted via OCR from a scanned PDF and may contain artifacts, merged columns, and garbled spacing. Identify every distinct problem.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
  Return a JSON array where each object has exactly these fields:
46
- - "question_number": string — the problem label as it appears (e.g. "P1.1", "AP3.4", "DP5.1", "CP2.1")
47
  - "question": string — complete question text, cleaned of OCR errors. Remove figure captions and page headers. Fix broken words from column wrapping. Format all math using LaTeX: inline with $...$ (e.g. $x_1$, $\\omega_n$, $K > 0$), display with $$...$$.
48
  - "page": number — page where the problem starts (use the --- PAGE N --- markers)
 
 
 
49
  - "has_diagram": boolean — true if the question references a Figure, asks to sketch a diagram or block diagram, or involves a circuit
50
  - "figure_reference": string or null — specific figure label when present (e.g. "Figure 13.18", "Fig. P1.2"), otherwise null
51
  - "exam_ready": boolean — true if suitable for a university exam. Mark false for: pure discussion/describe questions, problems entirely dependent on a figure students won't have, or questions too open-ended to grade objectively.
52
  - "exam_notes": string or null — if exam_ready is false, a brief reason (e.g. "discussion only", "requires Figure P1.2", "open-ended design"). If exam_ready is true, use null.
 
53
 
54
  Return ONLY a valid JSON array wrapped in ```json fences. No explanation.
55
 
@@ -66,6 +102,7 @@ _HTML = """<!DOCTYPE html>
66
  <script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.js"></script>
67
  <script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/contrib/auto-render.min.js"
68
  onload="onKatexReady()"></script>
 
69
  <style>
70
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
71
  body { font-family: system-ui, sans-serif; background: #f8fafc; color: #1e293b; line-height: 1.5; }
@@ -90,6 +127,10 @@ _HTML = """<!DOCTYPE html>
90
  /* Config bar */
91
  .config-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; }
92
  .config-bar input[type=number] { width: 68px; padding: 6px 8px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 0.85rem; font-family: inherit; text-align: center; }
 
 
 
 
93
  .config-bar input:focus { outline: none; border-color: #2563eb; }
94
  .config-sep { color: #94a3b8; font-size: 0.85rem; }
95
  #extract-status { font-size: 0.78rem; color: #64748b; }
@@ -97,14 +138,7 @@ _HTML = """<!DOCTYPE html>
97
  .spin { display: inline-block; width: 14px; height: 14px; border: 2px solid rgba(255,255,255,0.4); border-top-color: white; border-radius: 50%; animation: spin 0.6s linear infinite; }
98
  @keyframes spin { to { transform: rotate(360deg); } }
99
  /* PDF picker */
100
- .pdf-picker-btn { display: inline-flex; align-items: center; gap: 6px; padding: 6px 13px; background: #f8fafc; border: 1.5px dashed #cbd5e1; border-radius: 6px; font-size: 0.78rem; font-weight: 600; color: #475569; cursor: pointer; transition: border-color 0.15s, background 0.15s, color 0.15s; user-select: none; }
101
- .pdf-picker-btn:hover { border-color: #2563eb; color: #2563eb; background: #eff6ff; }
102
- .pdf-ready-pill { display: none; align-items: center; gap: 7px; background: #f0fdf4; border: 1px solid #bbf7d0; border-radius: 6px; padding: 5px 11px; font-size: 0.78rem; color: #166534; max-width: 340px; }
103
- .pdf-ready-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 220px; }
104
- .pdf-pending-pill { display: none; align-items: center; gap: 7px; background: #fffbeb; border: 1px solid #fde68a; border-radius: 6px; padding: 5px 11px; font-size: 0.78rem; color: #92400e; max-width: 380px; }
105
- .pdf-pending-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 180px; }
106
- .pdf-change-link { font-size: 0.7rem; color: #64748b; text-decoration: underline; cursor: pointer; flex-shrink: 0; }
107
- .pdf-change-link:hover { color: #2563eb; }
108
  /* Workflow grid */
109
  .workflow-grid { display: flex; gap: 12px; flex-wrap: wrap; margin-bottom: 12px; }
110
  .workflow-grid .card { flex: 1; min-width: 260px; margin-bottom: 0; }
@@ -123,8 +157,21 @@ _HTML = """<!DOCTYPE html>
123
  /* Question sections */
124
  .q-section { margin-bottom: 18px; }
125
  .q-section-title { font-size: 0.8rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.06em; color: #475569; margin: 10px 0 8px; }
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  /* Problem cards */
127
- .q-card { background: white; border: 1px solid #e2e8f0; border-radius: 8px; padding: 14px 18px; margin-bottom: 10px; transition: border-color 0.15s; cursor: default; }
128
  .q-card.active-card { border-color: #2563eb; box-shadow: 0 0 0 4px #bfdbfe; background: #f8fbff; }
129
  .q-card.flash { border-color: #4ade80; box-shadow: 0 0 0 3px #f0fdf4; }
130
  .q-header { display: flex; align-items: center; gap: 7px; flex-wrap: wrap; margin-bottom: 10px; }
@@ -142,6 +189,10 @@ _HTML = """<!DOCTYPE html>
142
  .exam-toggle { display: inline-flex; align-items: center; gap: 5px; font-size: 0.73rem; color: #64748b; cursor: pointer; user-select: none; margin-left: auto; }
143
  .exam-toggle input[type=checkbox] { cursor: pointer; }
144
  .q-notes { font-size: 0.71rem; color: #94a3b8; margin-top: 5px; font-style: italic; }
 
 
 
 
145
  .chips-row { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; }
146
  .img-chip { display: inline-flex; align-items: center; gap: 5px; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 6px; padding: 3px 8px 3px 3px; font-size: 0.72rem; color: #475569; }
147
  .img-chip img { width: 56px; height: 56px; object-fit: cover; border-radius: 4px; cursor: zoom-in; border: 1px solid #cbd5e1; }
@@ -150,9 +201,23 @@ _HTML = """<!DOCTYPE html>
150
  .img-chip-remove { background: none; border: none; cursor: pointer; color: #94a3b8; font-size: 1rem; line-height: 1; padding: 0; }
151
  .img-chip-remove:hover { color: #dc2626; }
152
  /* Export bar */
153
- .export-bar { position: fixed; bottom: 0; left: 0; right: 0; background: white; border-top: 1px solid #e2e8f0; padding: 10px 24px; display: none; justify-content: space-between; align-items: center; z-index: 100; }
154
  .export-bar-left { display: flex; align-items: center; gap: 14px; font-size: 0.82rem; color: #64748b; }
155
  .paste-hint { font-size: 0.75rem; color: #2563eb; background: #eff6ff; padding: 2px 8px; border-radius: 4px; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  /* Toast */
157
  .toast { position: fixed; bottom: 60px; left: 50%; transform: translateX(-50%); background: #1e293b; color: white; padding: 7px 16px; border-radius: 6px; font-size: 0.78rem; z-index: 200; pointer-events: none; opacity: 0; transition: opacity 0.2s; }
158
  .toast.show { opacity: 1; }
@@ -181,10 +246,7 @@ _HTML = """<!DOCTYPE html>
181
  body.dark .config-sep { color: #475569; }
182
  body.dark #extract-status { color: #64748b; }
183
  body.dark .config-bar input[type=number] { background: #0f172a; border-color: #334155; color: #e2e8f0; }
184
- body.dark .pdf-picker-btn { background: #1e293b; border-color: #475569; color: #94a3b8; }
185
- body.dark .pdf-picker-btn:hover { border-color: #2563eb; color: #93c5fd; background: #1e3a5f; }
186
  body.dark .pdf-change-link { color: #64748b; }
187
- body.dark .pdf-change-link:hover { color: #93c5fd; }
188
  body.dark .info-box { background: #1e3a5f; border-color: #1d4ed8; color: #93c5fd; }
189
  body.dark .error-box { background: #450a0a; border-color: #7f1d1d; color: #f87171; }
190
  body.dark .step-label { color: #64748b; }
@@ -204,6 +266,8 @@ _HTML = """<!DOCTYPE html>
204
  body.dark .q-rendered { color: #e2e8f0; }
205
  body.dark .q-text { background: #0f172a; border-color: #334155; color: #e2e8f0; }
206
  body.dark .q-text:focus { background: #0f172a; }
 
 
207
  body.dark .q-notes { color: #475569; }
208
  body.dark .exam-toggle { color: #64748b; }
209
  body.dark .img-chip { background: #0f172a; border-color: #334155; color: #94a3b8; }
@@ -231,54 +295,58 @@ _HTML = """<!DOCTYPE html>
231
 
232
  <div id="error-box" class="error-box"></div>
233
 
 
 
234
  <!-- ── Config bar ── -->
235
- <div class="card" style="margin-bottom:16px;">
236
  <div class="config-bar">
237
- <!-- PDF picker -->
238
- <input type="file" id="pdf-file-input" accept=".pdf" style="display:none;" onchange="handlePdfSelect(this)">
239
- <label id="pdf-picker-btn" class="pdf-picker-btn" for="pdf-file-input">
240
- <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
241
  Choose PDF
242
  </label>
243
- <div id="pdf-ready-pill" class="pdf-ready-pill">
244
- <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
245
  <span id="pdf-ready-name" class="pdf-ready-name"></span>
246
- <span class="pdf-change-link" onclick="document.getElementById('pdf-file-input').click()">Change</span>
247
- </div>
248
- <div id="pdf-pending-pill" class="pdf-pending-pill">
249
- <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
250
  <span id="pdf-pending-name" class="pdf-pending-name"></span>
251
  <span style="color:#a16207;font-size:0.68rem;flex-shrink:0;">uploads on Extract</span>
252
- <span class="pdf-change-link" onclick="document.getElementById('pdf-file-input').click()">Change</span>
253
- </div>
254
- <!-- Divider -->
255
- <span class="config-sep">|</span>
256
- <!-- Pages -->
257
- <span style="font-size:0.78rem;color:#64748b;">Pages</span>
258
- <input id="tb-start" type="number" min="1" placeholder="Start">
259
- <span class="config-sep">&ndash;</span>
260
- <input id="tb-end" type="number" min="1" placeholder="End">
261
- <!-- Extract -->
262
- <button id="extract-btn" class="btn btn-primary btn-sm" onclick="startExtract()">Extract</button>
263
- <span id="extract-status"></span>
 
 
 
264
  </div>
265
  </div>
266
 
267
- <!-- ── Workflow (always available) ── -->
268
- <div id="workflow-section">
269
  <div class="workflow-grid">
270
  <div class="card">
271
  <div class="step-label"><span class="step-num">1</span> Copy &amp; paste into <a href="https://gemini.google.com" target="_blank" style="color:#2563eb;">gemini.google.com</a></div>
272
  <div class="info-box">Copies the full prompt + your extracted text in one click.</div>
273
  <div style="display:flex;gap:8px;flex-wrap:wrap;">
274
- <button id="copy-btn" class="btn btn-primary btn-sm" onclick="copyForGemini()">Copy prompt + text</button>
275
- <button id="download-raw-btn" class="btn btn-secondary btn-sm" onclick="downloadRawText()">Download .txt</button>
276
  </div>
277
  </div>
278
  <div class="card">
279
  <div class="step-label"><span class="step-num">2</span> Paste Gemini&rsquo;s JSON response</div>
280
  <textarea id="json-paste" class="paste-area" placeholder="Paste here (with or without the ```json fences)..."></textarea>
281
- <button id="load-json-btn" class="btn btn-success btn-sm" onclick="loadFromJSON()">Load Problems &rarr;</button>
282
  </div>
283
  </div>
284
  <div id="workflow-busy" class="workflow-busy">
@@ -297,6 +365,11 @@ _HTML = """<!DOCTYPE html>
297
 
298
  <!-- ── Review (appears after loading JSON) ── -->
299
  <div id="review-section" style="display:none;">
 
 
 
 
 
300
  <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px;flex-wrap:wrap;gap:8px;">
301
  <p id="review-meta" style="font-size:0.82rem;color:#64748b;"></p>
302
  </div>
@@ -308,6 +381,22 @@ _HTML = """<!DOCTYPE html>
308
  </div>
309
  </div>
310
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
311
  <!-- Export bar -->
312
  <div id="export-bar" class="export-bar">
313
  <div class="export-bar-left">
@@ -317,8 +406,9 @@ _HTML = """<!DOCTYPE html>
317
  <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
318
  <input id="chapter-export" type="number" min="1" placeholder="Chapter" style="width:88px;padding:6px 8px;border:1px solid #cbd5e1;border-radius:6px;font-size:0.78rem;">
319
  <input id="teammate-export" type="text" placeholder="Teammate (optional)" style="width:160px;padding:6px 8px;border:1px solid #cbd5e1;border-radius:6px;font-size:0.78rem;">
320
- <button class="btn btn-secondary btn-sm" onclick="exportChapterZip(this)">Export chapter ZIP</button>
321
- <button class="btn btn-success btn-sm" onclick="exportJSON()">Export JSON</button>
 
322
  </div>
323
  </div>
324
 
@@ -336,34 +426,40 @@ _HTML = """<!DOCTYPE html>
336
  var activeFilter = 'all';
337
  var activeCardIdx = null;
338
  var pendingPdfFile = null;
 
 
 
 
 
 
 
 
 
339
 
340
  // ── PDF state ─────────────────────────────────────────────────────────────
341
 
342
  function initPdfState() {
343
- fetch('/api/pdf-info').then(function(r) { return r.json(); }).then(function(d) {
344
- if (d.saved && d.name) { showPdfReady(d.name); }
345
- }).catch(function() {});
346
  }
347
 
348
  function handlePdfSelect(input) {
349
  var file = input.files && input.files[0];
350
  if (!file) return;
351
  pendingPdfFile = file;
352
- document.getElementById('pdf-picker-btn').style.display = 'none';
353
- document.getElementById('pdf-ready-pill').style.display = 'none';
354
- var pill = document.getElementById('pdf-pending-pill');
355
- pill.style.display = 'inline-flex';
356
- document.getElementById('pdf-pending-name').textContent = file.name;
357
  input.value = '';
 
358
  }
359
 
360
  function showPdfReady(name) {
361
  pendingPdfFile = null;
362
- document.getElementById('pdf-picker-btn').style.display = 'none';
363
  document.getElementById('pdf-pending-pill').style.display = 'none';
364
- var pill = document.getElementById('pdf-ready-pill');
365
- pill.style.display = 'inline-flex';
366
- document.getElementById('pdf-ready-name').textContent = name;
367
  }
368
 
369
  // ── Dark mode ─────────────────────────────────────────────────────────────
@@ -380,13 +476,25 @@ _HTML = """<!DOCTYPE html>
380
  try { localStorage.setItem('dm', !isDark ? '1' : '0'); } catch(e) {}
381
  }
382
 
 
 
 
 
 
 
 
 
 
 
383
  window.addEventListener('DOMContentLoaded', function() {
384
  initPdfState();
 
385
  try {
386
  var saved = localStorage.getItem('dm');
387
  var prefersDark = saved !== null ? saved === '1' : window.matchMedia('(prefers-color-scheme: dark)').matches;
388
  applyDark(prefersDark);
389
  } catch(e) {}
 
390
  });
391
 
392
  var KATEX_OPTS = {
@@ -416,6 +524,7 @@ _HTML = """<!DOCTYPE html>
416
 
417
  async function startExtract() {
418
  hideError();
 
419
  var tbStartRaw = document.getElementById('tb-start').value.trim();
420
  var tbEndRaw = document.getElementById('tb-end').value.trim();
421
  var tbStart = parseInt(tbStartRaw, 10);
@@ -446,7 +555,7 @@ _HTML = """<!DOCTYPE html>
446
 
447
  var imgs = data.images || [];
448
  document.getElementById('extract-status').textContent =
449
- '\\u2713 ' + (data.char_count || 0).toLocaleString() + ' chars \\u00b7 ' + imgs.length + ' images';
450
  showToast(
451
  isReextract
452
  ? 'Re-extraction complete. Text and images refreshed.'
@@ -485,7 +594,7 @@ _HTML = """<!DOCTYPE html>
485
  document.getElementById('images-toggle-label').textContent = 'Page images (' + imgs.length + ')';
486
  toggle.style.display = 'inline-flex';
487
  document.getElementById('images-section').style.display = 'none';
488
- document.getElementById('images-arrow').textContent = '\\u25ba';
489
  imgs.forEach(function(img) {
490
  var src = '/output/' + img.filename;
491
  var wrapper = document.createElement('div');
@@ -512,7 +621,7 @@ _HTML = """<!DOCTYPE html>
512
  var arrow = document.getElementById('images-arrow');
513
  var open = section.style.display !== 'none';
514
  section.style.display = open ? 'none' : 'block';
515
- arrow.textContent = open ? '\\u25ba' : '\\u25bc';
516
  }
517
 
518
  function openImageModal(src) {
@@ -564,25 +673,29 @@ _HTML = """<!DOCTYPE html>
564
  problems = parsed.map(function(q) {
565
  var figureReference = q.figure_reference ? String(q.figure_reference) : detectFigureReference(String(q.question || ''));
566
  return {
567
- question_number: String(q.question_number || ''),
568
- question: String(q.question || ''),
569
- page: q.page || null,
570
- has_diagram: Boolean(q.has_diagram),
 
 
 
571
  figure_reference: figureReference || null,
572
- exam_ready: q.exam_ready !== false,
573
- exam_notes: q.exam_notes || null,
574
- answer: q.answer || null,
575
- images: [],
576
  };
577
  });
578
  var ready = problems.filter(function(q) { return q.exam_ready; }).length;
579
  document.getElementById('review-meta').textContent =
580
- problems.length + ' problems loaded \\u00b7 ' + ready + ' exam ready';
581
  updateFilterCounts();
582
  renderProblems();
583
  var rs = document.getElementById('review-section');
584
  rs.style.display = 'block';
585
  document.getElementById('export-bar').style.display = 'flex';
 
586
  setTimeout(function() { rs.scrollIntoView({ behavior: 'smooth', block: 'start' }); }, 80);
587
  } catch(e) { showError('Could not parse JSON: ' + e.message); }
588
  }
@@ -617,27 +730,21 @@ _HTML = """<!DOCTYPE html>
617
 
618
  // ── Problems ──────────────────────────────────────────────────────────────
619
 
620
- var TYPE_LABELS = {
621
- AP: 'Advanced Problems',
622
- P: 'Problems',
623
- E: 'Exercises',
624
- DP: 'Design Problems',
625
- CP: 'Computer Problems',
626
- EP: 'Extension Problems',
627
  };
 
628
 
629
- var TYPE_ORDER = ['AP', 'P', 'E', 'DP', 'CP', 'EP', 'OTHER'];
630
-
631
- function getQuestionTypeCode(questionNumber) {
632
- var qn = String(questionNumber || '').trim().toUpperCase();
633
- var m = qn.match(/^([A-Z]+)\s*\d/);
634
- if (!m) return 'OTHER';
635
- return m[1];
636
  }
637
 
638
- function getQuestionTypeLabel(typeCode) {
639
- if (TYPE_LABELS[typeCode]) return TYPE_LABELS[typeCode];
640
- return typeCode === 'OTHER' ? 'Other' : (typeCode + ' Questions');
641
  }
642
 
643
  function detectFigureReference(text) {
@@ -647,14 +754,6 @@ _HTML = """<!DOCTYPE html>
647
  return 'Figure ' + m[1];
648
  }
649
 
650
- function getSortedTypeCodes(grouped) {
651
- var known = TYPE_ORDER.filter(function(code) { return grouped[code] && grouped[code].length; });
652
- var unknown = Object.keys(grouped).filter(function(code) {
653
- return TYPE_ORDER.indexOf(code) === -1 && grouped[code] && grouped[code].length;
654
- }).sort();
655
- return known.concat(unknown);
656
- }
657
-
658
  function renderProblems() {
659
  var list = document.getElementById('problems-list');
660
  list.innerHTML = '';
@@ -666,19 +765,21 @@ _HTML = """<!DOCTYPE html>
666
 
667
  var grouped = {};
668
  problems.forEach(function(q, idx) {
669
- var typeCode = getQuestionTypeCode(q.question_number);
670
  if (!grouped[typeCode]) grouped[typeCode] = [];
671
  grouped[typeCode].push({ question: q, index: idx });
672
  });
673
 
674
- getSortedTypeCodes(grouped).forEach(function(typeCode) {
 
 
675
  var section = document.createElement('section');
676
  section.className = 'q-section';
677
  section.dataset.type = typeCode;
678
 
679
  var title = document.createElement('div');
680
  title.className = 'q-section-title';
681
- title.textContent = getQuestionTypeLabel(typeCode) + ' (' + grouped[typeCode].length + ')';
682
  section.appendChild(title);
683
 
684
  grouped[typeCode].forEach(function(item) {
@@ -690,6 +791,27 @@ _HTML = """<!DOCTYPE html>
690
  applyFilter();
691
  }
692
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
693
  function buildCard(q, idx) {
694
  var card = document.createElement('div');
695
  card.className = 'q-card';
@@ -706,21 +828,50 @@ _HTML = """<!DOCTYPE html>
706
  var pg = document.createElement('span'); pg.className = 'badge badge-page';
707
  pg.textContent = 'Page ' + q.page; header.appendChild(pg);
708
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
709
  if (q.figure_reference || q.has_diagram) {
710
  var dg = document.createElement('span'); dg.className = 'badge badge-warn';
711
- dg.textContent = '\\u26a0 ' + (q.figure_reference || 'diagram'); header.appendChild(dg);
 
 
 
 
 
712
  }
713
  var eb = document.createElement('span');
714
  eb.id = 'exam-badge-' + idx;
715
  eb.className = 'badge ' + (q.exam_ready ? 'badge-ready' : 'badge-skip');
716
- eb.textContent = q.exam_ready ? '\\u2713 exam ready' : '\\u00d7 skip';
 
 
717
  header.appendChild(eb);
718
  var targetPill = document.createElement('span');
719
  targetPill.className = 'paste-target-pill';
720
  targetPill.textContent = 'Ctrl+V target';
721
  header.appendChild(targetPill);
722
  var sp = document.createElement('div'); sp.style.flex = '1'; header.appendChild(sp);
723
- var del = document.createElement('button'); del.className = 'btn btn-danger btn-sm'; del.textContent = 'Delete';
 
724
  del.addEventListener('click', (function(i) {
725
  return function(e) { e.stopPropagation(); problems.splice(i,1); updateFilterCounts(); renderProblems(); };
726
  })(idx));
@@ -739,8 +890,10 @@ _HTML = """<!DOCTYPE html>
739
  // Controls
740
  var controls = document.createElement('div'); controls.className = 'q-controls';
741
 
742
- var editBtn = document.createElement('button'); editBtn.className = 'btn btn-secondary btn-xs'; editBtn.textContent = 'Edit';
743
- var doneBtn = document.createElement('button'); doneBtn.className = 'btn btn-primary btn-xs'; doneBtn.textContent = 'Done'; doneBtn.style.display = 'none';
 
 
744
  editBtn.addEventListener('click', function(e) {
745
  e.stopPropagation(); renderDiv.style.display = 'none'; ta.style.display = 'block'; ta.focus();
746
  editBtn.style.display = 'none'; doneBtn.style.display = 'inline-flex';
@@ -770,7 +923,8 @@ _HTML = """<!DOCTYPE html>
770
  };
771
  })(idx));
772
  card.appendChild(fi);
773
- var attachBtn = document.createElement('button'); attachBtn.className = 'btn btn-secondary btn-xs'; attachBtn.textContent = '+ Attach diagram';
 
774
  attachBtn.addEventListener('click', function(e) { e.stopPropagation(); fi.click(); });
775
  controls.appendChild(attachBtn);
776
 
@@ -782,7 +936,13 @@ _HTML = """<!DOCTYPE html>
782
  problems[i].exam_ready = e.target.checked;
783
  cardEl.dataset.examReady = e.target.checked ? '1' : '0';
784
  var badge = document.getElementById('exam-badge-' + i);
785
- if (badge) { badge.className = 'badge ' + (e.target.checked ? 'badge-ready' : 'badge-skip'); badge.textContent = e.target.checked ? '\\u2713 exam ready' : '\\u00d7 skip'; }
 
 
 
 
 
 
786
  applyFilter(); updateFilterCounts();
787
  };
788
  })(idx, card));
@@ -797,6 +957,57 @@ _HTML = """<!DOCTYPE html>
797
  notes.textContent = 'Note: ' + q.exam_notes; card.appendChild(notes);
798
  }
799
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
800
  // Image chips
801
  var chipsRow = document.createElement('div'); chipsRow.className = 'chips-row';
802
  chipsRow.id = 'chips-' + idx;
@@ -807,13 +1018,31 @@ _HTML = """<!DOCTYPE html>
807
 
808
  function updateChips(idx, chipsRow) {
809
  chipsRow.innerHTML = '';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
810
  (problems[idx].images || []).forEach(function(img, ii) {
811
  var chip = document.createElement('div'); chip.className = 'img-chip';
812
  var thumb = document.createElement('img'); thumb.src = img.data; thumb.title = img.name;
813
  thumb.addEventListener('click', function() { openImageModal(img.data); });
814
  var name = document.createElement('span'); name.textContent = img.name || 'image';
815
  name.style.cssText = 'max-width:80px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;';
816
- var rm = document.createElement('button'); rm.className = 'img-chip-remove'; rm.textContent = '\\u00d7';
817
  rm.addEventListener('click', (function(i, imgI, row) {
818
  return function() { problems[i].images.splice(imgI, 1); updateChips(i, row); };
819
  })(idx, ii, chipsRow));
@@ -891,6 +1120,57 @@ _HTML = """<!DOCTYPE html>
891
  setTimeout(function() { t.classList.remove('show'); }, 2500);
892
  }
893
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
894
  function downloadRawText() {
895
  var a = document.createElement('a');
896
  a.href = URL.createObjectURL(new Blob([rawText], { type: 'text/plain' }));
@@ -905,7 +1185,7 @@ _HTML = """<!DOCTYPE html>
905
 
906
  function inferChapterFromQuestionNumber(questionNumber) {
907
  var qn = String(questionNumber || '').trim().toUpperCase();
908
- var m = qn.match(/^[A-Z]+(\d+)\./);
909
  return m ? parseInt(m[1], 10) : null;
910
  }
911
 
@@ -1001,17 +1281,82 @@ async def extract(
1001
  return {"text": text, "images": images, "char_count": len(text)}
1002
 
1003
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1004
  @app.post("/api/parse-json")
1005
  async def parse_json_route(request: Request):
1006
  raw = (await request.body()).decode("utf-8").strip()
1007
  m = re.search(r"```(?:json)?\n([\s\S]*?)\n?```", raw)
1008
  if m:
1009
  raw = m.group(1).strip()
1010
- # Fix unescaped LaTeX backslashes like \le, \ge, \alpha that Gemini forgets to escape.
1011
- # Match every \X pair atomically: if X is a valid JSON escape char, leave it alone;
1012
- # otherwise double the backslash. This prevents the second \ of \\ from being re-matched.
1013
  fixed = re.sub(
1014
- r'\\(.)',
1015
  lambda m: m.group(0) if m.group(1) in '"\\/bfnrtu' else '\\\\' + m.group(1),
1016
  raw,
1017
  )
@@ -1098,7 +1443,7 @@ async def export_chapter(payload: dict):
1098
  "figure_reference": q.get("figure_reference"),
1099
  "exam_ready": q.get("exam_ready") is not False,
1100
  "exam_notes": q.get("exam_notes"),
1101
- "answer": q.get("answer"),
1102
  "assets": image_paths,
1103
  "source": {
1104
  "teammate": teammate,
@@ -1129,6 +1474,165 @@ async def save(problems: list):
1129
  return {"ok": True}
1130
 
1131
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1132
  @app.get("/output/{filename}")
1133
  def serve_output(filename: str):
1134
  path = OUTPUT_DIR / filename
 
2
  import base64
3
  import io
4
  import json
5
+ import os
6
  import re
7
  import shutil
8
  import tempfile
 
11
  from pathlib import Path
12
  from typing import Optional
13
 
14
+ import httpx
15
+ from dotenv import load_dotenv
16
  from fastapi import FastAPI, File, Form, HTTPException, Request, UploadFile
17
+
18
+ load_dotenv()
19
  from fastapi.middleware.cors import CORSMiddleware
20
  from fastapi.responses import FileResponse, HTMLResponse, Response
21
 
 
33
  BUNDLED_PDF = (Path(__file__).parent / "../../Reference and Solution Manual/Modern Control Systems-12 Edition.pdf").resolve()
34
  BUNDLED_PDF_NAME = "Modern Control Systems-12 Edition.pdf"
35
 
36
+ EDUVERSE_API_URL = os.getenv("EDUVERSE_API_URL", "https://eduverse-team-eduverse-backend.hf.space")
37
+ EDUVERSE_EMAIL = os.getenv("EDUVERSE_EMAIL", "")
38
+ EDUVERSE_PASSWORD = os.getenv("EDUVERSE_PASSWORD", "")
39
+
40
+ _eduverse_token: Optional[str] = None
41
+
42
 
43
  def _active_pdf() -> Optional[Path]:
44
  """Return the PDF to use: user-uploaded first, then the bundled textbook."""
 
48
  return BUNDLED_PDF
49
  return None
50
 
 
 
51
 
52
+ async def _get_eduverse_token() -> str:
53
+ global _eduverse_token
54
+ if _eduverse_token:
55
+ return _eduverse_token
56
+ if not EDUVERSE_EMAIL or not EDUVERSE_PASSWORD:
57
+ raise HTTPException(status_code=500, detail="EDUVERSE_EMAIL and EDUVERSE_PASSWORD must be set in .env")
58
+ async with httpx.AsyncClient() as client:
59
+ r = await client.post(
60
+ f"{EDUVERSE_API_URL}/api/auth/login",
61
+ json={"email": EDUVERSE_EMAIL, "password": EDUVERSE_PASSWORD},
62
+ timeout=15,
63
+ )
64
+ if r.status_code != 200:
65
+ raise HTTPException(status_code=502, detail=f"EduVerse login failed: {r.text}")
66
+ data = r.json()
67
+ token = data.get("accessToken") or data.get("access_token") or data.get("token")
68
+ if not token:
69
+ raise HTTPException(status_code=502, detail=f"EduVerse login response missing token: {data}")
70
+ _eduverse_token = token
71
+ return token
72
+
73
+
74
+ GEMINI_PROMPT = """\
75
+ You are extracting problems from an academic textbook. The text was extracted via OCR from a scanned PDF and may contain artifacts, merged columns, and garbled spacing. Identify every distinct problem or question.
76
 
77
  Return a JSON array where each object has exactly these fields:
78
+ - "question_number": string — the problem label as it appears (e.g. "P1.1", "Q3", "Exercise 4.2", "Problem 7")
79
  - "question": string — complete question text, cleaned of OCR errors. Remove figure captions and page headers. Fix broken words from column wrapping. Format all math using LaTeX: inline with $...$ (e.g. $x_1$, $\\omega_n$, $K > 0$), display with $$...$$.
80
  - "page": number — page where the problem starts (use the --- PAGE N --- markers)
81
+ - "question_type": string — one of exactly: "written", "mcq", "true_false". Use "mcq" only if the question lists labeled answer choices (A/B/C/D or similar). Use "true_false" only if the question is a direct true-or-false statement. Use "written" for everything else (derivations, calculations, short answer, design problems).
82
+ - "difficulty": string — one of exactly: "easy", "medium", "hard". Base this on cognitive load and prerequisite knowledge: easy = recall or single-step, medium = multi-step application, hard = synthesis, design, or proof.
83
+ - "bloom_level": string — one of exactly: "remembering", "understanding", "applying", "analyzing", "evaluating", "creating". Pick the highest Bloom's taxonomy level the question primarily demands.
84
  - "has_diagram": boolean — true if the question references a Figure, asks to sketch a diagram or block diagram, or involves a circuit
85
  - "figure_reference": string or null — specific figure label when present (e.g. "Figure 13.18", "Fig. P1.2"), otherwise null
86
  - "exam_ready": boolean — true if suitable for a university exam. Mark false for: pure discussion/describe questions, problems entirely dependent on a figure students won't have, or questions too open-ended to grade objectively.
87
  - "exam_notes": string or null — if exam_ready is false, a brief reason (e.g. "discussion only", "requires Figure P1.2", "open-ended design"). If exam_ready is true, use null.
88
+ - "expected_answer": string or null — for "written" and "true_false" question types only: a concise model answer (1–4 sentences or key steps). For "mcq" use null (the correct option already encodes the answer).
89
 
90
  Return ONLY a valid JSON array wrapped in ```json fences. No explanation.
91
 
 
102
  <script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.js"></script>
103
  <script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/contrib/auto-render.min.js"
104
  onload="onKatexReady()"></script>
105
+ <script src="https://unpkg.com/lucide@latest/dist/umd/lucide.min.js"></script>
106
  <style>
107
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
108
  body { font-family: system-ui, sans-serif; background: #f8fafc; color: #1e293b; line-height: 1.5; }
 
127
  /* Config bar */
128
  .config-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; }
129
  .config-bar input[type=number] { width: 68px; padding: 6px 8px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 0.85rem; font-family: inherit; text-align: center; }
130
+ /* Plain number fields: no stepper arrows, no wheel nudging */
131
+ input[type=number] { -moz-appearance: textfield; appearance: textfield; }
132
+ input[type=number]::-webkit-outer-spin-button,
133
+ input[type=number]::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
134
  .config-bar input:focus { outline: none; border-color: #2563eb; }
135
  .config-sep { color: #94a3b8; font-size: 0.85rem; }
136
  #extract-status { font-size: 0.78rem; color: #64748b; }
 
138
  .spin { display: inline-block; width: 14px; height: 14px; border: 2px solid rgba(255,255,255,0.4); border-top-color: white; border-radius: 50%; animation: spin 0.6s linear infinite; }
139
  @keyframes spin { to { transform: rotate(360deg); } }
140
  /* PDF picker */
141
+ .pdf-change-link { font-size: 0.7rem; color: #64748b; text-decoration: underline; flex-shrink: 0; }
 
 
 
 
 
 
 
142
  /* Workflow grid */
143
  .workflow-grid { display: flex; gap: 12px; flex-wrap: wrap; margin-bottom: 12px; }
144
  .workflow-grid .card { flex: 1; min-width: 260px; margin-bottom: 0; }
 
157
  /* Question sections */
158
  .q-section { margin-bottom: 18px; }
159
  .q-section-title { font-size: 0.8rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.06em; color: #475569; margin: 10px 0 8px; }
160
+ /* Locked state (before PDF chosen) */
161
+ .locked { opacity: 0.4; pointer-events: none; user-select: none; }
162
+ /* PDF picker pill — whole thing is clickable */
163
+ .pdf-picker-label { display: inline-flex; align-items: center; gap: 6px; padding: 6px 13px; background: #f8fafc; border: 1.5px dashed #cbd5e1; border-radius: 6px; font-size: 0.78rem; font-weight: 600; color: #475569; cursor: pointer; transition: border-color 0.15s, background 0.15s, color 0.15s; user-select: none; }
164
+ .pdf-picker-label:hover { border-color: #2563eb; color: #2563eb; background: #eff6ff; }
165
+ .pdf-ready-pill { display: none; align-items: center; gap: 7px; background: #f0fdf4; border: 1px solid #bbf7d0; border-radius: 6px; padding: 5px 11px; font-size: 0.78rem; color: #166534; max-width: 340px; cursor: pointer; }
166
+ .pdf-ready-pill:hover { background: #dcfce7; }
167
+ .pdf-ready-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 220px; }
168
+ .pdf-pending-pill { display: none; align-items: center; gap: 7px; background: #fffbeb; border: 1px solid #fde68a; border-radius: 6px; padding: 5px 11px; font-size: 0.78rem; color: #92400e; max-width: 380px; cursor: pointer; }
169
+ .pdf-pending-pill:hover { background: #fef9c3; }
170
+ .pdf-pending-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 180px; }
171
+ body.dark .pdf-picker-label { background: #1e293b; border-color: #475569; color: #94a3b8; }
172
+ body.dark .pdf-picker-label:hover { border-color: #2563eb; color: #93c5fd; background: #1e3a5f; }
173
  /* Problem cards */
174
+ .q-card { background: white; border: 1px solid #e2e8f0; border-radius: 8px; padding: 14px 18px; margin-bottom: 10px; transition: border-color 0.15s; cursor: pointer; }
175
  .q-card.active-card { border-color: #2563eb; box-shadow: 0 0 0 4px #bfdbfe; background: #f8fbff; }
176
  .q-card.flash { border-color: #4ade80; box-shadow: 0 0 0 3px #f0fdf4; }
177
  .q-header { display: flex; align-items: center; gap: 7px; flex-wrap: wrap; margin-bottom: 10px; }
 
189
  .exam-toggle { display: inline-flex; align-items: center; gap: 5px; font-size: 0.73rem; color: #64748b; cursor: pointer; user-select: none; margin-left: auto; }
190
  .exam-toggle input[type=checkbox] { cursor: pointer; }
191
  .q-notes { font-size: 0.71rem; color: #94a3b8; margin-top: 5px; font-style: italic; }
192
+ .q-answer-wrap { margin-top: 8px; }
193
+ .q-answer-body { margin-top: 4px; padding: 10px 12px; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 6px; }
194
+ .q-answer-body.hidden { display: none; }
195
+ .ans-rendered { font-size: 0.875rem; line-height: 1.9; min-height: 2em; overflow-x: auto; }
196
  .chips-row { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; }
197
  .img-chip { display: inline-flex; align-items: center; gap: 5px; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 6px; padding: 3px 8px 3px 3px; font-size: 0.72rem; color: #475569; }
198
  .img-chip img { width: 56px; height: 56px; object-fit: cover; border-radius: 4px; cursor: zoom-in; border: 1px solid #cbd5e1; }
 
201
  .img-chip-remove { background: none; border: none; cursor: pointer; color: #94a3b8; font-size: 1rem; line-height: 1; padding: 0; }
202
  .img-chip-remove:hover { color: #dc2626; }
203
  /* Export bar */
204
+ .export-bar { position: fixed; bottom: 0; left: 0; right: 0; background: white; border-top: 1px solid #e2e8f0; padding: 8px 24px; display: none; justify-content: space-between; align-items: center; z-index: 100; flex-wrap: wrap; gap: 8px; min-height: 52px; }
205
  .export-bar-left { display: flex; align-items: center; gap: 14px; font-size: 0.82rem; color: #64748b; }
206
  .paste-hint { font-size: 0.75rem; color: #2563eb; background: #eff6ff; padding: 2px 8px; border-radius: 4px; }
207
+ /* EduVerse save panel — fixed above export bar */
208
+ .ev-panel { position: fixed; bottom: 52px; left: 0; right: 0; background: #f0fdf4; border-top: 1px solid #bbf7d0; padding: 12px 24px; display: none; z-index: 99; box-shadow: 0 -4px 16px rgba(0,0,0,0.08); }
209
+ .ev-panel.open { display: block; }
210
+ body.dark .ev-panel { background: #052e16; border-color: #166534; box-shadow: 0 -4px 16px rgba(0,0,0,0.4); }
211
+ .ev-panel-title { font-size: 0.78rem; font-weight: 700; color: #166534; margin-bottom: 10px; }
212
+ .ev-row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
213
+ .ev-row input[type=number] { width: 100px; padding: 6px 8px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 0.82rem; font-family: inherit; }
214
+ .ev-row input[type=number]:focus { outline: none; border-color: #16a34a; }
215
+ .ev-status { font-size: 0.78rem; margin-top: 8px; color: #64748b; min-height: 18px; }
216
+ .ev-status.ok { color: #166534; }
217
+ .ev-status.err { color: #dc2626; }
218
+ body.dark .ev-panel { background: #052e16; border-color: #166534; }
219
+ body.dark .ev-panel-title { color: #86efac; }
220
+ body.dark .ev-row input[type=number] { background: #0f172a; border-color: #334155; color: #e2e8f0; }
221
  /* Toast */
222
  .toast { position: fixed; bottom: 60px; left: 50%; transform: translateX(-50%); background: #1e293b; color: white; padding: 7px 16px; border-radius: 6px; font-size: 0.78rem; z-index: 200; pointer-events: none; opacity: 0; transition: opacity 0.2s; }
223
  .toast.show { opacity: 1; }
 
246
  body.dark .config-sep { color: #475569; }
247
  body.dark #extract-status { color: #64748b; }
248
  body.dark .config-bar input[type=number] { background: #0f172a; border-color: #334155; color: #e2e8f0; }
 
 
249
  body.dark .pdf-change-link { color: #64748b; }
 
250
  body.dark .info-box { background: #1e3a5f; border-color: #1d4ed8; color: #93c5fd; }
251
  body.dark .error-box { background: #450a0a; border-color: #7f1d1d; color: #f87171; }
252
  body.dark .step-label { color: #64748b; }
 
266
  body.dark .q-rendered { color: #e2e8f0; }
267
  body.dark .q-text { background: #0f172a; border-color: #334155; color: #e2e8f0; }
268
  body.dark .q-text:focus { background: #0f172a; }
269
+ body.dark .q-answer-body { background: #0f172a; border-color: #334155; }
270
+ body.dark .ans-rendered { color: #e2e8f0; }
271
  body.dark .q-notes { color: #475569; }
272
  body.dark .exam-toggle { color: #64748b; }
273
  body.dark .img-chip { background: #0f172a; border-color: #334155; color: #94a3b8; }
 
295
 
296
  <div id="error-box" class="error-box"></div>
297
 
298
+ <input type="file" id="pdf-file-input" accept=".pdf" style="display:none;" onchange="handlePdfSelect(this)">
299
+
300
  <!-- ── Config bar ── -->
301
+ <div id="config-card" class="card" style="margin-bottom:16px;">
302
  <div class="config-bar">
303
+ <!-- PDF picker: whole element is clickable -->
304
+ <label id="pdf-picker-label" class="pdf-picker-label" for="pdf-file-input">
305
+ <i data-lucide="book-open" style="width:13px;height:13px;"></i>
 
306
  Choose PDF
307
  </label>
308
+ <label id="pdf-ready-pill" class="pdf-ready-pill" for="pdf-file-input">
309
+ <i data-lucide="check-circle" style="width:13px;height:13px;flex-shrink:0;"></i>
310
  <span id="pdf-ready-name" class="pdf-ready-name"></span>
311
+ <span class="pdf-change-link">Change</span>
312
+ </label>
313
+ <label id="pdf-pending-pill" class="pdf-pending-pill" for="pdf-file-input">
314
+ <i data-lucide="clock" style="width:13px;height:13px;flex-shrink:0;"></i>
315
  <span id="pdf-pending-name" class="pdf-pending-name"></span>
316
  <span style="color:#a16207;font-size:0.68rem;flex-shrink:0;">uploads on Extract</span>
317
+ <span class="pdf-change-link">Change</span>
318
+ </label>
319
+ <!-- Extract controls — locked until PDF chosen -->
320
+ <span id="extract-controls" class="locked" style="display:inline-flex;align-items:center;gap:10px;flex-wrap:wrap;">
321
+ <span class="config-sep">|</span>
322
+ <span style="font-size:0.78rem;color:#64748b;">Pages</span>
323
+ <input id="tb-start" type="number" min="1" placeholder="Start">
324
+ <span class="config-sep">&ndash;</span>
325
+ <input id="tb-end" type="number" min="1" placeholder="End">
326
+ <button id="extract-btn" class="btn btn-primary btn-sm" onclick="startExtract()">
327
+ <i data-lucide="scan-text" style="width:13px;height:13px;"></i>
328
+ Extract
329
+ </button>
330
+ <span id="extract-status"></span>
331
+ </span>
332
  </div>
333
  </div>
334
 
335
+ <!-- ── Workflow — locked until PDF chosen ── -->
336
+ <div id="workflow-section" class="locked">
337
  <div class="workflow-grid">
338
  <div class="card">
339
  <div class="step-label"><span class="step-num">1</span> Copy &amp; paste into <a href="https://gemini.google.com" target="_blank" style="color:#2563eb;">gemini.google.com</a></div>
340
  <div class="info-box">Copies the full prompt + your extracted text in one click.</div>
341
  <div style="display:flex;gap:8px;flex-wrap:wrap;">
342
+ <button id="copy-btn" class="btn btn-primary btn-sm" onclick="copyForGemini()"><i data-lucide="clipboard-copy" style="width:13px;height:13px;"></i> Copy prompt + text</button>
343
+ <button id="download-raw-btn" class="btn btn-secondary btn-sm" onclick="downloadRawText()"><i data-lucide="download" style="width:13px;height:13px;"></i> Download .txt</button>
344
  </div>
345
  </div>
346
  <div class="card">
347
  <div class="step-label"><span class="step-num">2</span> Paste Gemini&rsquo;s JSON response</div>
348
  <textarea id="json-paste" class="paste-area" placeholder="Paste here (with or without the ```json fences)..."></textarea>
349
+ <button id="load-json-btn" class="btn btn-success btn-sm" onclick="loadFromJSON()"><i data-lucide="list-checks" style="width:13px;height:13px;"></i> Load Problems</button>
350
  </div>
351
  </div>
352
  <div id="workflow-busy" class="workflow-busy">
 
365
 
366
  <!-- ── Review (appears after loading JSON) ── -->
367
  <div id="review-section" style="display:none;">
368
+ <div id="refresh-warning" style="display:flex;align-items:center;gap:10px;background:#fffbeb;border:1px solid #fde68a;border-radius:8px;padding:10px 14px;margin-bottom:14px;font-size:0.8rem;color:#92400e;">
369
+ <i data-lucide="triangle-alert" style="width:15px;height:15px;flex-shrink:0;"></i>
370
+ <span>Your questions live in memory only — <strong>refreshing this page will clear everything.</strong> Export JSON or Save to EduVerse before leaving.</span>
371
+ <button onclick="document.getElementById('refresh-warning').style.display='none'" style="margin-left:auto;background:none;border:none;cursor:pointer;color:#92400e;flex-shrink:0;"><i data-lucide="x" style="width:14px;height:14px;"></i></button>
372
+ </div>
373
  <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px;flex-wrap:wrap;gap:8px;">
374
  <p id="review-meta" style="font-size:0.82rem;color:#64748b;"></p>
375
  </div>
 
381
  </div>
382
  </div>
383
 
384
+ <!-- EduVerse save panel (shown above export bar when open) -->
385
+ <div id="ev-panel" class="ev-panel">
386
+ <div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap;">
387
+ <span style="font-size:0.78rem;font-weight:700;color:#166534;display:inline-flex;align-items:center;gap:5px;flex-shrink:0;">
388
+ <i data-lucide="database-zap" style="width:13px;height:13px;"></i> Save to EduVerse
389
+ </span>
390
+ <label style="font-size:0.78rem;color:#475569;flex-shrink:0;">Course ID</label>
391
+ <input id="ev-course-id" type="number" min="1" placeholder="e.g. 2" style="width:90px;padding:5px 8px;border:1px solid #cbd5e1;border-radius:6px;font-size:0.82rem;font-family:inherit;">
392
+ <label style="font-size:0.78rem;color:#475569;flex-shrink:0;">Chapter ID</label>
393
+ <input id="ev-chapter-id" type="number" min="1" placeholder="e.g. 1" style="width:90px;padding:5px 8px;border:1px solid #cbd5e1;border-radius:6px;font-size:0.82rem;font-family:inherit;">
394
+ <button class="btn btn-success btn-sm" onclick="saveToEduverse(this)"><i data-lucide="send" style="width:13px;height:13px;"></i> Save exam-ready</button>
395
+ <button class="btn btn-secondary btn-sm" onclick="toggleEvPanel()"><i data-lucide="x" style="width:13px;height:13px;"></i> Cancel</button>
396
+ <span id="ev-status" class="ev-status" style="margin-top:0;"></span>
397
+ </div>
398
+ </div>
399
+
400
  <!-- Export bar -->
401
  <div id="export-bar" class="export-bar">
402
  <div class="export-bar-left">
 
406
  <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
407
  <input id="chapter-export" type="number" min="1" placeholder="Chapter" style="width:88px;padding:6px 8px;border:1px solid #cbd5e1;border-radius:6px;font-size:0.78rem;">
408
  <input id="teammate-export" type="text" placeholder="Teammate (optional)" style="width:160px;padding:6px 8px;border:1px solid #cbd5e1;border-radius:6px;font-size:0.78rem;">
409
+ <button class="btn btn-secondary btn-sm" onclick="exportChapterZip(this)"><i data-lucide="archive" style="width:13px;height:13px;"></i> Export ZIP</button>
410
+ <button class="btn btn-secondary btn-sm" onclick="exportJSON()"><i data-lucide="file-json" style="width:13px;height:13px;"></i> Export JSON</button>
411
+ <button class="btn btn-primary btn-sm" onclick="toggleEvPanel()"><i data-lucide="database-zap" style="width:13px;height:13px;"></i> Save to EduVerse</button>
412
  </div>
413
  </div>
414
 
 
426
  var activeFilter = 'all';
427
  var activeCardIdx = null;
428
  var pendingPdfFile = null;
429
+ var hasPdf = false;
430
+
431
+ // ── PDF gate helpers ──────────────────────────────────────────────────────
432
+
433
+ function unlockWorkflow() {
434
+ hasPdf = true;
435
+ document.getElementById('extract-controls').classList.remove('locked');
436
+ document.getElementById('workflow-section').classList.remove('locked');
437
+ }
438
 
439
  // ── PDF state ─────────────────────────────────────────────────────────────
440
 
441
  function initPdfState() {
442
+ // Do NOT auto-activate saved/bundled PDF — require explicit selection each session.
 
 
443
  }
444
 
445
  function handlePdfSelect(input) {
446
  var file = input.files && input.files[0];
447
  if (!file) return;
448
  pendingPdfFile = file;
449
+ document.getElementById('pdf-picker-label').style.display = 'none';
450
+ document.getElementById('pdf-ready-pill').style.display = 'none';
451
+ document.getElementById('pdf-pending-pill').style.display = 'inline-flex';
452
+ document.getElementById('pdf-pending-name').textContent = file.name;
 
453
  input.value = '';
454
+ unlockWorkflow();
455
  }
456
 
457
  function showPdfReady(name) {
458
  pendingPdfFile = null;
459
+ document.getElementById('pdf-picker-label').style.display = 'none';
460
  document.getElementById('pdf-pending-pill').style.display = 'none';
461
+ document.getElementById('pdf-ready-pill').style.display = 'inline-flex';
462
+ document.getElementById('pdf-ready-name').textContent = name;
 
463
  }
464
 
465
  // ── Dark mode ─────────────────────────────────────────────────────────────
 
476
  try { localStorage.setItem('dm', !isDark ? '1' : '0'); } catch(e) {}
477
  }
478
 
479
+ function initNumberInputsNoWheel() {
480
+ document.querySelectorAll('input[type="number"]').forEach(function(el) {
481
+ el.addEventListener('wheel', function(e) { e.preventDefault(); }, { passive: false });
482
+ });
483
+ }
484
+
485
+ window.addEventListener('beforeunload', function(e) {
486
+ if (problems.length > 0) { e.preventDefault(); e.returnValue = ''; }
487
+ });
488
+
489
  window.addEventListener('DOMContentLoaded', function() {
490
  initPdfState();
491
+ initNumberInputsNoWheel();
492
  try {
493
  var saved = localStorage.getItem('dm');
494
  var prefersDark = saved !== null ? saved === '1' : window.matchMedia('(prefers-color-scheme: dark)').matches;
495
  applyDark(prefersDark);
496
  } catch(e) {}
497
+ lucide.createIcons();
498
  });
499
 
500
  var KATEX_OPTS = {
 
524
 
525
  async function startExtract() {
526
  hideError();
527
+ if (!hasPdf && !pendingPdfFile) { showError('Choose a PDF first.'); return; }
528
  var tbStartRaw = document.getElementById('tb-start').value.trim();
529
  var tbEndRaw = document.getElementById('tb-end').value.trim();
530
  var tbStart = parseInt(tbStartRaw, 10);
 
555
 
556
  var imgs = data.images || [];
557
  document.getElementById('extract-status').textContent =
558
+ '✓ ' + (data.char_count || 0).toLocaleString() + ' chars · ' + imgs.length + ' images';
559
  showToast(
560
  isReextract
561
  ? 'Re-extraction complete. Text and images refreshed.'
 
594
  document.getElementById('images-toggle-label').textContent = 'Page images (' + imgs.length + ')';
595
  toggle.style.display = 'inline-flex';
596
  document.getElementById('images-section').style.display = 'none';
597
+ document.getElementById('images-arrow').textContent = '▶';
598
  imgs.forEach(function(img) {
599
  var src = '/output/' + img.filename;
600
  var wrapper = document.createElement('div');
 
621
  var arrow = document.getElementById('images-arrow');
622
  var open = section.style.display !== 'none';
623
  section.style.display = open ? 'none' : 'block';
624
+ arrow.textContent = open ? '▶' : '▼';
625
  }
626
 
627
  function openImageModal(src) {
 
673
  problems = parsed.map(function(q) {
674
  var figureReference = q.figure_reference ? String(q.figure_reference) : detectFigureReference(String(q.question || ''));
675
  return {
676
+ question_number: String(q.question_number || ''),
677
+ question: String(q.question || ''),
678
+ page: q.page || null,
679
+ question_type: q.question_type || 'written',
680
+ difficulty: q.difficulty || 'medium',
681
+ bloom_level: q.bloom_level || 'applying',
682
+ has_diagram: Boolean(q.has_diagram),
683
  figure_reference: figureReference || null,
684
+ exam_ready: q.exam_ready !== false,
685
+ exam_notes: q.exam_notes || null,
686
+ expected_answer: q.expected_answer || null,
687
+ images: [],
688
  };
689
  });
690
  var ready = problems.filter(function(q) { return q.exam_ready; }).length;
691
  document.getElementById('review-meta').textContent =
692
+ problems.length + ' problems loaded · ' + ready + ' exam ready';
693
  updateFilterCounts();
694
  renderProblems();
695
  var rs = document.getElementById('review-section');
696
  rs.style.display = 'block';
697
  document.getElementById('export-bar').style.display = 'flex';
698
+ lucide.createIcons();
699
  setTimeout(function() { rs.scrollIntoView({ behavior: 'smooth', block: 'start' }); }, 80);
700
  } catch(e) { showError('Could not parse JSON: ' + e.message); }
701
  }
 
730
 
731
  // ── Problems ──────────────────────────────────────────────────────────────
732
 
733
+ var QTYPE_LABELS = {
734
+ 'mcq': 'Multiple Choice',
735
+ 'true_false': 'True / False',
736
+ 'written': 'Written / Open-ended',
737
+ 'essay': 'Essay',
 
 
738
  };
739
+ var QTYPE_ORDER = ['mcq', 'true_false', 'written', 'essay'];
740
 
741
+ function getGroupKey(questionType) {
742
+ var t = String(questionType || '').toLowerCase();
743
+ return QTYPE_LABELS[t] ? t : 'written';
 
 
 
 
744
  }
745
 
746
+ function getGroupLabel(key) {
747
+ return QTYPE_LABELS[key] || 'Written / Open-ended';
 
748
  }
749
 
750
  function detectFigureReference(text) {
 
754
  return 'Figure ' + m[1];
755
  }
756
 
 
 
 
 
 
 
 
 
757
  function renderProblems() {
758
  var list = document.getElementById('problems-list');
759
  list.innerHTML = '';
 
765
 
766
  var grouped = {};
767
  problems.forEach(function(q, idx) {
768
+ var typeCode = getGroupKey(q.question_type);
769
  if (!grouped[typeCode]) grouped[typeCode] = [];
770
  grouped[typeCode].push({ question: q, index: idx });
771
  });
772
 
773
+ var orderedKeys = QTYPE_ORDER.filter(function(k) { return grouped[k] && grouped[k].length; });
774
+
775
+ orderedKeys.forEach(function(typeCode) {
776
  var section = document.createElement('section');
777
  section.className = 'q-section';
778
  section.dataset.type = typeCode;
779
 
780
  var title = document.createElement('div');
781
  title.className = 'q-section-title';
782
+ title.textContent = getGroupLabel(typeCode) + ' (' + grouped[typeCode].length + ')';
783
  section.appendChild(title);
784
 
785
  grouped[typeCode].forEach(function(item) {
 
791
  applyFilter();
792
  }
793
 
794
+ function mkIcon(pathData, size) {
795
+ size = size || 12;
796
+ var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
797
+ svg.setAttribute('width', size); svg.setAttribute('height', size);
798
+ svg.setAttribute('viewBox', '0 0 24 24'); svg.setAttribute('fill', 'none');
799
+ svg.setAttribute('stroke', 'currentColor'); svg.setAttribute('stroke-width', '2.5');
800
+ svg.setAttribute('stroke-linecap', 'round'); svg.setAttribute('stroke-linejoin', 'round');
801
+ svg.style.cssText = 'flex-shrink:0;vertical-align:middle;';
802
+ svg.innerHTML = pathData;
803
+ return svg;
804
+ }
805
+ var IC = {
806
+ check: '<polyline points="20 6 9 17 4 12"/>',
807
+ x: '<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>',
808
+ warn: '<path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/>',
809
+ edit: '<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>',
810
+ done: '<polyline points="20 6 9 17 4 12"/>',
811
+ trash: '<polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14H6L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/><path d="M9 6V4h6v2"/>',
812
+ img: '<rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/>',
813
+ };
814
+
815
  function buildCard(q, idx) {
816
  var card = document.createElement('div');
817
  card.className = 'q-card';
 
828
  var pg = document.createElement('span'); pg.className = 'badge badge-page';
829
  pg.textContent = 'Page ' + q.page; header.appendChild(pg);
830
  }
831
+ if (q.question_type && q.question_type !== 'written') {
832
+ var qt = document.createElement('span'); qt.className = 'badge badge-page';
833
+ qt.textContent = q.question_type.replace('_', '/'); header.appendChild(qt);
834
+ }
835
+ if (q.difficulty) {
836
+ var diff = document.createElement('span');
837
+ diff.className = 'badge ' + (q.difficulty === 'hard' ? 'badge-warn' : q.difficulty === 'easy' ? 'badge-ready' : 'badge-skip');
838
+ diff.style.cssText = 'display:inline-flex;align-items:center;gap:3px;';
839
+ diff.title = 'Difficulty';
840
+ diff.appendChild(mkIcon('<path d="M2 20h20M6 20V10l6-8 6 8v10"/>', 11));
841
+ diff.appendChild(document.createTextNode(' ' + q.difficulty));
842
+ header.appendChild(diff);
843
+ }
844
+ if (q.bloom_level) {
845
+ var bl = document.createElement('span'); bl.className = 'badge badge-skip';
846
+ bl.style.cssText = 'display:inline-flex;align-items:center;gap:3px;';
847
+ bl.title = "Bloom's Taxonomy level";
848
+ bl.appendChild(mkIcon('<path d="M12 2a10 10 0 1 0 10 10"/><path d="M12 12V2"/><path d="M12 12l6.5-6.5"/>', 11));
849
+ bl.appendChild(document.createTextNode(' ' + q.bloom_level));
850
+ header.appendChild(bl);
851
+ }
852
  if (q.figure_reference || q.has_diagram) {
853
  var dg = document.createElement('span'); dg.className = 'badge badge-warn';
854
+ dg.id = 'diag-badge-' + idx;
855
+ dg.style.cssText = 'display:inline-flex;align-items:center;gap:3px;';
856
+ dg.title = 'References a diagram — attach an image to resolve';
857
+ dg.appendChild(mkIcon(IC.warn, 11));
858
+ dg.appendChild(document.createTextNode(' ' + (q.figure_reference || 'diagram needed')));
859
+ header.appendChild(dg);
860
  }
861
  var eb = document.createElement('span');
862
  eb.id = 'exam-badge-' + idx;
863
  eb.className = 'badge ' + (q.exam_ready ? 'badge-ready' : 'badge-skip');
864
+ eb.style.cssText = 'display:inline-flex;align-items:center;gap:3px;';
865
+ eb.appendChild(mkIcon(q.exam_ready ? IC.check : IC.x, 11));
866
+ eb.appendChild(document.createTextNode(q.exam_ready ? ' exam ready' : ' skip'));
867
  header.appendChild(eb);
868
  var targetPill = document.createElement('span');
869
  targetPill.className = 'paste-target-pill';
870
  targetPill.textContent = 'Ctrl+V target';
871
  header.appendChild(targetPill);
872
  var sp = document.createElement('div'); sp.style.flex = '1'; header.appendChild(sp);
873
+ var del = document.createElement('button'); del.className = 'btn btn-danger btn-sm'; del.style.cssText = 'display:inline-flex;align-items:center;gap:4px;';
874
+ del.appendChild(mkIcon(IC.trash, 12)); del.appendChild(document.createTextNode(' Delete'));
875
  del.addEventListener('click', (function(i) {
876
  return function(e) { e.stopPropagation(); problems.splice(i,1); updateFilterCounts(); renderProblems(); };
877
  })(idx));
 
890
  // Controls
891
  var controls = document.createElement('div'); controls.className = 'q-controls';
892
 
893
+ var editBtn = document.createElement('button'); editBtn.className = 'btn btn-secondary btn-xs'; editBtn.style.cssText = 'display:inline-flex;align-items:center;gap:4px;';
894
+ editBtn.appendChild(mkIcon(IC.edit, 11)); editBtn.appendChild(document.createTextNode(' Edit'));
895
+ var doneBtn = document.createElement('button'); doneBtn.className = 'btn btn-primary btn-xs'; doneBtn.style.display = 'none'; doneBtn.style.cssText = 'display:none;align-items:center;gap:4px;';
896
+ doneBtn.appendChild(mkIcon(IC.done, 11)); doneBtn.appendChild(document.createTextNode(' Done'));
897
  editBtn.addEventListener('click', function(e) {
898
  e.stopPropagation(); renderDiv.style.display = 'none'; ta.style.display = 'block'; ta.focus();
899
  editBtn.style.display = 'none'; doneBtn.style.display = 'inline-flex';
 
923
  };
924
  })(idx));
925
  card.appendChild(fi);
926
+ var attachBtn = document.createElement('button'); attachBtn.className = 'btn btn-secondary btn-xs'; attachBtn.style.cssText = 'display:inline-flex;align-items:center;gap:4px;';
927
+ attachBtn.appendChild(mkIcon(IC.img, 11)); attachBtn.appendChild(document.createTextNode(' Attach diagram'));
928
  attachBtn.addEventListener('click', function(e) { e.stopPropagation(); fi.click(); });
929
  controls.appendChild(attachBtn);
930
 
 
936
  problems[i].exam_ready = e.target.checked;
937
  cardEl.dataset.examReady = e.target.checked ? '1' : '0';
938
  var badge = document.getElementById('exam-badge-' + i);
939
+ if (badge) {
940
+ badge.className = 'badge ' + (e.target.checked ? 'badge-ready' : 'badge-skip');
941
+ badge.style.cssText = 'display:inline-flex;align-items:center;gap:3px;';
942
+ badge.innerHTML = '';
943
+ badge.appendChild(mkIcon(e.target.checked ? IC.check : IC.x, 11));
944
+ badge.appendChild(document.createTextNode(e.target.checked ? ' exam ready' : ' skip'));
945
+ }
946
  applyFilter(); updateFilterCounts();
947
  };
948
  })(idx, card));
 
957
  notes.textContent = 'Note: ' + q.exam_notes; card.appendChild(notes);
958
  }
959
 
960
+ // Model answer (written / true_false only)
961
+ if (q.question_type === 'written' || q.question_type === 'true_false') {
962
+ var ansWrap = document.createElement('div'); ansWrap.className = 'q-answer-wrap';
963
+ var ansToggle = document.createElement('button'); ansToggle.type = 'button'; ansToggle.className = 'btn btn-secondary btn-xs ans-toggle';
964
+ ansToggle.style.cssText = 'display:inline-flex;align-items:center;gap:4px;margin-bottom:4px;';
965
+ ansToggle.appendChild(mkIcon(IC.done, 11)); ansToggle.appendChild(document.createTextNode(' Model answer'));
966
+ var ansBody = document.createElement('div'); ansBody.className = 'q-answer-body hidden';
967
+ // Rendered view (mirrors q-rendered)
968
+ var ansRenderDiv = document.createElement('div'); ansRenderDiv.className = 'q-rendered ans-rendered';
969
+ ansRenderDiv.style.cssText = 'min-height:2em;cursor:text;';
970
+ ansRenderDiv.textContent = q.expected_answer || '(no answer yet — click Edit to add)';
971
+ if (q.expected_answer) renderMath(ansRenderDiv);
972
+ // Edit textarea (mirrors q-text but always visible when shown)
973
+ var ansTa = document.createElement('textarea'); ansTa.className = 'q-text ans-ta';
974
+ ansTa.rows = 3; ansTa.style.display = 'none';
975
+ ansTa.placeholder = 'Enter expected answer…';
976
+ ansTa.value = q.expected_answer || '';
977
+ ansTa.addEventListener('change', (function(i) { return function(e) { problems[i].expected_answer = e.target.value; }; })(idx));
978
+ ansTa.addEventListener('input', (function(i) { return function(e) { problems[i].expected_answer = e.target.value; }; })(idx));
979
+ // Edit / Done controls
980
+ var ansControls = document.createElement('div'); ansControls.style.cssText = 'display:flex;gap:6px;margin-top:6px;';
981
+ var ansEditBtn = document.createElement('button'); ansEditBtn.type = 'button'; ansEditBtn.className = 'btn btn-secondary btn-xs';
982
+ ansEditBtn.style.cssText = 'display:inline-flex;align-items:center;gap:4px;';
983
+ ansEditBtn.appendChild(mkIcon(IC.edit, 11)); ansEditBtn.appendChild(document.createTextNode(' Edit'));
984
+ var ansDoneBtn = document.createElement('button'); ansDoneBtn.type = 'button'; ansDoneBtn.className = 'btn btn-primary btn-xs';
985
+ ansDoneBtn.style.cssText = 'display:none;align-items:center;gap:4px;';
986
+ ansDoneBtn.appendChild(mkIcon(IC.done, 11)); ansDoneBtn.appendChild(document.createTextNode(' Done'));
987
+ ansEditBtn.addEventListener('click', (function(rd, ta, eb, db) { return function(e) {
988
+ e.stopPropagation();
989
+ rd.style.display = 'none'; ta.style.display = 'block'; ta.focus();
990
+ eb.style.display = 'none'; db.style.display = 'inline-flex';
991
+ }; })(ansRenderDiv, ansTa, ansEditBtn, ansDoneBtn));
992
+ ansDoneBtn.addEventListener('click', (function(i, rd, ta, eb, db) { return function(e) {
993
+ e.stopPropagation();
994
+ problems[i].expected_answer = ta.value;
995
+ rd.textContent = ta.value || '(no answer yet — click Edit to add)';
996
+ if (ta.value) renderMath(rd);
997
+ rd.style.display = 'block'; ta.style.display = 'none';
998
+ eb.style.display = 'inline-flex'; db.style.display = 'none';
999
+ }; })(idx, ansRenderDiv, ansTa, ansEditBtn, ansDoneBtn));
1000
+ ansControls.appendChild(ansEditBtn); ansControls.appendChild(ansDoneBtn);
1001
+ ansBody.appendChild(ansRenderDiv); ansBody.appendChild(ansTa); ansBody.appendChild(ansControls);
1002
+ ansToggle.addEventListener('click', function(e) {
1003
+ e.stopPropagation();
1004
+ e.preventDefault();
1005
+ ansBody.classList.toggle('hidden');
1006
+ });
1007
+ ansWrap.appendChild(ansToggle); ansWrap.appendChild(ansBody);
1008
+ card.appendChild(ansWrap);
1009
+ }
1010
+
1011
  // Image chips
1012
  var chipsRow = document.createElement('div'); chipsRow.className = 'chips-row';
1013
  chipsRow.id = 'chips-' + idx;
 
1018
 
1019
  function updateChips(idx, chipsRow) {
1020
  chipsRow.innerHTML = '';
1021
+ var hasImages = (problems[idx].images || []).length > 0;
1022
+ var diagBadge = document.getElementById('diag-badge-' + idx);
1023
+ if (diagBadge) {
1024
+ if (hasImages) {
1025
+ diagBadge.className = 'badge badge-ready';
1026
+ diagBadge.title = 'Diagram attached';
1027
+ diagBadge.innerHTML = '';
1028
+ diagBadge.appendChild(mkIcon(IC.img, 11));
1029
+ diagBadge.appendChild(document.createTextNode(' diagram attached'));
1030
+ } else {
1031
+ diagBadge.className = 'badge badge-warn';
1032
+ diagBadge.title = 'References a diagram — attach an image to resolve';
1033
+ diagBadge.innerHTML = '';
1034
+ diagBadge.appendChild(mkIcon(IC.warn, 11));
1035
+ var label = problems[idx].figure_reference || 'diagram needed';
1036
+ diagBadge.appendChild(document.createTextNode(' ' + label));
1037
+ }
1038
+ }
1039
  (problems[idx].images || []).forEach(function(img, ii) {
1040
  var chip = document.createElement('div'); chip.className = 'img-chip';
1041
  var thumb = document.createElement('img'); thumb.src = img.data; thumb.title = img.name;
1042
  thumb.addEventListener('click', function() { openImageModal(img.data); });
1043
  var name = document.createElement('span'); name.textContent = img.name || 'image';
1044
  name.style.cssText = 'max-width:80px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;';
1045
+ var rm = document.createElement('button'); rm.className = 'img-chip-remove'; rm.textContent = '✕';
1046
  rm.addEventListener('click', (function(i, imgI, row) {
1047
  return function() { problems[i].images.splice(imgI, 1); updateChips(i, row); };
1048
  })(idx, ii, chipsRow));
 
1120
  setTimeout(function() { t.classList.remove('show'); }, 2500);
1121
  }
1122
 
1123
+ // ── EduVerse save ─────────────────────────────────────────────────────────
1124
+
1125
+ function toggleEvPanel() {
1126
+ var panel = document.getElementById('ev-panel');
1127
+ panel.classList.toggle('open');
1128
+ document.getElementById('ev-status').textContent = '';
1129
+ document.getElementById('ev-status').className = 'ev-status';
1130
+ }
1131
+
1132
+ async function saveToEduverse(btn) {
1133
+ var courseId = parseInt(document.getElementById('ev-course-id').value, 10);
1134
+ var chapterId = parseInt(document.getElementById('ev-chapter-id').value, 10);
1135
+ var statusEl = document.getElementById('ev-status');
1136
+
1137
+ if (!courseId || courseId < 1) { statusEl.textContent = 'Enter a valid Course ID.'; statusEl.className = 'ev-status err'; return; }
1138
+ if (!chapterId || chapterId < 1) { statusEl.textContent = 'Enter a valid Chapter ID.'; statusEl.className = 'ev-status err'; return; }
1139
+
1140
+ var toSave = problems.filter(function(q) { return q.exam_ready; });
1141
+ if (!toSave.length) { statusEl.textContent = 'No exam-ready questions to save. Toggle "Exam ready" on questions first.'; statusEl.className = 'ev-status err'; return; }
1142
+
1143
+ btn.disabled = true;
1144
+ btn.innerHTML = '<span class="spin"></span> Saving...';
1145
+ var withImages = toSave.filter(function(q) { return (q.images || []).length > 0; }).length;
1146
+ statusEl.textContent = 'Sending ' + toSave.length + ' questions to EduVerse' + (withImages ? ' (uploading ' + withImages + ' diagram' + (withImages !== 1 ? 's' : '') + ')' : '') + '...';
1147
+ statusEl.className = 'ev-status';
1148
+
1149
+ try {
1150
+ var res = await fetch('/api/save-to-eduverse', {
1151
+ method: 'POST',
1152
+ headers: { 'Content-Type': 'application/json' },
1153
+ body: JSON.stringify({ courseId: courseId, chapterId: chapterId, problems: toSave }),
1154
+ });
1155
+ var data = await res.json();
1156
+ if (!res.ok) { throw new Error(data.detail || 'Save failed'); }
1157
+
1158
+ var msg = '✓ Saved ' + data.saved + ' question' + (data.saved !== 1 ? 's' : '') + ' to EduVerse as drafts.';
1159
+ if (data.imagesUploaded > 0) msg += ' ' + data.imagesUploaded + ' diagram' + (data.imagesUploaded !== 1 ? 's' : '') + ' uploaded.';
1160
+ if (data.failed > 0) { msg += ' ' + data.failed + ' failed (see console).'; console.warn('Failed items:', data.failedItems); }
1161
+ statusEl.textContent = msg;
1162
+ statusEl.className = 'ev-status ok';
1163
+ showToast('Saved ' + data.saved + ' questions to EduVerse.');
1164
+ document.getElementById('refresh-warning').style.display = 'none';
1165
+ } catch(e) {
1166
+ statusEl.textContent = 'Error: ' + e.message;
1167
+ statusEl.className = 'ev-status err';
1168
+ } finally {
1169
+ btn.disabled = false;
1170
+ btn.textContent = 'Save exam-ready questions';
1171
+ }
1172
+ }
1173
+
1174
  function downloadRawText() {
1175
  var a = document.createElement('a');
1176
  a.href = URL.createObjectURL(new Blob([rawText], { type: 'text/plain' }));
 
1185
 
1186
  function inferChapterFromQuestionNumber(questionNumber) {
1187
  var qn = String(questionNumber || '').trim().toUpperCase();
1188
+ var m = qn.match(/^[A-Z]+(\\d+)\\./);
1189
  return m ? parseInt(m[1], 10) : null;
1190
  }
1191
 
 
1281
  return {"text": text, "images": images, "char_count": len(text)}
1282
 
1283
 
1284
+ # LaTeX commands that start with b/f/n/r/t after a single "\". JSON treats \b \f \n \r \t as
1285
+ # control characters, so "\frac" becomes form feed + "rac" and "\to" becomes tab + "o" unless
1286
+ # we double the backslash before json.loads. Longer tokens first so e.g. \rightarrow is not split as \right.
1287
+ _LATEX_JSON_COLLISION_TOKENS = sorted(
1288
+ {
1289
+ "boldsymbol",
1290
+ "textbf",
1291
+ "textit",
1292
+ "textsf",
1293
+ "texttt",
1294
+ "textnormal",
1295
+ "text",
1296
+ "tfrac",
1297
+ "theta",
1298
+ "Theta",
1299
+ "triangle",
1300
+ "tilde",
1301
+ "times",
1302
+ "tanh",
1303
+ "tan",
1304
+ "tau",
1305
+ "to",
1306
+ "Rightarrow",
1307
+ "Rrightarrow",
1308
+ "rightarrow",
1309
+ "rightleftharpoons",
1310
+ "right",
1311
+ "rho",
1312
+ "rangle",
1313
+ "rfloor",
1314
+ "mathrm",
1315
+ "mathcal",
1316
+ "mathit",
1317
+ "mathfrak",
1318
+ "mathtt",
1319
+ "mathbf",
1320
+ "binom",
1321
+ "begin",
1322
+ "beta",
1323
+ "biggl",
1324
+ "biggr",
1325
+ "bigl",
1326
+ "bigr",
1327
+ "big",
1328
+ "nabla",
1329
+ "notin",
1330
+ "neq",
1331
+ "nu",
1332
+ "frac",
1333
+ "fbox",
1334
+ },
1335
+ key=len,
1336
+ reverse=True,
1337
+ )
1338
+
1339
+
1340
+ def _fix_latex_json_escape_collisions(raw: str) -> str:
1341
+ out = raw
1342
+ for tok in _LATEX_JSON_COLLISION_TOKENS:
1343
+ pat = rf"(?<!\\)\\{re.escape(tok)}(?![A-Za-z])"
1344
+ # Callable repl: string repl would interpret `\f` etc. inside the replacement.
1345
+ out = re.sub(pat, lambda m, t=tok: chr(92) * 2 + t, out)
1346
+ return out
1347
+
1348
+
1349
  @app.post("/api/parse-json")
1350
  async def parse_json_route(request: Request):
1351
  raw = (await request.body()).decode("utf-8").strip()
1352
  m = re.search(r"```(?:json)?\n([\s\S]*?)\n?```", raw)
1353
  if m:
1354
  raw = m.group(1).strip()
1355
+ raw = _fix_latex_json_escape_collisions(raw)
1356
+ # Fix remaining unescaped LaTeX backslashes (\alpha, \le, ...) for strict JSON.
1357
+ # (?<![\\]) so we do not treat the second "\" in "\\frac" as starting a new JSON escape.
1358
  fixed = re.sub(
1359
+ r'(?<!\\)\\(.)',
1360
  lambda m: m.group(0) if m.group(1) in '"\\/bfnrtu' else '\\\\' + m.group(1),
1361
  raw,
1362
  )
 
1443
  "figure_reference": q.get("figure_reference"),
1444
  "exam_ready": q.get("exam_ready") is not False,
1445
  "exam_notes": q.get("exam_notes"),
1446
+ "expected_answer": q.get("expected_answer"),
1447
  "assets": image_paths,
1448
  "source": {
1449
  "teammate": teammate,
 
1474
  return {"ok": True}
1475
 
1476
 
1477
+ _BLOOM_MAP = {
1478
+ "remembering": "remembering",
1479
+ "understanding": "understanding",
1480
+ "applying": "applying",
1481
+ "analyzing": "analyzing",
1482
+ "evaluating": "evaluating",
1483
+ "creating": "creating",
1484
+ }
1485
+ _DIFFICULTY_MAP = {"easy": "easy", "medium": "medium", "hard": "hard"}
1486
+ _TYPE_MAP = {"written": "written", "mcq": "mcq", "true_false": "true_false", "essay": "essay"}
1487
+
1488
+
1489
+ def _to_backend_question(q: dict, course_id: int, chapter_id: int, question_file_id: int | None = None) -> dict:
1490
+ question_type = _TYPE_MAP.get(str(q.get("question_type", "")).lower(), "written")
1491
+ difficulty = _DIFFICULTY_MAP.get(str(q.get("difficulty", "")).lower(), "medium")
1492
+ bloom_level = _BLOOM_MAP.get(str(q.get("bloom_level", "")).lower(), "applying")
1493
+
1494
+ payload: dict = {
1495
+ "courseId": course_id,
1496
+ "chapterId": chapter_id,
1497
+ "questionType": question_type,
1498
+ "difficulty": difficulty,
1499
+ "bloomLevel": bloom_level,
1500
+ "questionText": str(q.get("question", "") or ""),
1501
+ "status": "draft",
1502
+ }
1503
+
1504
+ if question_file_id:
1505
+ payload["questionFileId"] = question_file_id
1506
+
1507
+ if question_type in ("written", "essay"):
1508
+ payload["expectedAnswerText"] = str(q.get("expected_answer", "") or "")
1509
+
1510
+ if q.get("hints"):
1511
+ payload["hints"] = str(q["hints"])
1512
+
1513
+ if question_type == "mcq" and q.get("options"):
1514
+ payload["options"] = [
1515
+ {"optionText": str(o.get("optionText", o) if isinstance(o, dict) else o), "isCorrect": bool(o.get("isCorrect", False)) if isinstance(o, dict) else False}
1516
+ for o in q["options"]
1517
+ ]
1518
+ elif question_type == "true_false":
1519
+ payload["options"] = [
1520
+ {"optionText": "True", "isCorrect": True},
1521
+ {"optionText": "False", "isCorrect": False},
1522
+ ]
1523
+
1524
+ return payload
1525
+
1526
+
1527
+ async def _upload_question_image(client: httpx.AsyncClient, token: str, img_b64: str, filename: str) -> int | None:
1528
+ """Upload a base64 image to EduVerse, return fileId or None on failure."""
1529
+ try:
1530
+ header, data = img_b64.split(",", 1)
1531
+ mime = header.split(";")[0].split(":")[1]
1532
+ img_bytes = base64.b64decode(data)
1533
+ except Exception:
1534
+ return None
1535
+
1536
+ async def _do_upload(tok: str):
1537
+ return await client.post(
1538
+ f"{EDUVERSE_API_URL}/api/question-bank/questions/upload-image",
1539
+ headers={"Authorization": f"Bearer {tok}"},
1540
+ files={"image": (filename, img_bytes, mime)},
1541
+ )
1542
+
1543
+ r = await _do_upload(token)
1544
+ if r.status_code == 401:
1545
+ global _eduverse_token
1546
+ _eduverse_token = None
1547
+ token = await _get_eduverse_token()
1548
+ r = await _do_upload(token)
1549
+
1550
+ if not r.is_success:
1551
+ return None
1552
+
1553
+ resp = r.json()
1554
+ file_id = resp.get("fileId") or resp.get("data", {}).get("fileId")
1555
+ return int(file_id) if file_id else None
1556
+
1557
+
1558
+ @app.post("/api/save-to-eduverse")
1559
+ async def save_to_eduverse(payload: dict):
1560
+ """
1561
+ Bulk-save reviewed problems to the EduVerse question bank.
1562
+ Expects: { courseId, chapterId, problems: [...] }
1563
+ Images (base64 data URLs) in each problem's `images` array are uploaded
1564
+ first; the returned fileId is set as questionFileId on the question.
1565
+ """
1566
+ global _eduverse_token
1567
+
1568
+ course_id = payload.get("courseId")
1569
+ chapter_id = payload.get("chapterId")
1570
+ problems = payload.get("problems", [])
1571
+
1572
+ if not isinstance(course_id, int) or course_id < 1:
1573
+ raise HTTPException(status_code=400, detail="courseId must be a positive integer")
1574
+ if not isinstance(chapter_id, int) or chapter_id < 1:
1575
+ raise HTTPException(status_code=400, detail="chapterId must be a positive integer")
1576
+ if not problems:
1577
+ raise HTTPException(status_code=400, detail="No problems provided")
1578
+
1579
+ token = await _get_eduverse_token()
1580
+ images_uploaded = 0
1581
+
1582
+ async with httpx.AsyncClient(timeout=60) as client:
1583
+ # Step 1: upload primary image for each problem that has one
1584
+ question_file_ids: list[int | None] = []
1585
+ for q in problems:
1586
+ imgs = q.get("images") or []
1587
+ if imgs:
1588
+ first = imgs[0]
1589
+ file_id = await _upload_question_image(client, token, first.get("data", ""), first.get("name", "diagram.png"))
1590
+ question_file_ids.append(file_id)
1591
+ if file_id:
1592
+ images_uploaded += 1
1593
+ else:
1594
+ question_file_ids.append(None)
1595
+
1596
+ # Step 2: batch-create questions with questionFileId already set
1597
+ questions = [
1598
+ _to_backend_question(q, course_id, chapter_id, question_file_ids[i])
1599
+ for i, q in enumerate(problems)
1600
+ ]
1601
+
1602
+ BATCH_SIZE = 50
1603
+ all_created, all_failed = [], []
1604
+
1605
+ for i in range(0, len(questions), BATCH_SIZE):
1606
+ batch = questions[i:i + BATCH_SIZE]
1607
+ r = await client.post(
1608
+ f"{EDUVERSE_API_URL}/api/question-bank/questions/batch",
1609
+ json={"courseId": course_id, "defaultChapterId": chapter_id, "questions": batch},
1610
+ headers={"Authorization": f"Bearer {token}"},
1611
+ )
1612
+ if r.status_code == 401:
1613
+ _eduverse_token = None
1614
+ token = await _get_eduverse_token()
1615
+ r = await client.post(
1616
+ f"{EDUVERSE_API_URL}/api/question-bank/questions/batch",
1617
+ json={"courseId": course_id, "defaultChapterId": chapter_id, "questions": batch},
1618
+ headers={"Authorization": f"Bearer {token}"},
1619
+ )
1620
+ if not r.is_success:
1621
+ raise HTTPException(status_code=502, detail=f"EduVerse batch failed: {r.text}")
1622
+ data = r.json()
1623
+ all_created.extend(data.get("created", []))
1624
+ all_failed.extend(
1625
+ [{"rowIndex": f["rowIndex"] + i, **{k: v for k, v in f.items() if k != "rowIndex"}} for f in data.get("failed", [])]
1626
+ )
1627
+
1628
+ return {
1629
+ "saved": len(all_created),
1630
+ "failed": len(all_failed),
1631
+ "failedItems": all_failed,
1632
+ "imagesUploaded": images_uploaded,
1633
+ }
1634
+
1635
+
1636
  @app.get("/output/{filename}")
1637
  def serve_output(filename: str):
1638
  path = OUTPUT_DIR / filename
requirements.txt CHANGED
@@ -3,3 +3,5 @@ uvicorn[standard]
3
  pymupdf
4
  pydantic
5
  python-multipart
 
 
 
3
  pymupdf
4
  pydantic
5
  python-multipart
6
+ httpx
7
+ python-dotenv