Spaces:
Runtime error
Runtime error
Download engine/feedback_store.py from BNAmericas/ComparerTool: direct link, hf CLI and curl.
- Browser
- Download file 12.4 kB
-
https://huggingface.co/spaces/BNAmericas/ComparerTool/resolve/main/engine/feedback_store.py
- Command line
-
hf download hf://spaces/BNAmericas/ComparerTool/engine/feedback_store.py
-
curl -L -o feedback_store.py https://huggingface.co/spaces/BNAmericas/ComparerTool/resolve/main/engine/feedback_store.py
12.4 kB
| """Feedback storage with status tracking + Excel export. | |
| The Comparer Tool's Feedback tab collects free-text comments, project | |
| references, plus uploaded attachments (screenshots, technical files). | |
| This module is the storage layer. | |
| Workflow per submission | |
| ----------------------- | |
| 1. The Streamlit handler builds a dict of fields and a list of | |
| (filename, bytes) attachments. | |
| 2. ``save_submission()`` writes a self-contained folder under | |
| ``$BNA_FEEDBACK_DIR`` (default ``/tmp/bna_feedback``) named | |
| ``YYYYMMDD_HHMMSS_<8-char-id>``: | |
| feedback.json -- all form fields + manifest | |
| admin.json -- status + admin_notes (added later) | |
| attachments/ -- every uploaded file, original name | |
| attachments.zip -- same contents zipped | |
| 3. The Admin tab can: | |
| - Edit each submission's status + notes via ``update_submission()``. | |
| - Pull every submission into one Excel via ``export_all_as_excel()``. | |
| - Pull every submission + every attachment as one ZIP via | |
| ``collect_all_as_zip()``. | |
| Status workflow | |
| --------------- | |
| New submissions start with ``status = "Open"``. The team lead can move | |
| each one through: | |
| Open -> In Progress -> Resolved | |
| \-> Won't Fix | |
| \-> Closed | |
| The status + admin_notes live in ``admin.json`` next to ``feedback.json`` | |
| so researcher-side metadata stays separate from team-lead metadata. | |
| """ | |
| from __future__ import annotations | |
| import io | |
| import json | |
| import os | |
| import uuid | |
| import zipfile | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| from typing import Any, Dict, Iterable, List, Optional, Tuple | |
| # --------------------------------------------------------------------- | |
| # Status workflow. | |
| # --------------------------------------------------------------------- | |
| STATUS_OPTIONS: Tuple[str, ...] = ( | |
| "Open", | |
| "In Progress", | |
| "Resolved", | |
| "Won't Fix", | |
| "Closed", | |
| ) | |
| DEFAULT_STATUS = "Open" | |
| # --------------------------------------------------------------------- | |
| # Paths. | |
| # --------------------------------------------------------------------- | |
| def _root() -> Path: | |
| raw = os.environ.get("BNA_FEEDBACK_DIR") | |
| if raw: | |
| return Path(raw) | |
| return Path("/tmp/bna_feedback") | |
| def _submission_dir(submission_id: str) -> Path: | |
| return _root() / submission_id | |
| # --------------------------------------------------------------------- | |
| # Save. | |
| # --------------------------------------------------------------------- | |
| def _new_submission_id() -> str: | |
| stamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S") | |
| return f"{stamp}_{uuid.uuid4().hex[:8]}" | |
| def _safe_name(name: str) -> str: | |
| name = (name or "upload").strip().replace("\\", "_").replace("/", "_") | |
| name = "".join(c for c in name if c.isalnum() or c in (".", "-", "_", " ")) | |
| return name[:120] or "upload" | |
| def save_submission( | |
| fields: Dict[str, Any], | |
| attachments: Iterable[Tuple[str, bytes]] = (), | |
| ) -> Dict[str, Any]: | |
| """Persist a feedback submission + its attachments. Returns the | |
| manifest dict written to ``feedback.json``.""" | |
| sid = _new_submission_id() | |
| sdir = _submission_dir(sid) | |
| sdir.mkdir(parents=True, exist_ok=True) | |
| adir = sdir / "attachments" | |
| adir.mkdir(exist_ok=True) | |
| saved_attachments: List[Dict[str, Any]] = [] | |
| for raw_name, blob in attachments: | |
| if not blob: | |
| continue | |
| name = _safe_name(raw_name) | |
| out = adir / name | |
| i = 1 | |
| base = out.stem | |
| ext = out.suffix | |
| while out.exists(): | |
| out = adir / f"{base}_{i}{ext}" | |
| i += 1 | |
| out.write_bytes(blob) | |
| saved_attachments.append({"name": out.name, "bytes": len(blob)}) | |
| manifest: Dict[str, Any] = { | |
| "submission_id": sid, | |
| "received_at": datetime.now(timezone.utc).isoformat(), | |
| "fields": dict(fields), | |
| "attachments": saved_attachments, | |
| } | |
| (sdir / "feedback.json").write_text( | |
| json.dumps(manifest, indent=2, ensure_ascii=False), | |
| encoding="utf-8", | |
| ) | |
| try: | |
| os.chmod(sdir / "feedback.json", 0o600) | |
| except Exception: | |
| pass | |
| # Seed admin.json with the default Open status so it shows up in | |
| # the data editor right away. | |
| _write_admin(sid, {"status": DEFAULT_STATUS, "admin_notes": ""}) | |
| # Zip the per-submission folder for the team-lead bulk download. | |
| zip_path = sdir / "attachments.zip" | |
| with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf: | |
| zf.write(sdir / "feedback.json", arcname="feedback.json") | |
| for att in saved_attachments: | |
| zf.write(adir / att["name"], arcname=f"attachments/{att['name']}") | |
| return manifest | |
| # --------------------------------------------------------------------- | |
| # Admin metadata (status + notes). | |
| # --------------------------------------------------------------------- | |
| def _admin_path(submission_id: str) -> Path: | |
| return _submission_dir(submission_id) / "admin.json" | |
| def _read_admin(submission_id: str) -> Dict[str, Any]: | |
| p = _admin_path(submission_id) | |
| if not p.exists(): | |
| return {"status": DEFAULT_STATUS, "admin_notes": ""} | |
| try: | |
| d = json.loads(p.read_text(encoding="utf-8")) | |
| d.setdefault("status", DEFAULT_STATUS) | |
| d.setdefault("admin_notes", "") | |
| return d | |
| except Exception: | |
| return {"status": DEFAULT_STATUS, "admin_notes": ""} | |
| def _write_admin(submission_id: str, data: Dict[str, Any]) -> None: | |
| p = _admin_path(submission_id) | |
| p.parent.mkdir(parents=True, exist_ok=True) | |
| payload = { | |
| "status": data.get("status") or DEFAULT_STATUS, | |
| "admin_notes": data.get("admin_notes") or "", | |
| "updated_at": datetime.now(timezone.utc).isoformat(), | |
| } | |
| p.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8") | |
| try: | |
| os.chmod(p, 0o600) | |
| except Exception: | |
| pass | |
| def update_submission( | |
| submission_id: str, | |
| status: Optional[str] = None, | |
| admin_notes: Optional[str] = None, | |
| ) -> Dict[str, Any]: | |
| """Set the team-lead status and / or notes for a submission. Only | |
| the keys passed are updated; pass None to leave unchanged.""" | |
| cur = _read_admin(submission_id) | |
| if status is not None: | |
| if status not in STATUS_OPTIONS: | |
| status = DEFAULT_STATUS | |
| cur["status"] = status | |
| if admin_notes is not None: | |
| cur["admin_notes"] = admin_notes | |
| _write_admin(submission_id, cur) | |
| return cur | |
| def update_many(updates: Dict[str, Dict[str, Any]]) -> int: | |
| """Bulk update. ``updates`` keyed by submission_id, value is a dict | |
| with optional ``status`` and ``admin_notes``. Returns count of | |
| rows touched.""" | |
| n = 0 | |
| for sid, data in updates.items(): | |
| update_submission( | |
| sid, | |
| status=data.get("status"), | |
| admin_notes=data.get("admin_notes"), | |
| ) | |
| n += 1 | |
| return n | |
| # --------------------------------------------------------------------- | |
| # Listing + bulk downloads. | |
| # --------------------------------------------------------------------- | |
| def list_submissions() -> List[Dict[str, Any]]: | |
| """List every submission folder. Newest first. Each row includes | |
| the researcher manifest AND the admin overlay merged in.""" | |
| root = _root() | |
| if not root.exists(): | |
| return [] | |
| out: List[Dict[str, Any]] = [] | |
| for sub in sorted(root.iterdir(), reverse=True): | |
| if not sub.is_dir(): | |
| continue | |
| meta = sub / "feedback.json" | |
| if not meta.exists(): | |
| continue | |
| try: | |
| rec = json.loads(meta.read_text(encoding="utf-8")) | |
| except Exception: | |
| continue | |
| admin = _read_admin(rec["submission_id"]) | |
| rec["status"] = admin.get("status", DEFAULT_STATUS) | |
| rec["admin_notes"] = admin.get("admin_notes", "") | |
| rec["admin_updated_at"] = admin.get("updated_at", "") | |
| out.append(rec) | |
| return out | |
| def count_submissions() -> int: | |
| return len(list_submissions()) | |
| def collect_all_as_zip() -> bytes: | |
| """Bundle every feedback submission folder (researcher fields, | |
| attachments, admin overlay) into one ZIP.""" | |
| buf = io.BytesIO() | |
| root = _root() | |
| with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf: | |
| if root.exists(): | |
| for sub in sorted(root.iterdir()): | |
| if not sub.is_dir(): | |
| continue | |
| for f in sub.rglob("*"): | |
| if f.is_file(): | |
| zf.write(f, arcname=str(f.relative_to(root))) | |
| return buf.getvalue() | |
| # --------------------------------------------------------------------- | |
| # Excel export -- meeting-friendly view. | |
| # --------------------------------------------------------------------- | |
| def export_all_as_excel() -> bytes: | |
| """Return an .xlsx blob with one row per submission. The team lead | |
| downloads this from the Admin tab to discuss in meetings.""" | |
| # Local import so the module stays cheap to import in non-Excel | |
| # paths (e.g. the form-submit handler). | |
| import openpyxl | |
| from openpyxl.styles import Font, PatternFill, Alignment, Border, Side | |
| from openpyxl.utils import get_column_letter | |
| NAVY = "FF1E3A8A" | |
| LIGHT = "FFF8FAFC" | |
| BORDER_GREY = "FFE5E7EB" | |
| headers = [ | |
| "Submission ID", | |
| "Received at (UTC)", | |
| "Status", | |
| "Admin notes", | |
| "Researcher name", | |
| "Researcher email", | |
| "Feedback type", | |
| "Severity", | |
| "Project name", | |
| "Permalink", | |
| "Subject", | |
| "Comment", | |
| "Attachments (count)", | |
| "Attachment files", | |
| "Last reviewed (UTC)", | |
| ] | |
| wb = openpyxl.Workbook() | |
| ws = wb.active | |
| ws.title = "Feedback log" | |
| # Header styling. | |
| header_font = Font(bold=True, color="FFFFFFFF", name="Calibri", size=11) | |
| header_fill = PatternFill("solid", fgColor=NAVY) | |
| thin = Side(style="thin", color=BORDER_GREY) | |
| border = Border(top=thin, bottom=thin, left=thin, right=thin) | |
| center = Alignment(horizontal="left", vertical="top", wrap_text=True) | |
| for col_idx, h in enumerate(headers, start=1): | |
| c = ws.cell(row=1, column=col_idx, value=h) | |
| c.font = header_font | |
| c.fill = header_fill | |
| c.alignment = Alignment(horizontal="left", vertical="center") | |
| c.border = border | |
| # Body rows. | |
| body_font = Font(name="Calibri", size=11) | |
| row_idx = 2 | |
| for rec in list_submissions(): | |
| f = rec.get("fields", {}) | |
| atts = rec.get("attachments", []) or [] | |
| att_names = ", ".join(a.get("name", "") for a in atts) | |
| values = [ | |
| rec.get("submission_id", ""), | |
| rec.get("received_at", ""), | |
| rec.get("status", DEFAULT_STATUS), | |
| rec.get("admin_notes", ""), | |
| f.get("researcher_name", ""), | |
| f.get("researcher_email", ""), | |
| f.get("feedback_type", ""), | |
| f.get("severity", ""), | |
| f.get("project_ref", ""), | |
| f.get("permalink", ""), | |
| f.get("subject", ""), | |
| f.get("comment", ""), | |
| len(atts), | |
| att_names, | |
| rec.get("admin_updated_at", ""), | |
| ] | |
| for col_idx, v in enumerate(values, start=1): | |
| c = ws.cell(row=row_idx, column=col_idx, value=v) | |
| c.font = body_font | |
| c.alignment = center | |
| c.border = border | |
| # Tint the Status cell so it pops in the meeting view. | |
| status = (rec.get("status") or "").lower() | |
| status_cell = ws.cell(row=row_idx, column=3) | |
| tint = { | |
| "open": "FFFEE2E2", | |
| "in progress": "FFFEF3C7", | |
| "resolved": "FFDCFCE7", | |
| "won't fix": "FFE5E7EB", | |
| "closed": "FFE5E7EB", | |
| }.get(status, "FFFFFFFF") | |
| status_cell.fill = PatternFill("solid", fgColor=tint) | |
| row_idx += 1 | |
| # Freeze header + auto column widths. | |
| ws.freeze_panes = "A2" | |
| widths = [22, 22, 13, 38, 22, 30, 14, 12, 28, 28, 30, 60, 8, 40, 22] | |
| for i, w in enumerate(widths, start=1): | |
| ws.column_dimensions[get_column_letter(i)].width = w | |
| # Tall rows so wrapped Comment is visible. | |
| for r in range(2, row_idx): | |
| ws.row_dimensions[r].height = 42 | |
| buf = io.BytesIO() | |
| wb.save(buf) | |
| return buf.getvalue() | |