-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflask-app.py
More file actions
1788 lines (1554 loc) · 70.6 KB
/
flask-app.py
File metadata and controls
1788 lines (1554 loc) · 70.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
This application provides a deck-level structural analysis and targeted question
generation (slidesqaqa) pipeline for PDF presentations. Using the Gemini API, it extracts
text and visual modalities from PDF slides, builds contextual overlapping windows,
and produces a comprehensive JSON annotation detailing slide roles, learning goals,
and customized comprehension questions.
The pipeline explicitly handles deck-level reconciliation, assessing initial per-slide
question assignments and rewriting or modifying them to balance instructional coverage
and pedagogical scaffolding across the entire slide deck.
Live app: https://slidesqaqa-974767694043.us-west1.run.app/
Repo: https://github.com/blinding2submit/slidesqaqa
"""
from __future__ import annotations # Enable postponed evaluation of annotations
import io # For handling byte streams in memory (e.g., image manipulation)
import json # For encoding and decoding structured data to/from the LLM
import math # For mathematical operations (e.g., calculating grid rows/cols)
import os # For interacting with the operating system, like reading ENV variables
import re # For text processing and cleanup using regular expressions
import textwrap # For wrapping or formatting text strings
import uuid # For generating unique identifiers for processing jobs
from dataclasses import dataclass # For defining clean, typed data container classes
from datetime import datetime, timezone # For generating accurate UTC timestamps
from pathlib import Path # For object-oriented file system path manipulations
import urllib.request # For downloading PDF files from external URLs
import hashlib # For computing MD5 hashes to verify file/URL uniqueness
from typing import Any, Dict, Iterable, List, Optional # For robust static type hinting
import fitz # PyMuPDF: A high-performance PDF rendering and text extraction library
from flask import Flask, Response, render_template_string, request, stream_with_context, send_file, send_from_directory # Web framework components
from google import genai # Google's Generative AI SDK client
from google.genai import types # Google GenAI type definitions (e.g., passing image Parts)
from PIL import Image, ImageDraw, ImageOps # Python Imaging Library for creating contact sheets
from pydantic import BaseModel, Field, ValidationError # For defining strict schemas and validating LLM output
from werkzeug.utils import secure_filename # For sanitizing potentially dangerous user-uploaded filenames
# --- Constants & Configuration ---
# Application title used across logging and context contexts
APP_TITLE = "Slide Deck Q&A Quality Assurance app"
# The Gemini model variant to use. Defaults to a highly capable reasoning model.
DEFAULT_MODEL = os.environ.get("GEMINI_MODEL", "gemini-3.1-pro-preview")
# Hard upper limit on the number of questions allowed per individual slide.
MAX_QUESTIONS_PER_SLIDE = 5
# Local directory where uploaded/downloaded PDFs and output JSON files are temporarily stored.
UPLOAD_DIR = Path("jobs")
# Set of allowed file extensions for uploads to prevent dangerous file executions.
ALLOWED_EXTENSIONS = {".pdf"}
# Markers used to identify the final structured payload within the streamed string response.
BEGIN_JSON_MARKER = "\n===== FINAL JSON BEGIN =====\n"
END_JSON_MARKER = "\n===== FINAL JSON END =====\n"
HTML_PAGE = """
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Slide Deck Q&A Quality Assurance app</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="/scroll.svg" type="image/svg+xml">
<style>
:root {
--bg: #0b1020;
--panel: #121931;
--panel-2: #0f1530;
--text: #e7ecff;
--muted: #a8b3d6;
--accent: #7aa2ff;
--accent-2: #9fe3c1;
--border: rgba(255,255,255,0.12);
--danger: #ffb4b4;
}
* { box-sizing: border-box; }
body {
margin: 0;
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: linear-gradient(180deg, #0a0f1f 0%, #0d1428 100%);
color: var(--text);
}
.wrap {
max-width: 1200px;
margin: 0 auto;
padding: 24px;
}
h1 {
margin: 0 0 6px 0;
font-size: 28px;
line-height: 1.2;
}
.sub {
margin: 0 0 18px 0;
color: var(--muted);
max-width: 900px;
}
.grid {
display: grid;
grid-template-columns: 380px 1fr;
gap: 18px;
align-items: start;
}
.panel {
background: rgba(18,25,49,0.92);
border: 1px solid var(--border);
border-radius: 16px;
padding: 16px;
backdrop-filter: blur(8px);
box-shadow: 0 14px 36px rgba(0,0,0,0.28);
}
.panel a {
color: var(--accent);
}
.panel a:visited {
color: #cba6ff;
}
label {
display: block;
font-size: 13px;
color: var(--muted);
margin-bottom: 6px;
}
input[type="text"], input[type="password"], textarea, input[type="file"] {
width: 100%;
border: 1px solid var(--border);
background: var(--panel-2);
color: var(--text);
border-radius: 10px;
padding: 10px 12px;
font: inherit;
}
textarea {
min-height: 110px;
resize: vertical;
}
.row { margin-bottom: 14px; }
.hint {
font-size: 12px;
color: var(--muted);
margin-top: 6px;
line-height: 1.4;
}
.btns {
display: flex;
gap: 10px;
margin-top: 6px;
flex-wrap: wrap;
}
button {
appearance: none;
border: none;
border-radius: 10px;
padding: 10px 14px;
font: inherit;
cursor: pointer;
background: var(--accent);
color: #081022;
font-weight: 600;
}
button.secondary {
background: rgba(255,255,255,0.08);
color: var(--text);
border: 1px solid var(--border);
}
button:disabled {
opacity: 0.55;
cursor: not-allowed;
}
.status, .json {
min-height: 280px;
max-height: 75vh;
overflow: auto;
border: 1px solid var(--border);
background: #091022;
border-radius: 12px;
padding: 14px;
white-space: pre-wrap;
word-break: break-word;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12.5px;
line-height: 1.45;
}
.json {
background: #0a1226;
}
.meta {
display: flex;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
margin-bottom: 10px;
color: var(--muted);
font-size: 13px;
}
.ok { color: var(--accent-2); }
.err { color: var(--danger); }
.footer {
margin-top: 16px;
color: var(--muted);
font-size: 12px;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 10px;
}
th, td {
border: 1px solid var(--border);
padding: 8px 12px;
text-align: left;
}
th {
background: rgba(255,255,255,0.05);
font-weight: 600;
}
h2 {
margin-top: 0;
margin-bottom: 12px;
font-size: 20px;
color: var(--accent);
}
h3 {
font-size: 16px;
margin-top: 16px;
margin-bottom: 8px;
}
.viz-section {
margin-bottom: 16px;
}
@media (max-width: 960px) {
.grid { grid-template-columns: 1fr; }
}
.github-corner {
position: fixed;
top: 0;
right: 0;
z-index: 1000;
width: 200px;
height: 200px;
pointer-events: none;
}
.github-corner a {
position: absolute;
top: 40px;
right: -50px;
width: 260px;
padding: 10px 0;
background: #111;
color: #fff;
text-align: center;
text-decoration: none;
font-weight: 700;
letter-spacing: 0.5px;
transform: rotate(45deg);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.35);
pointer-events: auto;
}
.github-corner a:hover {
background: #1f4aa8;
}
@media (max-width: 700px) {
.github-corner {
width: 150px;
height: 150px;
}
.github-corner a {
top: 26px;
right: -58px;
width: 210px;
font-size: 13px;
}
}
</style>
</head>
<body>
<div class="github-corner" aria-hidden="false">
<a href="https://github.com/blinding2submit/slidesqaqa" target="_blank"> Fork me on GitHub </a>
</div>
<div class="wrap">
<img src="scroll.svg" width=30 align=right />
<h1>Slide Deck Q&A Quality Assurance app</h1>
<p class="sub">
Upload a PDF slide deck (or just provide its URL), give it a citation, and the app will stream planning status while it builds
a hierarchical JSON annotation with deck analysis, variable per-slide question budgets, and slide-level question sets.
</p>
<div class="panel" style="margin-bottom: 24px;">
<h2>Theory of Operation</h2>
<p>The system operates by first extracting text and visual information from the uploaded PDF presentation deck. Large decks are chunked into contiguous, overlapping sliding windows (e.g., 8 slides per window with a 2-slide overlap). This preserves contextual awareness, allowing the system to track transitions and narrative flow across boundaries without hitting the generative model's context limits.</p>
<p>Following extraction, the system infers crucial instructional attributes for every slide, such as its modality (e.g., diagram, table, text) and its specific role in the presentation (e.g., mechanism, summary, agenda). These attributes strictly dictate the mix of generated question types (e.g., diagram labeling vs. multiple-choice) and the initial per-slide question budget, balancing instructional importance with evidence richness.</p>
<p>Finally, the system executes targeted slide-level question generation and performs deck-level reconciliation using precise 1-5 rubrics. Provisional question sets are evaluated on Coverage (from poor facts to strong representation of core concepts), Scaffolding (from random questions to coherent progression), and Fidelity (ensuring answers are derivable purely from the slide). The reconciliation step uses these scores to zero out redundancies, balance coverage across learning goals, and shape a cohesive final question distribution.</p>
</div>
<div class="grid">
<div class="panel">
<form id="deck-form">
<div class="row">
<label for="deck_file">PDF deck</label>
<input id="deck_file" name="deck_file" type="file" accept=".pdf,application/pdf">
<div class="hint">One PDF only. Either upload a file or provide a URL below.</div>
</div>
<div class="row">
<label for="citation">Academic citation</label>
<textarea id="citation" name="citation" placeholder="Author, A. A. (2026). Lecture X: Title [Course lecture slides]. Course name, Institution. Or e.g., Author26" required></textarea>
</div>
<div class="row">
<label for="deck_url">Canonical deck URL (optional)</label>
<input id="deck_url" name="deck_url" type="text" placeholder="https://example.edu/lecture.pdf">
</div>
<div class="row" style="display: flex; gap: 10px;">
<div style="flex: 1;">
<label for="start_page">Start PDF page</label>
<input id="start_page" name="start_page" type="text" value="1" pattern="^[1-9][0-9]*$" title="Must be a positive integer or blank">
</div>
<div style="flex: 1;">
<label for="end_page">End PDF page</label>
<input id="end_page" name="end_page" type="text" placeholder="End" pattern="^[1-9][0-9]*$" title="Must be a positive integer or blank">
</div>
</div>
<div class="row" style="display: flex; gap: 10px;">
<div style="flex: 1;">
<label for="budget_mode_mean" style="display: flex; align-items: center; gap: 6px; cursor: pointer;">
<input type="radio" name="budget_mode" id="budget_mode_mean" value="mean" style="width: auto; margin: 0;">
Questions per slide
</label>
<input id="target_mean" name="target_mean" type="text" value="2.5" pattern="^[0-9]+(\\.[0-9]+)?$" title="Must be a positive number or blank">
</div>
<div style="flex: 1;">
<label for="budget_mode_total" style="display: flex; align-items: center; gap: 6px; cursor: pointer;">
<input type="radio" name="budget_mode" id="budget_mode_total" value="total" style="width: auto; margin: 0;">
Total questions
</label>
<input id="target_total" name="target_total" type="text" placeholder="" pattern="^[1-9][0-9]*$" title="Must be a positive integer or blank">
</div>
</div>
<div class="row">
<label for="model">Gemini model</label>
<input id="model" name="model" type="text" value="{{ default_model }}" required>
</div>
<div class="row">
<label for="api_key"><a href="https://aistudio.google.com/api-keys" target="_blank" style="color: inherit; text-decoration: underline;">Bring your own Gemini API key</a> (required)</label>
<input id="api_key" name="api_key" type="password" required>
</div>
<div class="btns">
<button id="submit-btn" type="submit">Analyze deck</button>
<button id="download-btn" class="secondary" type="button" disabled>Download JSON</button>
</div>
</form>
<div class="footer">
This page streams status logs from Flask while the analysis runs.
</div>
</div>
<div class="panel">
<div class="meta">
<div>Status log</div>
<div id="run-state">Idle</div>
</div>
<pre id="status" class="status"></pre>
<div class="meta" style="margin-top: 16px;">
<div>Final JSON</div>
<div id="json-state">No result yet</div>
</div>
<pre id="json" class="json"></pre>
</div>
</div>
<div id="visualizations" style="display: none; margin-top: 24px;">
<div class="panel" style="margin-bottom: 24px;">
<h2>Executive Summary</h2>
<div id="exec-summary"></div>
</div>
<div class="panel" style="margin-bottom: 24px;">
<h2>Deck Outline</h2>
<div id="deck-outline"></div>
</div>
<div class="panel" style="margin-bottom: 24px;">
<h2>Question Bank</h2>
<div id="question-bank"></div>
</div>
<div class="panel" style="margin-bottom: 24px;">
<h2>Evaluation Matrix</h2>
<div id="evaluation-matrix" style="overflow-x: auto;"></div>
</div>
</div>
</div>
<script>
(() => {
const form = document.getElementById("deck-form");
const statusEl = document.getElementById("status");
const jsonEl = document.getElementById("json");
const runStateEl = document.getElementById("run-state");
const jsonStateEl = document.getElementById("json-state");
const submitBtn = document.getElementById("submit-btn");
const downloadBtn = document.getElementById("download-btn");
const visualizerEl = document.getElementById("visualizations");
const execSummaryEl = document.getElementById("exec-summary");
const deckOutlineEl = document.getElementById("deck-outline");
const questionBankEl = document.getElementById("question-bank");
const evalMatrixEl = document.getElementById("evaluation-matrix");
const BEGIN = "===== FINAL JSON BEGIN =====";
const END = "===== FINAL JSON END =====";
let latestJson = "";
function setRunning(isRunning) {
submitBtn.disabled = isRunning;
runStateEl.textContent = isRunning ? "Running" : "Idle";
runStateEl.className = isRunning ? "ok" : "";
}
function clearOutput() {
statusEl.textContent = "";
jsonEl.textContent = "";
jsonStateEl.textContent = "No result yet";
jsonStateEl.className = "";
latestJson = "";
downloadBtn.disabled = true;
visualizerEl.style.display = "none";
execSummaryEl.innerHTML = "";
deckOutlineEl.innerHTML = "";
questionBankEl.innerHTML = "";
evalMatrixEl.innerHTML = "";
}
function escapeHtml(unsafe) {
if (typeof unsafe !== 'string') return '';
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function renderExecSummary(data) {
const analysis = data.deck_analysis || {};
const recon = data.reconciliation || {};
let html = `<div class="viz-section">
<p><strong>Topic:</strong> ${escapeHtml(analysis.deck_topic)}</p>
<p><strong>Target Audience:</strong> ${escapeHtml(analysis.target_audience)}</p>
<p><strong>Global Notes:</strong> ${escapeHtml(analysis.global_notes)}</p>
</div>`;
if (analysis.learning_goals && analysis.learning_goals.length > 0) {
html += `<div class="viz-section">
<h3>Learning Goals</h3>
<ul>
${analysis.learning_goals.map(g => `<li>${escapeHtml(g)}</li>`).join('')}
</ul>
</div>`;
}
if (recon.uncovered_learning_goals && recon.uncovered_learning_goals.length > 0) {
html += `<div class="viz-section">
<h3>Uncovered Learning Goals</h3>
<ul>
${recon.uncovered_learning_goals.map(g => `<li>${escapeHtml(g)}</li>`).join('')}
</ul>
</div>`;
}
execSummaryEl.innerHTML = html;
}
function renderDeckOutline(data) {
const analysis = data.deck_analysis || {};
const slides = data.slides || [];
const slidesByNum = {};
slides.forEach(s => slidesByNum[s.slide_number] = s);
let html = '';
if (analysis.sections && analysis.sections.length > 0) {
html += `<ol>`;
analysis.sections.forEach(sec => {
html += `<li>
<strong>${escapeHtml(sec.section_title)}</strong>
<p style="margin: 4px 0 8px 0; color: var(--muted);">${escapeHtml(sec.section_summary)}</p>
<ul>`;
for (let i = sec.start_slide; i <= sec.end_slide; i++) {
const s = slidesByNum[i];
if (s) {
html += `<li><em>Slide ${s.slide_number}:</em> ${escapeHtml(s.slide_title)} - ${escapeHtml(s.local_summary)}</li>`;
}
}
html += ` </ul>
</li>`;
});
html += `</ol>`;
} else {
html = '<p>No sections found.</p>';
}
deckOutlineEl.innerHTML = html;
}
function renderQuestionBank(data) {
const slides = data.slides || [];
let html = '';
let hasQuestions = false;
slides.forEach(s => {
if (s.questions && s.questions.length > 0) {
hasQuestions = true;
html += `<h3>Slide ${s.slide_number}: ${escapeHtml(s.slide_title)}</h3>`;
html += `<dl style="margin-bottom: 24px;">`;
s.questions.forEach(q => {
html += `<dt style="font-weight: bold; margin-top: 12px;">Q: ${escapeHtml(q.prompt)}</dt>`;
if (q.options && q.options.length > 0) {
html += `<dd style="margin-left: 20px; margin-top: 4px;">
<ul style="margin: 0; padding-left: 20px;">
${q.options.map(opt => `<li>${escapeHtml(opt)}</li>`).join('')}
</ul>
</dd>`;
}
html += `<dd style="margin-left: 20px; margin-top: 4px; font-style: italic; color: var(--accent-2);">A: ${escapeHtml(q.answer)}</dd>`;
});
html += `</dl>`;
}
});
if (!hasQuestions) {
html = '<p>No questions generated for this deck.</p>';
}
questionBankEl.innerHTML = html;
}
function renderEvalMatrix(data) {
const slides = data.slides || [];
const reconActions = data.reconciliation?.revised_slide_actions || [];
const reconMap = {};
reconActions.forEach(a => reconMap[a.slide_number] = a);
let html = `<table>
<thead>
<tr>
<th>Slide</th>
<th>Role</th>
<th>Budget</th>
<th>Coverage</th>
<th>Scaffolding</th>
<th>Reconciliation Note</th>
</tr>
</thead>
<tbody>`;
slides.forEach(s => {
const evalData = s.evaluation || {};
const recon = reconMap[s.slide_number];
const covScore = evalData.coverage_score !== null && evalData.coverage_score !== undefined ? evalData.coverage_score : '-';
const scafScore = evalData.scaffolding_score !== null && evalData.scaffolding_score !== undefined ? evalData.scaffolding_score : '-';
const reconNote = recon ? `${escapeHtml(recon.action)}: ${escapeHtml(recon.reason)}` : '';
html += `<tr>
<td>${s.slide_number}</td>
<td>${escapeHtml(s.role_in_deck)}</td>
<td>${s.question_budget}</td>
<td>${covScore}</td>
<td>${scafScore}</td>
<td>${reconNote}</td>
</tr>`;
});
html += `</tbody></table>`;
evalMatrixEl.innerHTML = html;
}
function renderVisualizations(data) {
visualizerEl.style.display = "block";
renderExecSummary(data);
renderDeckOutline(data);
renderQuestionBank(data);
renderEvalMatrix(data);
}
const deckFile = document.getElementById("deck_file");
const deckUrl = document.getElementById("deck_url");
function updateFileRequirement() {
if (deckUrl.value.trim() !== "") {
deckFile.required = false;
} else {
deckFile.required = true;
}
}
deckUrl.addEventListener("input", updateFileRequirement);
// Run once on load
updateFileRequirement();
// --- Budget Radio Button Logic ---
let lastCheckedRadio = document.querySelector('input[name="budget_mode"]:checked');
const budgetRadios = document.querySelectorAll('input[name="budget_mode"]');
budgetRadios.forEach(radio => {
radio.addEventListener('click', function(e) {
if (lastCheckedRadio === this) {
this.checked = false;
lastCheckedRadio = null;
} else {
lastCheckedRadio = this;
}
});
});
const targetMeanInput = document.getElementById('target_mean');
const targetTotalInput = document.getElementById('target_total');
const budgetModeMean = document.getElementById('budget_mode_mean');
const budgetModeTotal = document.getElementById('budget_mode_total');
function updateRadioFromInput(inputEl, radioEl) {
if (inputEl.value.trim() !== "") {
radioEl.checked = true;
lastCheckedRadio = radioEl;
} else {
radioEl.checked = false;
if (lastCheckedRadio === radioEl) {
lastCheckedRadio = null;
}
}
}
targetMeanInput.addEventListener('input', () => updateRadioFromInput(targetMeanInput, budgetModeMean));
targetTotalInput.addEventListener('input', () => updateRadioFromInput(targetTotalInput, budgetModeTotal));
downloadBtn.addEventListener("click", () => {
if (!latestJson) return;
const blob = new Blob([latestJson], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "deck_annotation.json";
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
});
form.addEventListener("submit", async (ev) => {
ev.preventDefault();
clearOutput();
setRunning(true);
jsonStateEl.textContent = "Waiting for result";
const formData = new FormData(form);
try {
const resp = await fetch("/analyze", {
method: "POST",
body: formData
});
if (!resp.ok || !resp.body) {
const text = await resp.text();
throw new Error(text || `HTTP ${resp.status}`);
}
const reader = resp.body.getReader();
const decoder = new TextDecoder();
let allText = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
const chunk = decoder.decode(value, { stream: true });
allText += chunk;
const beginIdx = allText.indexOf(BEGIN);
if (beginIdx === -1) {
statusEl.textContent = allText;
} else {
statusEl.textContent = allText.slice(0, beginIdx).trimEnd();
const afterBegin = allText.slice(beginIdx + BEGIN.length);
const endIdx = afterBegin.indexOf(END);
if (endIdx === -1) {
jsonEl.textContent = afterBegin.trimStart();
jsonStateEl.textContent = "Receiving JSON";
jsonStateEl.className = "ok";
} else {
latestJson = afterBegin.slice(0, endIdx).trim();
jsonEl.textContent = latestJson;
jsonStateEl.textContent = "JSON complete";
jsonStateEl.className = "ok";
downloadBtn.disabled = false;
try {
const parsed = JSON.parse(latestJson);
renderVisualizations(parsed);
} catch (e) {
console.error("Failed to parse JSON for visualizations:", e);
}
}
}
statusEl.scrollTop = statusEl.scrollHeight;
jsonEl.scrollTop = jsonEl.scrollHeight;
}
if (!latestJson) {
jsonStateEl.textContent = "No final JSON marker found";
jsonStateEl.className = "err";
}
} catch (err) {
statusEl.textContent += "\\n[client error] " + (err && err.message ? err.message : String(err));
runStateEl.textContent = "Error";
runStateEl.className = "err";
jsonStateEl.textContent = "Failed";
jsonStateEl.className = "err";
} finally {
setRunning(false);
}
});
})();
</script>
</body>
</html>
"""
FIELD_DESCRIPTIONS: Dict[str, str] = {
"schema_version": "Version of this JSON schema.",
"deck_metadata": "Metadata and citation for the source slide deck.",
"deck_analysis": "Whole-deck interpretation including topic, section structure, learning goals, and global coverage notes.",
"reconciliation": "Deck-level reconciliation output describing final balancing, reductions, or expansions after provisional slide annotations.",
"slides": "Ordered list of slide records, one per slide in the deck.",
"deck_metadata.deck_id": "Stable identifier for this deck.",
"deck_metadata.deck": "Full academic citation for the deck.",
"deck_metadata.deck_url": "Original source URL for the deck, if known.",
"deck_metadata.source_file": "Local uploaded PDF filename.",
"deck_metadata.total_slides": "Total number of PDF pages processed as slides.",
"deck_metadata.processed_at": "UTC timestamp when this JSON was produced.",
"deck_analysis.deck_topic": "Short description of the overall topic of the deck.",
"deck_analysis.target_audience": "Estimated audience level; for example undergraduate, graduate, or mixed.",
"deck_analysis.learning_goals": "List of deck-level learning goals inferred from the slides.",
"deck_analysis.sections": "Ordered list of section objects with start and end slides, title, and summary.",
"deck_analysis.coverage_targets": "Deck-level content targets such as text, diagram, table, chart, layout-aware, or image-plus-text.",
"deck_analysis.global_notes": "Important global caveats, ambiguities, or observations.",
"reconciliation.revised_slide_actions": "Per-slide reconciliation actions after reviewing the provisional full-deck annotation set.",
"reconciliation.deck_reconciliation_notes": "Global notes about redundancy, balancing, and quality adjustments across the deck.",
"reconciliation.uncovered_learning_goals": "Deck learning goals that remain weakly covered after reconciliation.",
"reconciliation.redundancy_warnings": "Warnings about overlapping or repeated question sets across slides.",
"slides[].slide_id": "Stable identifier for a slide within the deck.",
"slides[].slide_number": "1-based slide number corresponding to the PDF page order.",
"slides[].slide_title": "Visible title on the slide if present; otherwise a concise generated title.",
"slides[].modality_type": "Dominant visual form of the slide; for example text, diagram, table, chart, layout-aware, image-plus-text, or mixed.",
"slides[].role_in_deck": "Instructional role of the slide within the deck; for example title, agenda, transition, definition, example, mechanism, result, summary, or appendix.",
"slides[].local_summary": "One- or two-sentence summary of the slide's main instructional content.",
"slides[].key_concepts": "List of key concepts explicitly present on the slide.",
"slides[].evidence_regions": "List of human-readable descriptions of important visible regions on the slide.",
"slides[].eligible_for_questions": "Whether the slide should receive any comprehension questions.",
"slides[].eligibility_reason": "Explanation for why the slide should or should not receive questions.",
"slides[].question_budget": "Recommended number of questions for this slide in deck context.",
"slides[].question_mix": "Recommended mix of question types for this slide.",
"slides[].questions": "Variable-length list of question objects for this slide.",
"slides[].questions[].question_id": "Stable identifier for a question within a slide.",
"slides[].questions[].question_type": "Controlled label for the question form or reasoning type.",
"slides[].questions[].prompt": "Question text shown to the learner.",
"slides[].questions[].options": "List of answer options for a multiple-choice item; empty otherwise.",
"slides[].questions[].answer": "Gold answer or bounded reference answer grounded in the slide.",
"slides[].questions[].evidence_span": "Short description of where the answer is visible on the slide.",
"slides[].questions[].difficulty": "Relative difficulty label such as low, medium, or high.",
"slides[].questions[].purpose": "Instructional purpose such as terminology, relation check, interpretation, or synthesis.",
"slides[].questions[].fidelity_score": "1-5 judgment of whether the question is answerable from the slide alone.",
"slides[].questions[].fidelity_notes": "Short rationale for the fidelity score.",
"slides[].evaluation": "Slide-level evaluation for the full question bundle.",
"slides[].evaluation.coverage_score": "1-5 score for how well the slide's question bundle covers the slide's important content; null when the slide intentionally has no questions.",
"slides[].evaluation.coverage_notes": "Short rationale for the coverage score.",
"slides[].evaluation.scaffolding_score": "1-5 score for how well the question bundle forms an instructional progression; null when the slide intentionally has no questions.",
"slides[].evaluation.scaffolding_notes": "Short rationale for the scaffolding score."
}
# Restricted vocabulary representing the dominant visual forms a slide might take.
MODALITY_CHOICES = ["text", "diagram", "table", "chart", "layout-aware", "image-plus-text", "mixed"]
# Restricted vocabulary representing the pedagogical or structural purpose of a slide.
ROLE_CHOICES = ["title", "agenda", "transition", "definition", "example", "mechanism", "comparison", "result", "summary", "administrative", "appendix", "review", "reference"]
# Restricted vocabulary representing the specific format or cognitive skill targeted by a generated question.
QUESTION_TYPE_CHOICES = ["fill_blank", "mcq", "open_ended", "short_answer", "diagram_labeling", "comparison", "interpretation", "evidence_localization"]
class LocalSectionHypothesis(BaseModel):
section_title: str
start_slide: int
end_slide: int
section_summary: str
class SlidePlan(BaseModel):
slide_number: int
slide_title: str
local_summary: str
modality_type: str
role_in_deck: str
eligible_for_questions: bool
eligibility_reason: str
question_budget: int = Field(ge=0, le=MAX_QUESTIONS_PER_SLIDE)
question_mix: List[str]
class WindowPlan(BaseModel):
local_section_hypotheses: List[LocalSectionHypothesis]
slides: List[SlidePlan]
class SectionModel(BaseModel):
section_id: str
start_slide: int
end_slide: int
section_title: str
section_summary: str
class DeckPlan(BaseModel):
deck_topic: str
target_audience: str
learning_goals: List[str]
sections: List[SectionModel]
coverage_targets: List[str]
global_notes: str
slides: List[SlidePlan]
class QuestionModel(BaseModel):
question_id: str
question_type: str
prompt: str
options: List[str] = Field(default_factory=list)
answer: str
evidence_span: str
difficulty: str
purpose: str
fidelity_score: int = Field(ge=1, le=5)
fidelity_notes: str
class SlideEvaluationModel(BaseModel):
coverage_score: int = Field(ge=1, le=5)
coverage_notes: str
scaffolding_score: int = Field(ge=1, le=5)
scaffolding_notes: str
class SlideAnnotationModel(BaseModel):
key_concepts: List[str]
evidence_regions: List[str]
questions: List[QuestionModel]
evaluation: SlideEvaluationModel
class ReconcileAction(BaseModel):
slide_number: int
action: str
new_question_budget: int = Field(ge=0, le=MAX_QUESTIONS_PER_SLIDE)
reason: str
class ReconciliationModel(BaseModel):
revised_slide_actions: List[ReconcileAction]
deck_reconciliation_notes: str
uncovered_learning_goals: List[str]
redundancy_warnings: List[str]
@dataclass
class SlideAsset:
slide_number: int
png_bytes: bytes
text: str
text_snippet: str
# --- LLM Prompts ---
# Prompt for the initial sliding-window analysis phase. Instructs the LLM to extract roles, modalities, and budgets.
WINDOW_PLANNER_PROMPT = """
You are analyzing a contiguous window from a larger lecture slide deck.
For each slide in this window:
- infer slide_title
- write a short local_summary
- assign modality_type
- assign role_in_deck
- decide whether the slide is eligible for learner-facing comprehension questions
- give an eligibility_reason
- assign a question_budget from 0 to 5
- assign a question_mix
Important:
- Use neighboring slides in the window to reason about redundancy and transitions.
- It is acceptable to assign zero questions.
- Do not force a fixed number of questions.
- Favor low budgets for title, agenda, transition, administrative, appendix, and repeated recap slides.
- Favor higher budgets for rich mechanism, comparison, result, diagram, chart, table, or synthesis slides.
- question_mix must use only these values:
["fill_blank", "mcq", "open_ended", "short_answer", "diagram_labeling", "comparison", "interpretation", "evidence_localization"]
- modality_type must use only these values:
["text", "diagram", "table", "chart", "layout-aware", "image-plus-text", "mixed"]
- role_in_deck must use only these values:
["title", "agenda", "transition", "definition", "example", "mechanism", "comparison", "result", "summary", "administrative", "appendix", "review", "reference"]
Return JSON only. Do not include explanatory prose outside JSON.
""".strip()
# Prompt for the synthesis phase. Instructs the LLM to merge overlapping window plans into a coherent deck outline.
DECK_SYNTHESIS_PROMPT = """
You are merging overlapping window-level analyses of one lecture slide deck into one final deck plan.
Goals:
1. Infer the deck topic and likely target audience.
2. Infer deck-level learning goals.
3. Produce section boundaries for the full deck.
4. Resolve conflicting window-level slide plans conservatively.
5. Return exactly one slide plan object per slide number.
Important:
- Preserve zero-question slides when they are non-instructional, redundant, or too thin.
- Some slides may deserve more than three questions.
- Keep question budgets based on instructional importance, self-containedness, evidence richness, and novelty.
- Use only the allowed label vocabularies already present in the window plans.
- Sections should be contiguous and ordered.
Return JSON only. Do not include explanatory prose outside JSON.
""".strip()
# Prompt for generating the actual comprehension questions for a single slide based on its synthesized plan.
SLIDE_ANNOTATOR_PROMPT = """
You are generating slidesqaqa annotations for one slide within a lecture deck.
Use both the local slide evidence and the provided deck context.
Your tasks:
1. Identify key_concepts explicitly present on the slide.
2. Identify 2 to 6 evidence_regions as short human-readable descriptions of important visible regions.
3. Generate exactly the assigned question budget in the supplied question mix.
4. Every question must be answerable from the slide alone.
5. Every answer must be bounded and evidence-grounded.
6. Use deck context only to decide what is educationally important. Do not answer from hidden lecture knowledge.
7. Avoid redundancy with the neighboring slides when possible.
Question-writing guidance:
- On text slides, favor terminology, distinctions, and concise explanation.
- On diagram slides, favor component labeling, relationships, flow, and mechanism.
- On table/chart slides, favor lookup, comparison, trend, and interpretation.
- On layout-aware slides, favor spatial or grouping-based reasoning when relevant.
- If a question_type is mcq, include exactly 4 options.
- If a question_type is not mcq, options must be an empty list.
- fidelity_score must be an integer from 1 to 5.
- coverage_score and scaffolding_score must be integers from 1 to 5.
Coverage guidance:
- 1 means poor coverage or repeated tiny facts.
- 3 means adequate coverage of the main concept and at least one secondary element.
- 5 means strong coverage of the slide's important visible content.
Scaffolding guidance:
- 1 means random or disconnected.
- 3 means reasonable progression.
- 5 means coherent progression from simpler to deeper understanding.
Return JSON only. Do not include explanatory prose outside JSON.
""".strip()
# Prompt for the final reconciliation phase. Evaluates the generated question set and balances coverage/scaffolding.
RECONCILIATION_PROMPT = """
You are reconciling a provisional slidesqaqa annotation set for a full lecture deck.
You are given:
- deck metadata
- deck analysis
- all slide plans
- all provisional slide annotations