Spaces:
Running
Running
Download persistence.py from princessamygdala/HarvestForTwo: direct link, hf CLI and curl.
- Browser
- Download file 4.3 kB
-
https://huggingface.co/spaces/princessamygdala/HarvestForTwo/resolve/main/persistence.py
- Command line
-
hf download hf://spaces/princessamygdala/HarvestForTwo/persistence.py
-
curl -L -o persistence.py https://huggingface.co/spaces/princessamygdala/HarvestForTwo/resolve/main/persistence.py
4.3 kB
| """Shared data-persistence helpers usable from both web_app.py (the periodic | |
| timer) and effort_stages.py (per-trial saves) without an import cycle -- | |
| web_app.py already imports effort_stages, so the reverse isn't possible.""" | |
| import os | |
| from datetime import datetime | |
| import asyncio | |
| from nicegui import app | |
| import nicewebrl | |
| from nicewebrl.logging import get_logger | |
| logger = get_logger("persistence") | |
| # Per-pid locks so overlapping push_current_data calls for the SAME participant | |
| # (e.g. two trials finishing faster than one export+GitLab round trip) serialize | |
| # instead of racing on the same on-disk CSV file. Same idiom as web_app.py's | |
| # _user_locks / get_user_lock() (web_app.py:72, :186). | |
| _push_locks = {} | |
| def _get_push_lock(pid): | |
| if pid not in _push_locks: | |
| _push_locks[pid] = asyncio.Lock() | |
| return _push_locks[pid] | |
| def get_push_lock(pid): | |
| """Public accessor for _get_push_lock, for callers outside this module | |
| (e.g. web_app.py's end-of-session save) that need to hold the exact same | |
| per-pid lock as push_current_data() without duplicating the lock-registry | |
| logic here.""" | |
| return _get_push_lock(pid) | |
| async def push_current_data(pid): | |
| """Export the current local data file to CSV and push both to GitLab. | |
| Best-effort: failures are logged, never raised (a save hiccup must never | |
| interrupt the participant's session). Mirrors web_app.py's incremental_save | |
| body exactly, parameterized on pid so both the periodic timer and the | |
| per-trial caller can share it. | |
| Serialized per pid: export_qualtrics.export() writes a deterministic path | |
| per participant via a non-atomic `open(out, "w")`, run on a real OS thread | |
| via asyncio.to_thread. Without a lock, two overlapping calls for the same | |
| pid (plausible once this runs after every trial) can concurrently | |
| write/truncate that file and push a torn CSV to GitLab. | |
| Coalesced: if a push for this pid is already in flight, skip this call | |
| instead of queueing behind it. export_qualtrics.export() re-reads the | |
| on-disk data file fresh every time it runs (see export(), which calls | |
| read_all_records_sync(path) at call time, not from some snapshot taken | |
| when this was queued), so the in-flight push already captures a superset | |
| of whatever's on disk right now by the time IT finishes -- a queued call | |
| would just re-export/re-push data that's about to be superseded seconds | |
| later anyway. Without this, per-trial pushes queue up (measured: ~96 | |
| POSTs / ~50MB per participant instead of ~8-10).""" | |
| if not pid: | |
| return | |
| lock = _get_push_lock(pid) | |
| if lock.locked(): | |
| return | |
| async with lock: | |
| try: | |
| udf = nicewebrl.user_data_file() | |
| if not os.path.exists(udf): | |
| return | |
| import export_qualtrics | |
| import export_timing | |
| import gitlab_save | |
| csv_path = await asyncio.to_thread(export_qualtrics.export, udf, pid) | |
| timing_path = await asyncio.to_thread(export_timing.export, udf, pid) | |
| to_push = [f for f in [udf, csv_path, timing_path] if f and os.path.exists(f)] | |
| await asyncio.to_thread(gitlab_save.push_to_gitlab, to_push, f"pilot/{pid}", | |
| name_map=_stamped_names(to_push, pid)) | |
| except Exception as e: | |
| logger.warning(f"push_current_data failed: {e}") | |
| def _stamped_names(files, pid): | |
| """Map local filenames -> '<pid>_<date>_<time>...' so every stored file | |
| carries the participant id + the date/time of the session (PsychoPy-style, | |
| no overwrites). Single canonical copy: web_app.py imports this rather than | |
| keeping its own duplicate (persistence.py must never import from web_app, | |
| to avoid the import cycle this module exists to solve).""" | |
| ts = app.storage.user.get("session_ts") | |
| if not ts: | |
| ts = datetime.now().strftime("%Y-%m-%d_%Hh%M.%S") | |
| app.storage.user["session_ts"] = ts # one stamp per session | |
| name_map = {} | |
| for f in files: | |
| if not f: | |
| continue | |
| b = os.path.basename(f) | |
| # strip the internal "user_data_<seed>" prefix, keep any suffix (e.g. _behavioral.csv) | |
| rest = b.split(".", 1) | |
| ext = "." + rest[1] if len(rest) > 1 else "" | |
| suffix = "" | |
| stem = rest[0] | |
| if "_" in stem.replace("user_data_", "", 1): | |
| suffix = "_" + stem.replace("user_data_", "", 1).split("_", 1)[1] | |
| name_map[b] = f"{pid}_{ts}{suffix}{ext}" | |
| return name_map | |