Kattine commited on
Commit
7ff3e94
·
1 Parent(s): 3877b20

Phase 8: provider toggle, layout fix, markdown rendering

Browse files
.dockerignore ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Keep the image small: exclude local artifacts that are not needed at runtime.
2
+ venv/
3
+ .venv/
4
+ __pycache__/
5
+ *.pyc
6
+ .git/
7
+ .env
8
+ data/raw/
9
+ data/processed/
10
+ data/outputs/
11
+ models/
12
+ notebooks/
13
+ *.zip
14
+ .DS_Store
Dockerfile ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Dockerfile for deploying Dialectica on Hugging Face Spaces (Docker SDK).
2
+ #
3
+ # Notes specific to Spaces:
4
+ # * The app must listen on port 7860.
5
+ # * Only /tmp is writable, so all model caches are redirected there.
6
+ # * The fine-tuned DistilBERT is pulled from the Hugging Face Hub at startup
7
+ # (set MODEL_REPO below), so it does not need to be baked into the image.
8
+
9
+ FROM python:3.11-slim
10
+
11
+ # System deps for PyMuPDF and general builds.
12
+ RUN apt-get update && apt-get install -y --no-install-recommends \
13
+ build-essential \
14
+ && rm -rf /var/lib/apt/lists/*
15
+
16
+ # Redirect all model/library caches to /tmp (the only writable dir on Spaces).
17
+ ENV HF_HOME=/tmp/hf_home \
18
+ TRANSFORMERS_CACHE=/tmp/hf_home \
19
+ SENTENCE_TRANSFORMERS_HOME=/tmp/st_home \
20
+ XDG_CACHE_HOME=/tmp/cache \
21
+ MPLCONFIGDIR=/tmp/mpl
22
+
23
+ WORKDIR /app
24
+
25
+ # Install Python dependencies first for better layer caching.
26
+ # Install the CPU build of torch explicitly to avoid pulling large CUDA wheels.
27
+ COPY requirements-app.txt .
28
+ RUN pip install --no-cache-dir "torch>=2.2.0" --index-url https://download.pytorch.org/whl/cpu
29
+ RUN pip install --no-cache-dir --upgrade -r requirements-app.txt
30
+
31
+ # Copy the application code.
32
+ COPY . .
33
+
34
+ # Spaces expects the app on port 7860.
35
+ EXPOSE 7860
36
+
37
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
config.py CHANGED
@@ -291,3 +291,29 @@ class DeepModelConfig:
291
  # for a speedup if your macOS supports it.
292
  use_bf16: bool = False
293
  seed: int = 42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
291
  # for a speedup if your macOS supports it.
292
  use_bf16: bool = False
293
  seed: int = 42
294
+
295
+
296
+
297
+ # Product layer (Dialectica app) parameters
298
+
299
+ @dataclass
300
+ class ProductConfig:
301
+ """Configuration for the Dialectica application backend."""
302
+
303
+ # the fine-tuned classifier saved by Phase 4b
304
+ classifier_dir: str = "models/distilbert_bloom"
305
+ # sentence embedding model for matching a question to a concept
306
+ embed_model: str = "all-MiniLM-L6-v2"
307
+
308
+ # expert dialogue provider: "deepseek" (default, no rate limits) or "gemini"
309
+ provider: str = "deepseek"
310
+ deepseek_model: str = "deepseek-v4-flash"
311
+ gemini_model: str = "gemini-2.5-flash"
312
+
313
+ # how much material text to inject as the expert's knowledge context
314
+ max_context_chars: int = 12000
315
+ # number of key concepts to extract from uploaded material
316
+ num_concepts: int = 10
317
+ # minimum cosine similarity to attribute a question to a concept
318
+ concept_match_threshold: float = 0.25
319
+ max_question_length: int = 64
frontend/index.html ADDED
@@ -0,0 +1,514 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Dialectica — interrogate the expert</title>
7
+ <link rel="preconnect" href="https://fonts.googleapis.com">
8
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
9
+ <link href="https://fonts.googleapis.com/css2?family=Newsreader:ital,opsz,wght@0,6..72,400;0,6..72,500;1,6..72,400&family=Inter:wght@400;500;600&family=IBM+Plex+Mono:wght@400;500;600&display=swap" rel="stylesheet">
10
+ <script src="https://cdn.jsdelivr.net/npm/marked@12.0.0/marked.min.js"></script>
11
+ <style>
12
+ :root {
13
+ --desk: #1B1D23;
14
+ --paper: #EDEAE2;
15
+ --paper-inset: #E3DFD5;
16
+ --ink: #22262E;
17
+ --ink-soft: #61656d;
18
+ --rule: rgba(34,38,46,.14);
19
+ --rule-strong: rgba(34,38,46,.28);
20
+ --surface: #9FB8C6;
21
+ --mech: #3F6E96;
22
+ --crit: #B14A2F;
23
+ --crit-ink: #8d3a23;
24
+ --paper-shadow: 0 1px 0 rgba(255,255,255,.5) inset, 0 18px 40px rgba(0,0,0,.32);
25
+ }
26
+ * { box-sizing: border-box; margin: 0; padding: 0; }
27
+ html, body { height: 100%; }
28
+ body {
29
+ background: var(--desk);
30
+ color: var(--ink);
31
+ font-family: 'Inter', sans-serif;
32
+ font-size: 15px;
33
+ line-height: 1.5;
34
+ -webkit-font-smoothing: antialiased;
35
+ }
36
+ .mono { font-family: 'IBM Plex Mono', monospace; }
37
+
38
+ /* ---- header ---- */
39
+ header {
40
+ display: flex; align-items: baseline; justify-content: space-between;
41
+ padding: 22px 32px 18px; color: var(--paper);
42
+ border-bottom: 1px solid rgba(237,234,226,.12);
43
+ }
44
+ .wordmark {
45
+ font-family: 'Newsreader', serif; font-weight: 500; font-size: 30px;
46
+ letter-spacing: .01em;
47
+ }
48
+ .wordmark .dot { color: var(--crit); }
49
+ .tagline {
50
+ font-family: 'IBM Plex Mono', monospace; font-size: 11px;
51
+ text-transform: uppercase; letter-spacing: .22em; color: rgba(237,234,226,.55);
52
+ }
53
+ .reset {
54
+ font-family: 'IBM Plex Mono', monospace; font-size: 11px;
55
+ text-transform: uppercase; letter-spacing: .14em;
56
+ color: rgba(237,234,226,.7); background: none; border: 1px solid rgba(237,234,226,.25);
57
+ padding: 7px 13px; border-radius: 2px; cursor: pointer; transition: .15s;
58
+ }
59
+ .reset:hover { color: var(--paper); border-color: rgba(237,234,226,.5); }
60
+
61
+ /* provider toggle */
62
+ .provider-pick {
63
+ display: flex; align-items: center; gap: 8px;
64
+ }
65
+ .provider-pick label {
66
+ font-family: 'IBM Plex Mono', monospace; font-size: 10px;
67
+ text-transform: uppercase; letter-spacing: .16em; color: rgba(237,234,226,.5);
68
+ }
69
+ .seg-toggle { display: flex; border: 1px solid rgba(237,234,226,.25); border-radius: 2px; overflow: hidden; }
70
+ .seg-toggle button {
71
+ font-family: 'IBM Plex Mono', monospace; font-size: 11px; letter-spacing: .08em;
72
+ background: none; border: none; color: rgba(237,234,226,.6);
73
+ padding: 6px 12px; cursor: pointer; transition: .15s;
74
+ }
75
+ .seg-toggle button.active { background: var(--crit); color: #fff; }
76
+ .seg-toggle button:not(.active):hover { color: var(--paper); }
77
+
78
+ /* ---- workspace ---- */
79
+ .workspace {
80
+ display: grid; grid-template-columns: minmax(300px, 38%) 1fr;
81
+ gap: 22px; padding: 22px 32px 32px; height: calc(100vh - 73px);
82
+ }
83
+ .panel {
84
+ background: var(--paper); border-radius: 3px; box-shadow: var(--paper-shadow);
85
+ display: flex; flex-direction: column; overflow: hidden; position: relative;
86
+ }
87
+ .panel::before {
88
+ content: ""; position: absolute; inset: 0; pointer-events: none;
89
+ border-radius: 3px; border: 1px solid rgba(255,255,255,.35);
90
+ }
91
+ .panel-head {
92
+ padding: 16px 20px 13px; border-bottom: 1px solid var(--rule);
93
+ display: flex; align-items: baseline; justify-content: space-between;
94
+ }
95
+ .panel-label {
96
+ font-family: 'IBM Plex Mono', monospace; font-size: 11px;
97
+ text-transform: uppercase; letter-spacing: .2em; color: var(--ink-soft);
98
+ }
99
+ .panel-meta { font-family:'IBM Plex Mono',monospace; font-size: 11px; color: var(--ink-soft); }
100
+ .panel-body { flex: 1; overflow-y: auto; padding: 20px; }
101
+
102
+ /* ---- left: setup ---- */
103
+ .dropzone {
104
+ border: 1.5px dashed var(--rule-strong); border-radius: 3px;
105
+ padding: 28px 18px; text-align: center; cursor: pointer; transition: .15s;
106
+ background: var(--paper-inset);
107
+ }
108
+ .dropzone:hover, .dropzone.drag { border-color: var(--crit); background: #e9e2d8; }
109
+ .dropzone .big {
110
+ font-family:'Newsreader',serif; font-size: 19px; margin-bottom: 4px;
111
+ }
112
+ .dropzone .small { font-size: 13px; color: var(--ink-soft); }
113
+ .or {
114
+ text-align: center; font-family:'IBM Plex Mono',monospace; font-size: 11px;
115
+ letter-spacing: .18em; text-transform: uppercase; color: var(--ink-soft);
116
+ margin: 16px 0 12px; position: relative;
117
+ }
118
+ textarea#paste {
119
+ width: 100%; min-height: 120px; resize: vertical; padding: 12px 14px;
120
+ border: 1px solid var(--rule-strong); border-radius: 3px; background: var(--paper-inset);
121
+ font-family: 'Inter', sans-serif; font-size: 14px; color: var(--ink); line-height: 1.5;
122
+ }
123
+ textarea#paste:focus { outline: none; border-color: var(--mech); }
124
+ .btn {
125
+ font-family:'IBM Plex Mono',monospace; font-size: 12px; letter-spacing: .12em;
126
+ text-transform: uppercase; cursor: pointer; transition: .15s;
127
+ background: var(--ink); color: var(--paper); border: none; padding: 12px 18px;
128
+ border-radius: 3px;
129
+ }
130
+ .btn:hover { background: #000; }
131
+ .btn:disabled { opacity: .45; cursor: default; }
132
+ .btn-block { width: 100%; margin-top: 14px; }
133
+ .filename { font-size: 13px; color: var(--crit-ink); margin-top: 10px; font-weight: 500; }
134
+
135
+ /* ---- left: coverage map (signature) ---- */
136
+ .legend { display: flex; gap: 14px; margin-bottom: 18px; }
137
+ .legend span { display: flex; align-items: center; gap: 6px; font-size: 11px; color: var(--ink-soft);
138
+ font-family:'IBM Plex Mono',monospace; letter-spacing: .04em; }
139
+ .chip { width: 11px; height: 11px; border-radius: 2px; display: inline-block; }
140
+ .chip.s { background: var(--surface); }
141
+ .chip.m { background: var(--mech); }
142
+ .chip.c { background: var(--crit); }
143
+
144
+ .concept { padding: 11px 0; border-bottom: 1px solid var(--rule); }
145
+ .concept:last-child { border-bottom: none; }
146
+ .concept-name { font-size: 14px; margin-bottom: 7px; font-weight: 500; }
147
+ .depth { display: flex; gap: 4px; }
148
+ .seg {
149
+ flex: 1; height: 7px; border-radius: 2px; border: 1px solid var(--rule-strong);
150
+ background: transparent; transition: .35s;
151
+ }
152
+ .seg.lit.s { background: var(--surface); border-color: var(--surface); }
153
+ .seg.lit.m { background: var(--mech); border-color: var(--mech); }
154
+ .seg.lit.c { background: var(--crit); border-color: var(--crit); }
155
+ .seg.pulse { animation: pulse .6s ease; }
156
+ @keyframes pulse { 0%{transform:scaleY(1)} 40%{transform:scaleY(2.1)} 100%{transform:scaleY(1)} }
157
+
158
+ /* ---- right: dialogue ---- */
159
+ .dialogue { display: flex; flex-direction: column; height: 100%; min-height: 0; overflow: hidden; }
160
+ .transcript { flex: 1; min-height: 0; overflow-y: auto; padding: 22px 22px 8px; }
161
+ .empty {
162
+ height: 100%; display: flex; flex-direction: column; align-items: center;
163
+ justify-content: center; text-align: center; color: var(--ink-soft); padding: 30px;
164
+ }
165
+ .empty .lead { font-family:'Newsreader',serif; font-size: 22px; color: var(--ink); margin-bottom: 8px; font-style: italic; }
166
+ .empty .sub { font-size: 14px; max-width: 320px; }
167
+
168
+ .turn { margin-bottom: 20px; max-width: 88%; }
169
+ .turn.student { margin-left: auto; }
170
+ .turn .who {
171
+ font-family:'IBM Plex Mono',monospace; font-size: 10px; text-transform: uppercase;
172
+ letter-spacing: .16em; color: var(--ink-soft); margin-bottom: 5px;
173
+ display: flex; gap: 8px; align-items: center;
174
+ }
175
+ .turn.student .who { justify-content: flex-end; }
176
+ .bubble {
177
+ padding: 12px 15px; border-radius: 3px; font-size: 14.5px; line-height: 1.6;
178
+ white-space: pre-wrap;
179
+ }
180
+ .turn.student .bubble { background: var(--ink); color: var(--paper); }
181
+ .turn.expert .bubble { background: var(--paper-inset); border: 1px solid var(--rule); }
182
+ .bubble.md p { margin: 0 0 8px; }
183
+ .bubble.md p:last-child { margin-bottom: 0; }
184
+ .bubble.md ul, .bubble.md ol { margin: 6px 0 8px 20px; }
185
+ .bubble.md li { margin: 2px 0; }
186
+ .bubble.md strong { font-weight: 600; }
187
+ .bubble.md code {
188
+ font-family: 'IBM Plex Mono', monospace; font-size: 13px;
189
+ background: rgba(34,38,46,.08); padding: 1px 5px; border-radius: 3px;
190
+ }
191
+ .bubble.md pre {
192
+ background: rgba(34,38,46,.06); padding: 10px 12px; border-radius: 3px;
193
+ overflow-x: auto; margin: 6px 0;
194
+ }
195
+ .bubble.md pre code { background: none; padding: 0; }
196
+ .bubble.md h1, .bubble.md h2, .bubble.md h3 {
197
+ font-family: 'Newsreader', serif; font-size: 16px; margin: 8px 0 4px;
198
+ }
199
+ .badge {
200
+ font-family:'IBM Plex Mono',monospace; font-size: 9.5px; font-weight: 600;
201
+ letter-spacing: .08em; padding: 2px 6px; border-radius: 2px; color: #fff;
202
+ }
203
+ .badge.Surface { background: var(--surface); color: #1f3a47; }
204
+ .badge.Mechanistic { background: var(--mech); }
205
+ .badge.Critical { background: var(--crit); }
206
+ .concept-tag { color: var(--ink-soft); font-style: normal; }
207
+
208
+ .thinking { font-style: italic; color: var(--ink-soft); font-size: 14px; }
209
+ .dot-flash::after { content: "…"; animation: dots 1.2s steps(4,end) infinite; }
210
+ @keyframes dots { 0%{content:""} 25%{content:"."} 50%{content:".."} 75%{content:"…"} }
211
+
212
+ .composer {
213
+ border-top: 1px solid var(--rule); padding: 14px 18px;
214
+ display: flex; gap: 10px; align-items: flex-end; background: var(--paper);
215
+ flex-shrink: 0;
216
+ }
217
+ .composer textarea {
218
+ flex: 1; resize: none; height: 44px; max-height: 120px; padding: 11px 13px;
219
+ border: 1px solid var(--rule-strong); border-radius: 3px; background: var(--paper-inset);
220
+ font-family: 'Inter', sans-serif; font-size: 14.5px; color: var(--ink); line-height: 1.4;
221
+ }
222
+ .composer textarea:focus { outline: none; border-color: var(--mech); }
223
+
224
+ .errline { color: var(--crit-ink); font-size: 13px; margin-top: 10px; }
225
+ .hidden { display: none !important; }
226
+
227
+ ::-webkit-scrollbar { width: 9px; }
228
+ ::-webkit-scrollbar-thumb { background: var(--rule-strong); border-radius: 4px; }
229
+
230
+ @media (max-width: 860px) {
231
+ .workspace { grid-template-columns: 1fr; height: auto; }
232
+ .panel.left { min-height: 340px; }
233
+ .panel.right { min-height: 520px; }
234
+ }
235
+ </style>
236
+ </head>
237
+ <body>
238
+ <header>
239
+ <div>
240
+ <div class="wordmark">Dialectica<span class="dot">.</span></div>
241
+ </div>
242
+ <div class="tagline">you ask · the expert answers · depth is measured</div>
243
+ <div class="provider-pick">
244
+ <label>Expert</label>
245
+ <div class="seg-toggle" id="providerToggle">
246
+ <button data-provider="deepseek" class="active">DeepSeek</button>
247
+ <button data-provider="gemini">Gemini</button>
248
+ </div>
249
+ </div>
250
+ <button class="reset hidden" id="resetBtn">New material</button>
251
+ </header>
252
+
253
+ <div class="workspace">
254
+ <!-- LEFT -->
255
+ <section class="panel left">
256
+ <div class="panel-head">
257
+ <span class="panel-label" id="leftLabel">Material</span>
258
+ <span class="panel-meta" id="leftMeta"></span>
259
+ </div>
260
+ <div class="panel-body" id="leftBody">
261
+ <!-- setup state -->
262
+ <div id="setup">
263
+ <div class="dropzone" id="dropzone">
264
+ <div class="big">Drop your lecture material</div>
265
+ <div class="small">PDF · PPTX · DOCX · TXT</div>
266
+ <input type="file" id="fileInput" class="hidden" accept=".pdf,.pptx,.docx,.txt,.md">
267
+ </div>
268
+ <div class="filename hidden" id="filename"></div>
269
+ <div class="or">— or paste —</div>
270
+ <textarea id="paste" placeholder="Paste notes, a chapter, slides text…"></textarea>
271
+ <button class="btn btn-block" id="loadBtn">Load material</button>
272
+ <div class="errline hidden" id="setupErr"></div>
273
+ </div>
274
+
275
+ <!-- coverage state -->
276
+ <div id="coverage" class="hidden">
277
+ <div class="legend">
278
+ <span><i class="chip s"></i>Surface</span>
279
+ <span><i class="chip m"></i>Mechanistic</span>
280
+ <span><i class="chip c"></i>Critical</span>
281
+ </div>
282
+ <div id="conceptList"></div>
283
+ </div>
284
+ </div>
285
+ </section>
286
+
287
+ <!-- RIGHT -->
288
+ <section class="panel right">
289
+ <div class="panel-head">
290
+ <span class="panel-label">The interrogation</span>
291
+ <span class="panel-meta" id="rightMeta"></span>
292
+ </div>
293
+ <div class="dialogue">
294
+ <div class="transcript" id="transcript">
295
+ <div class="empty" id="emptyState">
296
+ <div class="lead">"Know thyself by questioning."</div>
297
+ <div class="sub">Load material on the left, then put the expert under
298
+ pressure. Every question you ask is scored for its cognitive depth.</div>
299
+ </div>
300
+ </div>
301
+ <div class="composer hidden" id="composer">
302
+ <textarea id="qInput" placeholder="Put a question to the expert…" rows="1"></textarea>
303
+ <button class="btn" id="askBtn">Ask</button>
304
+ </div>
305
+ </div>
306
+ </section>
307
+ </div>
308
+
309
+ <script>
310
+ const LEVELS = ["Surface", "Mechanistic", "Critical"];
311
+ const SEG_CLASS = { Surface: "s", Mechanistic: "m", Critical: "c" };
312
+ let selectedFile = null;
313
+ let provider = "deepseek";
314
+
315
+ const $ = (id) => document.getElementById(id);
316
+
317
+ // ---- provider toggle ----
318
+ document.querySelectorAll("#providerToggle button").forEach((btn) => {
319
+ btn.addEventListener("click", () => {
320
+ document.querySelectorAll("#providerToggle button").forEach((b) =>
321
+ b.classList.remove("active"));
322
+ btn.classList.add("active");
323
+ provider = btn.dataset.provider;
324
+ });
325
+ });
326
+
327
+ // ---- material loading ----
328
+ $("dropzone").addEventListener("click", () => $("fileInput").click());
329
+ $("fileInput").addEventListener("change", (e) => {
330
+ selectedFile = e.target.files[0] || null;
331
+ if (selectedFile) {
332
+ $("filename").textContent = "Selected: " + selectedFile.name;
333
+ $("filename").classList.remove("hidden");
334
+ }
335
+ });
336
+ ["dragover", "dragleave", "drop"].forEach(evt =>
337
+ $("dropzone").addEventListener(evt, (e) => {
338
+ e.preventDefault();
339
+ $("dropzone").classList.toggle("drag", evt === "dragover");
340
+ if (evt === "drop" && e.dataTransfer.files[0]) {
341
+ selectedFile = e.dataTransfer.files[0];
342
+ $("filename").textContent = "Selected: " + selectedFile.name;
343
+ $("filename").classList.remove("hidden");
344
+ }
345
+ })
346
+ );
347
+
348
+ $("loadBtn").addEventListener("click", loadMaterial);
349
+
350
+ async function loadMaterial() {
351
+ const paste = $("paste").value.trim();
352
+ if (!selectedFile && !paste) {
353
+ return showSetupErr("Choose a file or paste some text first.");
354
+ }
355
+ setLoading(true, "Reading material…");
356
+
357
+ const form = new FormData();
358
+ if (selectedFile) form.append("file", selectedFile);
359
+ else form.append("text", paste);
360
+ form.append("provider", provider);
361
+
362
+ try {
363
+ const res = await fetch("/api/upload", { method: "POST", body: form });
364
+ const data = await res.json();
365
+ if (!res.ok) { setLoading(false); return showSetupErr(data.error || "Could not read that."); }
366
+ enterInterrogation(data);
367
+ } catch (err) {
368
+ setLoading(false);
369
+ showSetupErr("Could not reach the server. Is it running?");
370
+ }
371
+ }
372
+
373
+ function setLoading(on, label) {
374
+ $("loadBtn").disabled = on;
375
+ $("loadBtn").textContent = on ? (label || "Working…") : "Load material";
376
+ }
377
+ function showSetupErr(msg) {
378
+ $("setupErr").textContent = msg;
379
+ $("setupErr").classList.remove("hidden");
380
+ }
381
+
382
+ // ---- enter interrogation ----
383
+ function enterInterrogation(data) {
384
+ setLoading(false);
385
+ $("setup").classList.add("hidden");
386
+ $("coverage").classList.remove("hidden");
387
+ $("leftLabel").textContent = "Coverage map";
388
+ $("leftMeta").textContent = data.char_count.toLocaleString() + " chars";
389
+ $("resetBtn").classList.remove("hidden");
390
+ $("emptyState").classList.add("hidden");
391
+ $("composer").classList.remove("hidden");
392
+ renderConcepts(data.concepts, data.coverage);
393
+ $("rightMeta").textContent = data.concepts.length + " concepts in play";
394
+ $("qInput").focus();
395
+ }
396
+
397
+ function renderConcepts(concepts, coverage) {
398
+ const list = $("conceptList");
399
+ list.innerHTML = "";
400
+ concepts.forEach((c) => {
401
+ const row = document.createElement("div");
402
+ row.className = "concept";
403
+ const cov = coverage[c] || {};
404
+ const segs = LEVELS.map((lv) => {
405
+ const lit = cov[lv] > 0 ? "lit" : "";
406
+ return `<span class="seg ${SEG_CLASS[lv]} ${lit}" data-concept="${encodeURIComponent(c)}" data-level="${lv}"></span>`;
407
+ }).join("");
408
+ row.innerHTML = `<div class="concept-name">${c}</div><div class="depth">${segs}</div>`;
409
+ list.appendChild(row);
410
+ });
411
+ }
412
+
413
+ function updateCoverage(coverage) {
414
+ document.querySelectorAll(".seg").forEach((seg) => {
415
+ const c = decodeURIComponent(seg.dataset.concept);
416
+ const lv = seg.dataset.level;
417
+ const reached = coverage[c] && coverage[c][lv] > 0;
418
+ if (reached && !seg.classList.contains("lit")) {
419
+ seg.classList.add("lit", "pulse");
420
+ setTimeout(() => seg.classList.remove("pulse"), 600);
421
+ }
422
+ });
423
+ }
424
+
425
+ // ---- asking ----
426
+ $("askBtn").addEventListener("click", ask);
427
+ $("qInput").addEventListener("keydown", (e) => {
428
+ if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); ask(); }
429
+ });
430
+
431
+ async function ask() {
432
+ const q = $("qInput").value.trim();
433
+ if (!q) return;
434
+ $("qInput").value = "";
435
+ addStudentTurn(q);
436
+ const thinkingEl = addThinking();
437
+ $("askBtn").disabled = true;
438
+
439
+ try {
440
+ const res = await fetch("/api/ask", {
441
+ method: "POST",
442
+ headers: { "Content-Type": "application/json" },
443
+ body: JSON.stringify({ question: q, provider: provider }),
444
+ });
445
+ const data = await res.json();
446
+ thinkingEl.remove();
447
+ if (!res.ok) { addExpertTurn(data.error || "Something went wrong."); }
448
+ else {
449
+ tagLastStudent(data.level, data.confidence, data.concept);
450
+ addExpertTurn(data.answer);
451
+ updateCoverage(data.coverage);
452
+ }
453
+ } catch (err) {
454
+ thinkingEl.remove();
455
+ addExpertTurn("Could not reach the server.");
456
+ }
457
+ $("askBtn").disabled = false;
458
+ $("qInput").focus();
459
+ }
460
+
461
+ function scrollDown() { const t = $("transcript"); t.scrollTop = t.scrollHeight; }
462
+
463
+ let lastStudentEl = null;
464
+ function addStudentTurn(text) {
465
+ const el = document.createElement("div");
466
+ el.className = "turn student";
467
+ el.innerHTML = `<div class="who"><span class="pending mono">scoring…</span> You</div>
468
+ <div class="bubble"></div>`;
469
+ el.querySelector(".bubble").textContent = text;
470
+ $("transcript").appendChild(el);
471
+ lastStudentEl = el;
472
+ scrollDown();
473
+ }
474
+ function tagLastStudent(level, conf, concept) {
475
+ if (!lastStudentEl) return;
476
+ const pct = Math.round(conf * 100);
477
+ const conceptBit = concept ? ` · <span class="concept-tag">${concept}</span>` : "";
478
+ lastStudentEl.querySelector(".who").innerHTML =
479
+ `<span class="badge ${level}">${level.toUpperCase()} ${pct}%</span>${conceptBit} You`;
480
+ }
481
+ function addThinking() {
482
+ const el = document.createElement("div");
483
+ el.className = "turn expert";
484
+ el.innerHTML = `<div class="who">The expert</div>
485
+ <div class="bubble thinking"><span class="dot-flash">considering</span></div>`;
486
+ $("transcript").appendChild(el);
487
+ scrollDown();
488
+ return el;
489
+ }
490
+ function addExpertTurn(text) {
491
+ const el = document.createElement("div");
492
+ el.className = "turn expert";
493
+ el.innerHTML = `<div class="who">The expert</div><div class="bubble md"></div>`;
494
+ const bubble = el.querySelector(".bubble");
495
+ if (window.marked) {
496
+ bubble.innerHTML = marked.parse(text);
497
+ } else {
498
+ bubble.textContent = text;
499
+ }
500
+ $("transcript").appendChild(el);
501
+ scrollDown();
502
+ }
503
+
504
+ // ---- reset ----
505
+ $("resetBtn").addEventListener("click", () => location.reload());
506
+
507
+ // auto-grow question box
508
+ $("qInput").addEventListener("input", function () {
509
+ this.style.height = "44px";
510
+ this.style.height = Math.min(this.scrollHeight, 120) + "px";
511
+ });
512
+ </script>
513
+ </body>
514
+ </html>
main.py CHANGED
@@ -1,13 +1,177 @@
1
- """Application entry point.
2
 
3
- Phase 8 app code will be added here.
 
 
 
 
 
 
 
4
  """
5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
- def main():
8
- """Placeholder for app startup."""
9
- raise NotImplementedError("Phase 8: application layer not yet implemented.")
 
 
 
 
 
10
 
11
 
12
- if __name__ == "__main__":
13
- main()
 
 
 
1
+ """FastAPI backend for Dialectica.
2
 
3
+ Endpoints:
4
+ GET / serve the frontend
5
+ POST /api/upload parse material, extract concepts, init session
6
+ POST /api/ask classify question, get expert answer, update coverage
7
+ GET /api/coverage current coverage map
8
+
9
+ Run locally:
10
+ PYTORCH_ENABLE_MPS_FALLBACK=1 uvicorn main:app
11
  """
12
 
13
+ import os
14
+
15
+ from dotenv import load_dotenv
16
+ from fastapi import FastAPI, File, Form, UploadFile
17
+ from fastapi.responses import FileResponse, JSONResponse
18
+ from pydantic import BaseModel
19
+
20
+ import config
21
+ from scripts import parsing
22
+ from scripts.expert import Expert
23
+ from scripts.inference import ORDERED_LABELS, CognitiveClassifier, ConceptMatcher
24
+
25
+ load_dotenv()
26
+
27
+ app = FastAPI(title="Dialectica")
28
+
29
+ VALID_PROVIDERS = ("deepseek", "gemini")
30
+
31
+ # In-memory session state for the demo.
32
+ SESSION = {
33
+ "material": "",
34
+ "concepts": [],
35
+ "coverage": {}, # concept -> {Surface: n, Mechanistic: n, Critical: n}
36
+ "history": [],
37
+ }
38
+
39
+ # Shared classifier/matcher; one cached expert per provider.
40
+ COMPONENTS = {"classifier": None, "matcher": None, "experts": {}}
41
+
42
+
43
+ def get_classifier_and_matcher():
44
+ """Initialize classifier and matcher on first use."""
45
+ product_config = config.ProductConfig()
46
+ if COMPONENTS["classifier"] is None:
47
+ COMPONENTS["classifier"] = CognitiveClassifier(product_config)
48
+ if COMPONENTS["matcher"] is None:
49
+ COMPONENTS["matcher"] = ConceptMatcher(product_config)
50
+ return COMPONENTS["classifier"], COMPONENTS["matcher"]
51
+
52
+
53
+ def get_expert(provider):
54
+ """Return a cached expert for the given provider, or an error string."""
55
+ if provider not in VALID_PROVIDERS:
56
+ provider = "deepseek"
57
+ if provider not in COMPONENTS["experts"]:
58
+ product_config = config.ProductConfig()
59
+ product_config.provider = provider
60
+ try:
61
+ COMPONENTS["experts"][provider] = Expert(product_config)
62
+ except SystemExit as error:
63
+ return None, str(error)
64
+ except Exception as error: # missing SDK, bad key shape, etc.
65
+ return None, f"Could not start the {provider} expert: {error}"
66
+ return COMPONENTS["experts"][provider], None
67
+
68
+
69
+ def _blank_coverage(concepts):
70
+ """Initialise an empty coverage record for each concept."""
71
+ return {c: {level: 0 for level in ORDERED_LABELS} for c in concepts}
72
+
73
+
74
+ class AskRequest(BaseModel):
75
+ """Body for the /api/ask endpoint."""
76
+
77
+ question: str
78
+ provider: str = "deepseek"
79
+
80
+
81
+ @app.get("/")
82
+ def index():
83
+ """Serve the single-page frontend."""
84
+ return FileResponse(os.path.join("frontend", "index.html"))
85
+
86
+
87
+ @app.post("/api/upload")
88
+ async def upload(
89
+ file: UploadFile = File(None),
90
+ text: str = Form(None),
91
+ provider: str = Form("deepseek"),
92
+ ):
93
+ """Parse uploaded material or pasted text and extract concepts."""
94
+ if file is not None:
95
+ data = await file.read()
96
+ try:
97
+ raw = parsing.parse_material(file.filename, data)
98
+ except ValueError as error:
99
+ return JSONResponse(status_code=400, content={"error": str(error)})
100
+ elif text:
101
+ raw = text
102
+ else:
103
+ return JSONResponse(
104
+ status_code=400,
105
+ content={"error": "Upload a file or paste some text to begin."},
106
+ )
107
+
108
+ material = parsing.clean_text(raw)
109
+ if len(material) < 40:
110
+ return JSONResponse(
111
+ status_code=400,
112
+ content={"error": "That material is too short to work with."},
113
+ )
114
+
115
+ _, matcher = get_classifier_and_matcher()
116
+ expert, error = get_expert(provider)
117
+ if expert is None:
118
+ return JSONResponse(status_code=400, content={"error": error})
119
+
120
+ concepts = expert.extract_concepts(material)
121
+ matcher.set_concepts(concepts)
122
+
123
+ SESSION["material"] = material
124
+ SESSION["concepts"] = concepts
125
+ SESSION["coverage"] = _blank_coverage(concepts)
126
+ SESSION["history"] = []
127
+
128
+ return {"concepts": concepts, "coverage": SESSION["coverage"],
129
+ "char_count": len(material), "provider": provider}
130
+
131
+
132
+ @app.post("/api/ask")
133
+ def ask(request: AskRequest):
134
+ """Classify the question, answer as the expert, and update coverage."""
135
+ question = request.question.strip()
136
+ if not question:
137
+ return JSONResponse(status_code=400,
138
+ content={"error": "Ask the expert something."})
139
+ if not SESSION["material"]:
140
+ return JSONResponse(
141
+ status_code=400,
142
+ content={"error": "Load some material before you start asking."},
143
+ )
144
+
145
+ classifier, matcher = get_classifier_and_matcher()
146
+ expert, error = get_expert(request.provider)
147
+ if expert is None:
148
+ return JSONResponse(status_code=400, content={"error": error})
149
+
150
+ classification = classifier.classify(question)
151
+ level = classification["level"]
152
+ concept = matcher.match(question)
153
+
154
+ answer_text = expert.answer(
155
+ question, SESSION["material"], SESSION["history"]
156
+ )
157
+
158
+ SESSION["history"].append({"role": "student", "text": question})
159
+ SESSION["history"].append({"role": "expert", "text": answer_text})
160
+
161
+ if concept and concept in SESSION["coverage"]:
162
+ SESSION["coverage"][concept][level] += 1
163
 
164
+ return {
165
+ "answer": answer_text,
166
+ "level": level,
167
+ "confidence": classification["confidence"],
168
+ "concept": concept,
169
+ "coverage": SESSION["coverage"],
170
+ "provider": request.provider,
171
+ }
172
 
173
 
174
+ @app.get("/api/coverage")
175
+ def coverage():
176
+ """Return the current coverage map and concept list."""
177
+ return {"concepts": SESSION["concepts"], "coverage": SESSION["coverage"]}
requirements-app.txt ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Runtime dependencies for the deployed Dialectica app only.
2
+ # Training-only packages (scikit-learn, datasets, matplotlib, seaborn, pandas)
3
+ # are intentionally omitted to keep the image small and the build fast.
4
+
5
+ fastapi>=0.110.0
6
+ uvicorn[standard]>=0.29.0
7
+ python-multipart>=0.0.9
8
+ python-dotenv>=1.0.0
9
+
10
+ # classifier (live inference)
11
+ transformers>=4.44.0
12
+ # torch is installed separately (CPU build) in the Dockerfile
13
+
14
+ # concept matching
15
+ sentence-transformers>=3.0.0
16
+
17
+ # expert dialogue providers
18
+ openai>=1.40.0
19
+ google-genai>=1.0.0
20
+
21
+ # material parsing
22
+ pymupdf>=1.24.0
23
+ python-pptx>=0.6.23
24
+ python-docx>=1.1.0
requirements.txt CHANGED
@@ -18,8 +18,10 @@ datasets>=2.20.0
18
  matplotlib>=3.8.0
19
  seaborn>=0.13.0
20
 
21
- # Product backend (Phase 8, added later)
22
- # fastapi>=0.110.0
23
- # uvicorn>=0.29.0
24
- # pymupdf>=1.24.0
25
- # python-pptx>=0.6.23
 
 
 
18
  matplotlib>=3.8.0
19
  seaborn>=0.13.0
20
 
21
+ # Product backend (Phase 8)
22
+ fastapi>=0.110.0
23
+ uvicorn[standard]>=0.29.0
24
+ python-multipart>=0.0.9
25
+ pymupdf>=1.24.0
26
+ python-pptx>=0.6.23
27
+ python-docx>=1.1.0
scripts/expert.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Gemini/DeepSeek-backed expert for concept extraction and student dialogue."""
2
+
3
+ import json
4
+ import os
5
+
6
+
7
+ EXPERT_SYSTEM_PROMPT = """You are a knowledgeable subject-matter expert on the \
8
+ study material provided below. A student is going to question, probe, and \
9
+ challenge you in order to deepen their own understanding. You are not a tutor \
10
+ who quizzes them; they lead the inquiry.
11
+
12
+ Rules:
13
+ - Answer directly and substantively, grounded in the material. Do not pad.
14
+ - Match the student's depth. A plain factual question gets a plain answer; a \
15
+ question that probes mechanism or challenges an assumption gets a deeper, \
16
+ reasoned response.
17
+ - When the student challenges you or surfaces a genuine edge case, limitation, \
18
+ or counterexample, acknowledge it honestly and engage with it. Do not be \
19
+ defensive, and do not pretend the material is more complete than it is.
20
+ - If they ask something the material does not cover, say so plainly and reason \
21
+ from first principles, flagging that you are going beyond the source.
22
+ - Never quiz the student back or end with "does that make sense?". They are the \
23
+ one asking the questions.
24
+ - You may use light markdown (bold, lists) when it aids clarity.
25
+
26
+ Study material:
27
+ ---
28
+ {material}
29
+ ---
30
+ """
31
+
32
+ CONCEPT_PROMPT = """From the study material below, extract the {n} most \
33
+ important distinct concepts or topics a student would want to understand. \
34
+ Return a JSON object with a single key "concepts" whose value is an array of \
35
+ short concept names (2-5 words each), ordered from most to least central.
36
+
37
+ Material:
38
+ ---
39
+ {material}
40
+ ---
41
+ Return only the JSON object."""
42
+
43
+
44
+ class Expert:
45
+ """Concept extraction and expert dialogue, via DeepSeek or Gemini."""
46
+
47
+ def __init__(self, product_config):
48
+ """Initialise the client for the configured provider."""
49
+ self.cfg = product_config
50
+ self.provider = getattr(product_config, "provider", "deepseek")
51
+ if self.provider == "deepseek":
52
+ self._init_deepseek()
53
+ elif self.provider == "gemini":
54
+ self._init_gemini()
55
+ else:
56
+ raise ValueError(f"Unknown provider: {self.provider}")
57
+
58
+ def _init_deepseek(self):
59
+ """Set up the DeepSeek (OpenAI-compatible) client."""
60
+ from openai import OpenAI
61
+
62
+ api_key = os.environ.get("DEEPSEEK_API_KEY")
63
+ if not api_key:
64
+ raise SystemExit(
65
+ "DEEPSEEK_API_KEY is not set. Add it to .env, or set "
66
+ "ProductConfig.provider = 'gemini' to use Gemini instead."
67
+ )
68
+ self.client = OpenAI(api_key=api_key, base_url="https://api.deepseek.com")
69
+ self.model = self.cfg.deepseek_model
70
+
71
+ def _init_gemini(self):
72
+ """Set up the Gemini client."""
73
+ from google import genai
74
+
75
+ api_key = os.environ.get("GEMINI_API_KEY")
76
+ if not api_key:
77
+ raise SystemExit("GEMINI_API_KEY is not set. Add it to .env.")
78
+ self.client = genai.Client(api_key=api_key)
79
+ self.model = self.cfg.gemini_model
80
+
81
+ # ---- concept extraction ----
82
+
83
+ def extract_concepts(self, material_text):
84
+ """Ask the model for the key concepts in the material."""
85
+ material = material_text[: self.cfg.max_context_chars]
86
+ prompt = CONCEPT_PROMPT.format(n=self.cfg.num_concepts, material=material)
87
+ if self.provider == "deepseek":
88
+ raw = self._deepseek_json(prompt)
89
+ else:
90
+ raw = self._gemini_json(prompt)
91
+ try:
92
+ parsed = json.loads(raw)
93
+ concepts = parsed.get("concepts", []) if isinstance(parsed, dict) else []
94
+ except (json.JSONDecodeError, TypeError):
95
+ concepts = []
96
+ return [c.strip() for c in concepts if isinstance(c, str) and c.strip()]
97
+
98
+ def _deepseek_json(self, prompt):
99
+ """One DeepSeek call returning a JSON object string."""
100
+ response = self.client.chat.completions.create(
101
+ model=self.model,
102
+ messages=[{"role": "user", "content": prompt}],
103
+ response_format={"type": "json_object"},
104
+ temperature=0.3,
105
+ )
106
+ return response.choices[0].message.content
107
+
108
+ def _gemini_json(self, prompt):
109
+ """One Gemini call returning a JSON object string."""
110
+ from google.genai import types
111
+
112
+ response = self.client.models.generate_content(
113
+ model=self.model,
114
+ contents=prompt,
115
+ config=types.GenerateContentConfig(
116
+ response_mime_type="application/json",
117
+ temperature=0.3,
118
+ ),
119
+ )
120
+ return response.text
121
+
122
+ # ---- expert dialogue ----
123
+
124
+ def answer(self, question, material_text, history):
125
+ """Answer a student question given material context and chat history."""
126
+ material = material_text[: self.cfg.max_context_chars]
127
+ system = EXPERT_SYSTEM_PROMPT.format(material=material)
128
+ if self.provider == "deepseek":
129
+ return self._deepseek_answer(system, question, history)
130
+ return self._gemini_answer(system, question, history)
131
+
132
+ def _deepseek_answer(self, system, question, history):
133
+ """Send question to DeepSeek and return the answer."""
134
+ messages = [{"role": "system", "content": system}]
135
+ for turn in history[-8:]:
136
+ role = "user" if turn["role"] == "student" else "assistant"
137
+ messages.append({"role": role, "content": turn["text"]})
138
+ messages.append({"role": "user", "content": question})
139
+ response = self.client.chat.completions.create(
140
+ model=self.model,
141
+ messages=messages,
142
+ temperature=0.7,
143
+ )
144
+ return response.choices[0].message.content.strip()
145
+
146
+ def _gemini_answer(self, system, question, history):
147
+ """Send question to Gemini and return the answer."""
148
+ from google.genai import types
149
+
150
+ transcript = []
151
+ for turn in history[-8:]:
152
+ speaker = "Student" if turn["role"] == "student" else "Expert"
153
+ transcript.append(f"{speaker}: {turn['text']}")
154
+ transcript.append(f"Student: {question}")
155
+ conversation = "\n\n".join(transcript)
156
+ response = self.client.models.generate_content(
157
+ model=self.model,
158
+ contents=conversation,
159
+ config=types.GenerateContentConfig(
160
+ system_instruction=system,
161
+ temperature=0.7,
162
+ ),
163
+ )
164
+ return response.text.strip()
scripts/inference.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Inference for the Dialectica app.
2
+
3
+ Two jobs:
4
+ 1. Classify the cognitive level of a student question in real time, using the
5
+ DistilBERT model fine-tuned in Phase 4b. This is the trained model running
6
+ live inference in the deployed product, satisfying the rubric requirement.
7
+ 2. Match a question to the nearest extracted concept via sentence-embedding
8
+ similarity, so the coverage map knows which concept the question advanced.
9
+
10
+ Both models load once at startup.
11
+
12
+ Author: Keming Zhang
13
+ Note: Drafted with assistance from Claude (Anthropic). Uses the fine-tuned
14
+ DistilBERT classifier and sentence-transformers for concept matching.
15
+ """
16
+
17
+ ORDERED_LABELS = ["Surface", "Mechanistic", "Critical"]
18
+
19
+
20
+ class CognitiveClassifier:
21
+ """Wraps the fine-tuned DistilBERT for live question classification."""
22
+
23
+ def __init__(self, product_config):
24
+ """Load the classifier and tokenizer from disk."""
25
+ import torch
26
+ from transformers import (
27
+ AutoModelForSequenceClassification,
28
+ AutoTokenizer,
29
+ )
30
+
31
+ self.cfg = product_config
32
+ self.torch = torch
33
+ self.tokenizer = AutoTokenizer.from_pretrained(self.cfg.classifier_dir)
34
+ self.model = AutoModelForSequenceClassification.from_pretrained(
35
+ self.cfg.classifier_dir
36
+ )
37
+ self.model.eval()
38
+ # use the model's own id2label if present, else fall back to ordered
39
+ self.id2label = self.model.config.id2label or {
40
+ i: label for i, label in enumerate(ORDERED_LABELS)
41
+ }
42
+
43
+ def classify(self, question):
44
+ """Return the predicted level and a confidence score for one question."""
45
+ inputs = self.tokenizer(
46
+ question,
47
+ truncation=True,
48
+ max_length=self.cfg.max_question_length,
49
+ return_tensors="pt",
50
+ )
51
+ with self.torch.no_grad():
52
+ logits = self.model(**inputs).logits
53
+ probs = self.torch.softmax(logits, dim=1)[0]
54
+ predicted_id = int(self.torch.argmax(probs))
55
+ return {
56
+ "level": self.id2label[predicted_id],
57
+ "confidence": float(probs[predicted_id]),
58
+ }
59
+
60
+
61
+ class ConceptMatcher:
62
+ """Matches a question to the nearest concept by embedding similarity."""
63
+
64
+ def __init__(self, product_config):
65
+ """Load the sentence embedding model."""
66
+ from sentence_transformers import SentenceTransformer
67
+
68
+ self.cfg = product_config
69
+ self.model = SentenceTransformer(self.cfg.embed_model)
70
+ self.concepts = []
71
+ self.concept_embeddings = None
72
+
73
+ def set_concepts(self, concepts):
74
+ """Embed and store the current material's concept list."""
75
+ self.concepts = concepts
76
+ if concepts:
77
+ self.concept_embeddings = self.model.encode(
78
+ concepts, convert_to_tensor=True
79
+ )
80
+ else:
81
+ self.concept_embeddings = None
82
+
83
+ def match(self, question):
84
+ """Return the best-matching concept, or None if below threshold."""
85
+ from sentence_transformers import util
86
+
87
+ if not self.concepts or self.concept_embeddings is None:
88
+ return None
89
+ query = self.model.encode(question, convert_to_tensor=True)
90
+ scores = util.cos_sim(query, self.concept_embeddings)[0]
91
+ best_index = int(scores.argmax())
92
+ best_score = float(scores[best_index])
93
+ if best_score < self.cfg.concept_match_threshold:
94
+ return None
95
+ return self.concepts[best_index]
scripts/parsing.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Parse uploaded course material into plain text.
2
+
3
+ Supports PDF, PPTX, DOCX, and plain text files.
4
+ """
5
+
6
+ import io
7
+
8
+
9
+ def parse_pdf(data):
10
+ """Extract text from PDF bytes using PyMuPDF."""
11
+ import fitz # PyMuPDF
12
+
13
+ text_parts = []
14
+ with fitz.open(stream=data, filetype="pdf") as document:
15
+ for page in document:
16
+ text_parts.append(page.get_text())
17
+ return "\n".join(text_parts)
18
+
19
+
20
+ def parse_pptx(data):
21
+ """Extract text from PPTX bytes, slide by slide."""
22
+ from pptx import Presentation
23
+
24
+ presentation = Presentation(io.BytesIO(data))
25
+ text_parts = []
26
+ for index, slide in enumerate(presentation.slides, start=1):
27
+ text_parts.append(f"[Slide {index}]")
28
+ for shape in slide.shapes:
29
+ if shape.has_text_frame:
30
+ for paragraph in shape.text_frame.paragraphs:
31
+ line = "".join(run.text for run in paragraph.runs)
32
+ if line.strip():
33
+ text_parts.append(line)
34
+ return "\n".join(text_parts)
35
+
36
+
37
+ def parse_docx(data):
38
+ """Extract text from DOCX bytes."""
39
+ from docx import Document
40
+
41
+ document = Document(io.BytesIO(data))
42
+ return "\n".join(p.text for p in document.paragraphs if p.text.strip())
43
+
44
+
45
+ def parse_material(filename, data):
46
+ """Pick the right parser based on file extension and return plain text."""
47
+ lower = filename.lower()
48
+ if lower.endswith(".pdf"):
49
+ return parse_pdf(data)
50
+ if lower.endswith(".pptx"):
51
+ return parse_pptx(data)
52
+ if lower.endswith(".docx"):
53
+ return parse_docx(data)
54
+ if lower.endswith(".txt") or lower.endswith(".md"):
55
+ return data.decode("utf-8", errors="ignore")
56
+ raise ValueError(f"Unsupported file type: {filename}")
57
+
58
+
59
+ def clean_text(text):
60
+ """Strip extra whitespace and blank lines."""
61
+ lines = [line.strip() for line in text.splitlines()]
62
+ non_empty = [line for line in lines if line]
63
+ return "\n".join(non_empty)