GopiBNA commited on
Commit
52fb3f3
·
verified ·
1 Parent(s): fdb26a6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +208 -55
app.py CHANGED
@@ -269,54 +269,184 @@ ss.setdefault("uploader_nonce", 0)
269
  ss.setdefault("run_status", "idle") # idle | running | success | error
270
  ss.setdefault("run_error_msg", "")
271
  ss.setdefault("queue_id", None)
 
272
 
273
 
274
- def _stage_uploads(uploads, into_dir: Path) -> Path:
275
- """Stage Streamlit uploads to disk and unpack any ZIPs.
276
- Handles browser quirks where some uploads carry a path-like name
277
- (e.g. 'my_folder/data.xlsx') by flattening the basename — Streamlit's
278
- file_uploader can't accept a real folder, only files, so any 'path'
279
- in the name is decorative."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
280
  into_dir.mkdir(parents=True, exist_ok=True)
281
- staged = 0
282
- for up in uploads:
283
- # Some browsers send filenames with separators; keep just the basename.
284
- raw_name = (up.name or "").strip()
285
- if not raw_name:
286
- continue
287
- # Normalise both separator flavours
288
- basename = raw_name.replace("\\", "/").split("/")[-1] or raw_name
289
- target = into_dir / basename
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
290
  try:
291
- target.write_bytes(up.getvalue() or b"")
 
 
292
  except Exception as e:
293
- st.error(f"Could not save '{raw_name}': {e}")
294
- st.stop()
295
- # Unpack ZIPs in-place; treat anything else as a leaf file.
296
- if basename.lower().endswith(".zip"):
297
- try:
298
- with zipfile.ZipFile(target, "r") as zf:
299
- zf.extractall(into_dir)
300
- except zipfile.BadZipFile:
301
- st.error(f"'{basename}' is not a valid ZIP.")
302
- st.stop()
303
- target.unlink(missing_ok=True)
304
- elif basename.lower().endswith((".xlsx", ".xls", ".xlsm")):
305
- staged += 1
306
- # else: silently allow (TIE workbook, README, etc.) — they're harmless
307
-
308
- if staged == 0 and not any(into_dir.rglob("*.xlsx")) \
309
- and not any(into_dir.rglob("*.xls")) \
310
- and not any(into_dir.rglob("*.xlsm")):
311
- st.error(
312
- "No Excel files in your upload. The Comparator expects "
313
- "either a ZIP containing AI Excels, or individual .xlsx files. "
314
- "Streamlit cannot accept a folder directly — please either "
315
- "ZIP the folder first, or use 'Browse files' and Ctrl-click each "
316
- ".xlsx inside the folder."
 
 
 
 
317
  )
318
- st.stop()
319
- return into_dir
 
 
 
 
 
 
 
 
 
320
 
321
 
322
  def _zip_directory(src: Path) -> bytes:
@@ -455,14 +585,23 @@ with tab_inputs:
455
  )
456
 
457
  c1, c2 = st.columns([1, 4])
458
- _label(c1, "AI Excels (.xlsx files or ZIP)")
459
- ai_files = c2.file_uploader(
460
- "AI Excels",
461
- type=None,
462
- accept_multiple_files=True,
463
- label_visibility="collapsed",
464
- key=f"uploader_{ss.uploader_nonce}",
465
- )
 
 
 
 
 
 
 
 
 
466
 
467
  c1, c2 = st.columns([1, 4])
468
  _label(c1, "Output language")
@@ -491,7 +630,7 @@ with tab_inputs:
491
  _, c_btns = st.columns([1, 4])
492
  b1, b2, b3, _ = c_btns.columns([1.4, 1.8, 1.2, 4])
493
 
494
- run_disabled = not (ai_files and bna_email and bna_password)
495
  if b1.button("▶ Run batch", type="primary", disabled=run_disabled):
496
  ss.trigger_run = True
497
  ss.run_status = "running"
@@ -797,9 +936,12 @@ if ss.trigger_run:
797
 
798
  with tempfile.TemporaryDirectory(prefix="bna_web_") as tmp:
799
  tmp_path = Path(tmp)
800
- ai_dir = _stage_uploads(ai_files, tmp_path / "ai_input")
801
- out_dir = tmp_path / "output"
802
- out_dir.mkdir()
 
 
 
803
  tie_path = HERE / "resources" / "TIE_Requirements.xlsx"
804
 
805
  def _progress_cb(info):
@@ -815,7 +957,18 @@ if ss.trigger_run:
815
  ss.run_status = "error"
816
  ss.run_error_msg = error
817
  else:
818
- zip_bytes = _zip_directory(out_dir)
 
 
 
 
 
 
 
 
 
 
 
819
  ss.last_zip_bytes = zip_bytes
820
  ts = datetime.now().strftime("%Y%m%d_%H%M%S")
821
  ss.last_zip_name = f"bna_comparator_results_{ts}.zip"
 
269
  ss.setdefault("run_status", "idle") # idle | running | success | error
270
  ss.setdefault("run_error_msg", "")
271
  ss.setdefault("queue_id", None)
272
+ ss.setdefault("zip_layout", {})
273
 
274
 
275
+ REQUIRED_ZIP_FOLDERS = ("Input", "Output", "Summary")
276
+
277
+
278
+ def _validation_error(title: str, body: str) -> None:
279
+ """Render a friendly inline error and stop the run. Title is shown
280
+ as a banner, body explains exactly what the researcher should do."""
281
+ st.markdown(
282
+ f'<div class="status-banner error">'
283
+ f'<div class="icon">⚠️</div>'
284
+ f'<div><b>{title}</b><br>{body}</div>'
285
+ f'</div>',
286
+ unsafe_allow_html=True,
287
+ )
288
+ st.stop()
289
+
290
+
291
+ def _stage_zip(upload, into_dir: Path) -> Path:
292
+ """Strict validation pipeline for the single-ZIP upload.
293
+
294
+ The Comparator now accepts exactly one ZIP, with this internal
295
+ structure:
296
+
297
+ Comparator_<batch-name>.zip
298
+ ├── Input/ ← AI Excel files (.xlsx)
299
+ ├── Output/ ← (created/managed by Comparator; can be empty)
300
+ └── Summary/ ← (created/managed by Comparator; can be empty)
301
+
302
+ Any deviation raises a clear, actionable validation message and
303
+ halts the run before the engine starts. The engine then reads AI
304
+ Excels from `Input/`, writes per-project results to `Output/`, and
305
+ drops the batch summary into `Summary/`.
306
+ """
307
  into_dir.mkdir(parents=True, exist_ok=True)
308
+
309
+ # --- 1) File presence ----------------------------------------------
310
+ if upload is None:
311
+ _validation_error(
312
+ "No file uploaded",
313
+ "Drop a ZIP into the uploader. The Comparator accepts exactly "
314
+ "one ZIP per run — see the panel for the required folder layout.",
315
+ )
316
+
317
+ raw_name = (upload.name or "").strip()
318
+ if not raw_name:
319
+ _validation_error(
320
+ "Upload has no filename",
321
+ "Your browser sent a file with an empty name. Try uploading again, "
322
+ "or rename the ZIP before uploading.",
323
+ )
324
+
325
+ # --- 2) Extension --------------------------------------------------
326
+ if not raw_name.lower().endswith(".zip"):
327
+ _validation_error(
328
+ f'"{raw_name}" is not a ZIP file',
329
+ "The Comparator only accepts a single <code>.zip</code> archive. "
330
+ "Right-click the folder containing your Input/Output/Summary "
331
+ "folders → <b>Send to → Compressed (zipped) folder</b>, then "
332
+ "upload the resulting <code>.zip</code>.",
333
+ )
334
+
335
+ # --- 3) Save to disk -----------------------------------------------
336
+ basename = raw_name.replace("\\", "/").split("/")[-1] or raw_name
337
+ zip_path = into_dir / basename
338
+ try:
339
+ zip_path.write_bytes(upload.getvalue() or b"")
340
+ except Exception as e:
341
+ _validation_error(
342
+ "Could not save your upload",
343
+ f"Something went wrong saving <code>{basename}</code> to the "
344
+ f"server: <code>{e}</code>. Try uploading again.",
345
+ )
346
+
347
+ # --- 4) Valid ZIP --------------------------------------------------
348
+ try:
349
+ zf = zipfile.ZipFile(zip_path, "r")
350
+ except zipfile.BadZipFile:
351
+ _validation_error(
352
+ f'"{basename}" is not a valid ZIP',
353
+ "The file uploaded with a <code>.zip</code> extension but its "
354
+ "contents are corrupted or in a different format. Re-create the "
355
+ "ZIP and upload again.",
356
+ )
357
+
358
+ # --- 5) Structure: Input / Output / Summary at the top level -------
359
+ # Walk the ZIP namelist to find which top-level folders exist. We
360
+ # tolerate either Comparator_xxx/Input/ (single root wrapper, e.g.
361
+ # Windows ZIP creates this) OR Input/ directly at the root.
362
+ with zf:
363
+ names = zf.namelist()
364
+ # Build set of top-level entries (folders). Strip empty roots.
365
+ top_level: set[str] = set()
366
+ nested_under: dict[str, set[str]] = {}
367
+ for n in names:
368
+ parts = [p for p in n.replace("\\", "/").split("/") if p]
369
+ if not parts:
370
+ continue
371
+ top_level.add(parts[0])
372
+ if len(parts) >= 2:
373
+ nested_under.setdefault(parts[0], set()).add(parts[1])
374
+
375
+ wrapper = ""
376
+ if all(folder in top_level for folder in REQUIRED_ZIP_FOLDERS):
377
+ # Folders are at the ZIP root
378
+ wrapper = ""
379
+ elif len(top_level) == 1:
380
+ only = next(iter(top_level))
381
+ children = nested_under.get(only, set())
382
+ if all(folder in children for folder in REQUIRED_ZIP_FOLDERS):
383
+ wrapper = only
384
+ else:
385
+ _validation_error(
386
+ "ZIP is missing the required folders",
387
+ f"Your ZIP contains a single top folder <code>{only}/</code>, "
388
+ f"but inside it we expected <code>Input/</code>, "
389
+ f"<code>Output/</code>, and <code>Summary/</code>. "
390
+ f"Found instead: <code>{', '.join(sorted(children)) or '(empty)'}</code>.",
391
+ )
392
+ else:
393
+ missing = [f for f in REQUIRED_ZIP_FOLDERS if f not in top_level]
394
+ _validation_error(
395
+ "ZIP is missing the required folders",
396
+ f"The ZIP must contain three folders at its root: "
397
+ f"<code>Input/</code>, <code>Output/</code>, "
398
+ f"<code>Summary/</code>. Missing: "
399
+ f"<code>{', '.join(missing) or '(none — but layout is off)'}</code>."
400
+ f"<br><br>Found at root: "
401
+ f"<code>{', '.join(sorted(top_level)) or '(empty ZIP)'}</code>.",
402
+ )
403
+
404
+ # --- 6) Extract -----------------------------------------------
405
  try:
406
+ zf_ref = zipfile.ZipFile(zip_path, "r")
407
+ with zf_ref:
408
+ zf_ref.extractall(into_dir)
409
  except Exception as e:
410
+ _validation_error(
411
+ "Could not unpack the ZIP",
412
+ f"Extraction failed with: <code>{e}</code>. Re-create the ZIP "
413
+ f"with standard tooling (Windows: right-click → Send to → "
414
+ f"Compressed; Mac: right-click → Compress) and try again.",
415
+ )
416
+
417
+ # Resolve the actual Input/ folder on disk after extraction
418
+ root = into_dir / wrapper if wrapper else into_dir
419
+ input_dir = root / "Input"
420
+ output_dir = root / "Output"
421
+ summary_dir = root / "Summary"
422
+
423
+ # Belt-and-braces: make sure the dirs actually exist on disk too
424
+ for d in (input_dir, output_dir, summary_dir):
425
+ d.mkdir(parents=True, exist_ok=True)
426
+
427
+ # --- 7) Input/ must have at least one Excel file -------------------
428
+ excels = []
429
+ for ext in (".xlsx", ".xls", ".xlsm"):
430
+ excels.extend(input_dir.rglob(f"*{ext}"))
431
+ excels = [p for p in excels if not p.name.startswith("~$")]
432
+ if not excels:
433
+ _validation_error(
434
+ "The Input/ folder is empty",
435
+ "Your ZIP has the right structure, but <code>Input/</code> "
436
+ "contains no Excel files. Put your AI Excels (<code>.xlsx</code>) "
437
+ "into the Input folder, re-zip, and upload again.",
438
  )
439
+
440
+ # Stash the resolved layout on the upload object via attribute trick —
441
+ # the run handler reads it back from session_state instead, set there.
442
+ ss.zip_layout = {
443
+ "root": str(root),
444
+ "input": str(input_dir),
445
+ "output": str(output_dir),
446
+ "summary": str(summary_dir),
447
+ "zip_basename": basename,
448
+ }
449
+ return root
450
 
451
 
452
  def _zip_directory(src: Path) -> bytes:
 
585
  )
586
 
587
  c1, c2 = st.columns([1, 4])
588
+ _label(c1, "Comparator ZIP")
589
+ with c2:
590
+ ai_zip = st.file_uploader(
591
+ "Comparator ZIP",
592
+ type=["zip"],
593
+ accept_multiple_files=False,
594
+ label_visibility="collapsed",
595
+ key=f"uploader_{ss.uploader_nonce}",
596
+ help="Upload a single .zip with Input/, Output/, and Summary/ folders inside.",
597
+ )
598
+ st.caption(
599
+ "Required ZIP layout: "
600
+ "**`Input/`** (your AI Excels) · "
601
+ "**`Output/`** · "
602
+ "**`Summary/`**. "
603
+ "One ZIP per run."
604
+ )
605
 
606
  c1, c2 = st.columns([1, 4])
607
  _label(c1, "Output language")
 
630
  _, c_btns = st.columns([1, 4])
631
  b1, b2, b3, _ = c_btns.columns([1.4, 1.8, 1.2, 4])
632
 
633
+ run_disabled = not (ai_zip and bna_email and bna_password)
634
  if b1.button("▶ Run batch", type="primary", disabled=run_disabled):
635
  ss.trigger_run = True
636
  ss.run_status = "running"
 
936
 
937
  with tempfile.TemporaryDirectory(prefix="bna_web_") as tmp:
938
  tmp_path = Path(tmp)
939
+ # Strict single-ZIP validation + extract Input/Output/Summary
940
+ staged_root = _stage_zip(ai_zip, tmp_path / "staged")
941
+ layout = ss.zip_layout
942
+ ai_dir = Path(layout["input"])
943
+ out_dir = Path(layout["output"])
944
+ summary_dir = Path(layout["summary"])
945
  tie_path = HERE / "resources" / "TIE_Requirements.xlsx"
946
 
947
  def _progress_cb(info):
 
957
  ss.run_status = "error"
958
  ss.run_error_msg = error
959
  else:
960
+ # Move the batch summary xlsx (written into out_dir by
961
+ # batch_runner) into Summary/ so the researcher's ZIP
962
+ # layout stays clean.
963
+ try:
964
+ for f in out_dir.glob("batch_summary_*.xlsx"):
965
+ f.replace(summary_dir / f.name)
966
+ except Exception:
967
+ pass
968
+ # Repackage the whole Input/Output/Summary tree (sans
969
+ # the original Input/ payload) so the researcher can
970
+ # download an organized result archive.
971
+ zip_bytes = _zip_directory(staged_root)
972
  ss.last_zip_bytes = zip_bytes
973
  ts = datetime.now().strftime("%Y%m%d_%H%M%S")
974
  ss.last_zip_name = f"bna_comparator_results_{ts}.zip"