Awab-Elsadig Claude Sonnet 4.6 commited on
Commit
b148513
Β·
1 Parent(s): 2821b5d

Add PDF picker UI with server-side persistence

Browse files

Teammates can now upload their own PDF once via a clean file picker.
The file is saved server-side so it persists across page refreshes.
Branch renamed from master to main.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

Files changed (1) hide show
  1. main.py +81 -53
main.py CHANGED
@@ -25,6 +25,18 @@ app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], all
25
  SAVED_PDF = OUTPUT_DIR / "saved_textbook.pdf"
26
  SAVED_PDF_NAME = OUTPUT_DIR / "saved_textbook_name.txt"
27
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  GEMINI_PROMPT = """\
29
  You are extracting end-of-chapter problems from a Control Systems textbook (Modern Control Systems, 12th edition).
30
 
@@ -84,8 +96,15 @@ _HTML = """<!DOCTYPE html>
84
  /* Spinner (inline) */
85
  .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; }
86
  @keyframes spin { to { transform: rotate(360deg); } }
87
- /* PDF saved indicator */
88
- .pdf-saved-pill { display: none; align-items: center; gap: 8px; background: #f0fdf4; border: 1px solid #bbf7d0; border-radius: 6px; padding: 5px 10px; font-size: 0.78rem; color: #166534; }
 
 
 
 
 
 
 
89
  /* Workflow grid */
90
  .workflow-grid { display: flex; gap: 12px; flex-wrap: wrap; margin-bottom: 12px; }
91
  .workflow-grid .card { flex: 1; min-width: 260px; margin-bottom: 0; }
@@ -160,17 +179,23 @@ _HTML = """<!DOCTYPE html>
160
  <!-- ── Config bar ── -->
161
  <div class="card" style="margin-bottom:16px;">
162
  <div class="config-bar">
163
- <!-- PDF -->
164
- <div id="pdf-saved-row" class="pdf-saved-pill">
165
- <span>&#10003;</span>
166
- <span id="pdf-saved-name"></span>
167
- <button class="btn btn-secondary btn-xs" onclick="changePdf()">Change</button>
 
 
 
 
 
168
  </div>
169
- <div id="pdf-picker-row" style="display:flex;align-items:center;gap:8px;">
170
- <button class="btn btn-secondary btn-sm" onclick="document.getElementById('tb-file').click()">Choose PDF</button>
171
- <span id="tb-name" style="font-size:0.78rem;color:#64748b;">No file chosen</span>
 
 
172
  </div>
173
- <input id="tb-file" type="file" accept=".pdf" style="display:none" onchange="onFileChosen(this)">
174
  <!-- Divider -->
175
  <span class="config-sep">|</span>
176
  <!-- Pages -->
@@ -250,11 +275,43 @@ _HTML = """<!DOCTYPE html>
250
 
251
  <script>
252
  var PROMPT = __PROMPT__;
253
- var katexReady = false;
254
- var problems = [];
255
- var rawText = '';
256
- var activeFilter = 'all';
257
  var activeCardIdx = null;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
258
 
259
  var KATEX_OPTS = {
260
  delimiters: [
@@ -279,43 +336,15 @@ _HTML = """<!DOCTYPE html>
279
  }
280
  }
281
 
282
- // ── PDF persistence ───────────────────────────────────────────────────────
283
-
284
- (async function checkSavedPdf() {
285
- try {
286
- var info = await (await fetch('/api/pdf-info')).json();
287
- if (info.saved) {
288
- document.getElementById('pdf-saved-name').textContent = info.name;
289
- document.getElementById('pdf-saved-row').style.display = 'flex';
290
- document.getElementById('pdf-picker-row').style.display = 'none';
291
- }
292
- } catch(e) {}
293
- })();
294
-
295
- function onFileChosen(input) {
296
- document.getElementById('tb-name').textContent = input.files[0] ? input.files[0].name : 'No file chosen';
297
- }
298
-
299
- function changePdf() {
300
- document.getElementById('pdf-saved-row').style.display = 'none';
301
- document.getElementById('pdf-picker-row').style.display = 'flex';
302
- document.getElementById('tb-file').value = '';
303
- document.getElementById('tb-name').textContent = 'No file chosen';
304
- document.getElementById('tb-file').click();
305
- }
306
-
307
  // ── Extract ───────────────────────────────────────────────────────────────
308
 
309
  async function startExtract() {
310
  hideError();
311
- var tbFile = document.getElementById('tb-file').files[0] || null;
312
- var hasSaved = document.getElementById('pdf-saved-row').style.display !== 'none';
313
  var tbStartRaw = document.getElementById('tb-start').value.trim();
314
  var tbEndRaw = document.getElementById('tb-end').value.trim();
315
  var tbStart = parseInt(tbStartRaw, 10);
316
  var tbEnd = parseInt(tbEndRaw, 10);
317
  var isReextract = rawText.trim().length > 0;
318
- if (!tbFile && !hasSaved) { showError('Please choose a PDF file.'); return; }
319
  if (!tbStartRaw || !tbEndRaw || Number.isNaN(tbStart) || Number.isNaN(tbEnd)) {
320
  showError('Please enter both start and end page numbers.');
321
  return;
@@ -330,19 +359,14 @@ _HTML = """<!DOCTYPE html>
330
 
331
  try {
332
  var form = new FormData();
333
- if (tbFile) form.append('textbook', tbFile);
334
  form.append('tb_start', tbStart);
335
  form.append('tb_end', tbEnd);
 
336
  var res = await fetch('/api/extract', { method: 'POST', body: form });
337
  if (!res.ok) { var e = await res.json(); throw new Error(e.detail || 'Extraction failed'); }
338
  var data = await res.json();
339
  rawText = data.text || '';
340
-
341
- if (tbFile) {
342
- document.getElementById('pdf-saved-name').textContent = tbFile.name;
343
- document.getElementById('pdf-saved-row').style.display = 'flex';
344
- document.getElementById('pdf-picker-row').style.display = 'none';
345
- }
346
 
347
  var imgs = data.images || [];
348
  document.getElementById('extract-status').textContent =
@@ -871,6 +895,8 @@ def pdf_info():
871
  if SAVED_PDF.exists():
872
  name = SAVED_PDF_NAME.read_text(encoding="utf-8") if SAVED_PDF_NAME.exists() else "textbook.pdf"
873
  return {"saved": True, "name": name}
 
 
874
  return {"saved": False, "name": None}
875
 
876
 
@@ -884,13 +910,15 @@ async def extract(
884
  with open(SAVED_PDF, "wb") as f:
885
  shutil.copyfileobj(textbook.file, f)
886
  SAVED_PDF_NAME.write_text(textbook.filename, encoding="utf-8")
887
- elif not SAVED_PDF.exists():
888
- raise HTTPException(status_code=400, detail="No PDF uploaded. Please choose a PDF file first.")
 
 
889
 
890
  for old in OUTPUT_DIR.glob("q_page*"):
891
  old.unlink(missing_ok=True)
892
  text, images = await asyncio.to_thread(
893
- extract_page_range, str(SAVED_PDF), tb_start, tb_end, OUTPUT_DIR, "q"
894
  )
895
  with open(OUTPUT_DIR / "raw_text.txt", "w", encoding="utf-8") as f:
896
  f.write(text)
 
25
  SAVED_PDF = OUTPUT_DIR / "saved_textbook.pdf"
26
  SAVED_PDF_NAME = OUTPUT_DIR / "saved_textbook_name.txt"
27
 
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."""
34
+ if SAVED_PDF.exists():
35
+ return SAVED_PDF
36
+ if BUNDLED_PDF.exists():
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
 
 
96
  /* Spinner (inline) */
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; }
 
179
  <!-- ── Config bar ── -->
180
  <div class="card" style="margin-bottom:16px;">
181
  <div class="config-bar">
182
+ <!-- PDF picker -->
183
+ <input type="file" id="pdf-file-input" accept=".pdf" style="display:none;" onchange="handlePdfSelect(this)">
184
+ <label id="pdf-picker-btn" class="pdf-picker-btn" for="pdf-file-input">
185
+ <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>
186
+ Choose PDF
187
+ </label>
188
+ <div id="pdf-ready-pill" class="pdf-ready-pill">
189
+ <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>
190
+ <span id="pdf-ready-name" class="pdf-ready-name"></span>
191
+ <span class="pdf-change-link" onclick="document.getElementById('pdf-file-input').click()">Change</span>
192
  </div>
193
+ <div id="pdf-pending-pill" class="pdf-pending-pill">
194
+ <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>
195
+ <span id="pdf-pending-name" class="pdf-pending-name"></span>
196
+ <span style="color:#a16207;font-size:0.68rem;flex-shrink:0;">uploads on Extract</span>
197
+ <span class="pdf-change-link" onclick="document.getElementById('pdf-file-input').click()">Change</span>
198
  </div>
 
199
  <!-- Divider -->
200
  <span class="config-sep">|</span>
201
  <!-- Pages -->
 
275
 
276
  <script>
277
  var PROMPT = __PROMPT__;
278
+ var katexReady = false;
279
+ var problems = [];
280
+ var rawText = '';
281
+ var activeFilter = 'all';
282
  var activeCardIdx = null;
283
+ var pendingPdfFile = null;
284
+
285
+ // ── PDF state ─────────────────────────────────────────────────────────────
286
+
287
+ function initPdfState() {
288
+ fetch('/api/pdf-info').then(function(r) { return r.json(); }).then(function(d) {
289
+ if (d.saved && d.name) { showPdfReady(d.name); }
290
+ }).catch(function() {});
291
+ }
292
+
293
+ function handlePdfSelect(input) {
294
+ var file = input.files && input.files[0];
295
+ if (!file) return;
296
+ pendingPdfFile = file;
297
+ document.getElementById('pdf-picker-btn').style.display = 'none';
298
+ document.getElementById('pdf-ready-pill').style.display = 'none';
299
+ var pill = document.getElementById('pdf-pending-pill');
300
+ pill.style.display = 'inline-flex';
301
+ document.getElementById('pdf-pending-name').textContent = file.name;
302
+ input.value = '';
303
+ }
304
+
305
+ function showPdfReady(name) {
306
+ pendingPdfFile = null;
307
+ document.getElementById('pdf-picker-btn').style.display = 'none';
308
+ document.getElementById('pdf-pending-pill').style.display = 'none';
309
+ var pill = document.getElementById('pdf-ready-pill');
310
+ pill.style.display = 'inline-flex';
311
+ document.getElementById('pdf-ready-name').textContent = name;
312
+ }
313
+
314
+ window.addEventListener('DOMContentLoaded', initPdfState);
315
 
316
  var KATEX_OPTS = {
317
  delimiters: [
 
336
  }
337
  }
338
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
  // ── Extract ───────────────────────────────────────────────────────────────
340
 
341
  async function startExtract() {
342
  hideError();
 
 
343
  var tbStartRaw = document.getElementById('tb-start').value.trim();
344
  var tbEndRaw = document.getElementById('tb-end').value.trim();
345
  var tbStart = parseInt(tbStartRaw, 10);
346
  var tbEnd = parseInt(tbEndRaw, 10);
347
  var isReextract = rawText.trim().length > 0;
 
348
  if (!tbStartRaw || !tbEndRaw || Number.isNaN(tbStart) || Number.isNaN(tbEnd)) {
349
  showError('Please enter both start and end page numbers.');
350
  return;
 
359
 
360
  try {
361
  var form = new FormData();
 
362
  form.append('tb_start', tbStart);
363
  form.append('tb_end', tbEnd);
364
+ if (pendingPdfFile) { form.append('textbook', pendingPdfFile, pendingPdfFile.name); }
365
  var res = await fetch('/api/extract', { method: 'POST', body: form });
366
  if (!res.ok) { var e = await res.json(); throw new Error(e.detail || 'Extraction failed'); }
367
  var data = await res.json();
368
  rawText = data.text || '';
369
+ if (pendingPdfFile) { showPdfReady(pendingPdfFile.name); }
 
 
 
 
 
370
 
371
  var imgs = data.images || [];
372
  document.getElementById('extract-status').textContent =
 
895
  if SAVED_PDF.exists():
896
  name = SAVED_PDF_NAME.read_text(encoding="utf-8") if SAVED_PDF_NAME.exists() else "textbook.pdf"
897
  return {"saved": True, "name": name}
898
+ if BUNDLED_PDF.exists():
899
+ return {"saved": True, "name": BUNDLED_PDF_NAME}
900
  return {"saved": False, "name": None}
901
 
902
 
 
910
  with open(SAVED_PDF, "wb") as f:
911
  shutil.copyfileobj(textbook.file, f)
912
  SAVED_PDF_NAME.write_text(textbook.filename, encoding="utf-8")
913
+
914
+ active = _active_pdf()
915
+ if active is None:
916
+ raise HTTPException(status_code=400, detail="No PDF available. Please choose a PDF file first.")
917
 
918
  for old in OUTPUT_DIR.glob("q_page*"):
919
  old.unlink(missing_ok=True)
920
  text, images = await asyncio.to_thread(
921
+ extract_page_range, str(active), tb_start, tb_end, OUTPUT_DIR, "q"
922
  )
923
  with open(OUTPUT_DIR / "raw_text.txt", "w", encoding="utf-8") as f:
924
  f.write(text)