Spaces:
Running
Running
Download gitlab_save.py from princessamygdala/HarvestForTwo: direct link, hf CLI and curl.
- Browser
- Download file 12 kB
-
https://huggingface.co/spaces/princessamygdala/HarvestForTwo/resolve/main/gitlab_save.py
- Command line
-
hf download hf://spaces/princessamygdala/HarvestForTwo/gitlab_save.py
-
curl -L -o gitlab_save.py https://huggingface.co/spaces/princessamygdala/HarvestForTwo/resolve/main/gitlab_save.py
12 kB
| """ | |
| Push a participant's data files to a GitLab repo via the API. | |
| Configured by environment variables (set locally in .env or as Hugging Face Space secrets): | |
| GITLAB_TOKEN -- a project/personal access token with `write_repository` (or `api`) scope | |
| GITLAB_PROJECT -- the repo path, e.g. "princessamygdala/task_sl-cu-data" | |
| GITLAB_URL -- default "https://gitlab.com" | |
| GITLAB_BRANCH -- default "master" | |
| If GITLAB_TOKEN / GITLAB_PROJECT are unset, push_to_gitlab() is a no-op (returns False), | |
| so local-only runs keep working. | |
| """ | |
| import base64 | |
| import csv | |
| import io | |
| import os | |
| from urllib.parse import quote | |
| try: | |
| import requests | |
| except Exception: # pragma: no cover | |
| requests = None | |
| #: Where the data repos actually are. This defaulted to gitlab.pavlovia.org, | |
| #: inherited from the task this was forked from, and nothing here is on | |
| #: Pavlovia. With GITLAB_URL unset, every push authenticated a gitlab.com | |
| #: token against Pavlovia, was refused, and returned False -- which nothing | |
| #: looked at. A Space with its token and project both set, reporting healthy, | |
| #: saving nothing, on a filesystem that does not survive a restart. | |
| GITLAB_URL_DEFAULT = "https://gitlab.com" | |
| def _loud(msg): | |
| """Report to the app log if there is one, and to stdout regardless, which | |
| is what a HuggingFace Space's logs capture.""" | |
| print(f"[gitlab] {msg}", flush=True) | |
| try: | |
| import logging | |
| logging.getLogger("main").warning(f"[gitlab] {msg}") | |
| except Exception: | |
| pass | |
| def _env(): | |
| return (os.getenv("GITLAB_TOKEN", "").strip(), | |
| os.getenv("GITLAB_PROJECT", "").strip(), | |
| os.getenv("GITLAB_URL", GITLAB_URL_DEFAULT).strip().rstrip("/"), | |
| (os.getenv("GITLAB_BRANCH", "") or "").strip()) | |
| def _get_raw(base, pid, token, branch, path): | |
| try: | |
| r = requests.get( | |
| f"{base}/api/v4/projects/{pid}/repository/files/{quote(path, safe='')}/raw", | |
| params={"ref": branch}, headers={"PRIVATE-TOKEN": token}, timeout=20) | |
| return r.text if r.status_code < 400 else None | |
| except Exception: | |
| return None | |
| def _get_file(base, pid, token, branch, path): | |
| """(text, last_commit_id) for a file, or (None, None) if it is not there. | |
| The commit id is what makes a read-modify-write safe: handing it back on | |
| the update tells GitLab to refuse if anyone else has written since. | |
| """ | |
| try: | |
| r = requests.get( | |
| f"{base}/api/v4/projects/{pid}/repository/files/{quote(path, safe='')}", | |
| params={"ref": branch}, headers={"PRIVATE-TOKEN": token}, timeout=20) | |
| if r.status_code >= 400: | |
| return None, None | |
| j = r.json() | |
| return (base64.b64decode(j.get("content", "")).decode("utf-8", "replace"), | |
| j.get("last_commit_id")) | |
| except Exception: | |
| return None, None | |
| #: How many times to re-read and retry when someone else wrote first. | |
| _APPEND_ATTEMPTS = 5 | |
| def append_to_log(row, path="randomization_log.csv", key="pid"): | |
| """Append one row to a growing CSV in the repo, safely against concurrency. | |
| `key` names the column that makes a row unique; re-appending a row whose | |
| key is already present is a no-op. Defaults to "pid", but callers logging | |
| participant arrivals should pass key="session": pilot links are handed out | |
| as "pick one at random", so several participants share a pid and keying on | |
| it would silently drop everyone after the first. | |
| This is a read-modify-write, and it used to be an unguarded one: read the | |
| file, append a row, commit the whole thing back. Two people arriving in | |
| the same moment both read N rows and both write N+1, and the second | |
| silently erases the first. Arrivals are exactly when that happens -- a | |
| class gets the link at once -- and this log exists to catch the people who | |
| drop out before any other file is written, so a lost row here is a | |
| participant who leaves no trace at all. | |
| Each attempt now hands back the commit id it read, which GitLab refuses if | |
| anyone has written since, and re-reads on conflict. After | |
| _APPEND_ATTEMPTS it gives up and says so rather than guessing. | |
| """ | |
| token, project, base, branch = _env() | |
| if not token or not project or requests is None: | |
| _loud(f"roster row NOT written (missing token/project): {row.get(key)!r}") | |
| return False | |
| pid_id = quote(project, safe="") | |
| branch = branch or _default_branch(base, pid_id, token) or "main" | |
| last = None | |
| for attempt in range(1, _APPEND_ATTEMPTS + 1): | |
| existing, commit_id = _get_file(base, pid_id, token, branch, path) | |
| if existing: | |
| rdr = list(csv.DictReader(io.StringIO(existing))) | |
| cols = list(rdr[0].keys()) if rdr else list(row.keys()) | |
| if any(str(r.get(key)) == str(row.get(key)) for r in rdr): | |
| return True # already logged this row | |
| rows = rdr + [row] | |
| action = {"action": "update", "last_commit_id": commit_id} | |
| else: | |
| cols = list(row.keys()) | |
| rows = [row] | |
| action = {"action": "create"} | |
| buf = io.StringIO() | |
| w = csv.DictWriter(buf, fieldnames=cols) | |
| w.writeheader() | |
| for r in rows: | |
| w.writerow({k: r.get(k, "") for k in cols}) | |
| action.update(file_path=path, | |
| content=base64.b64encode(buf.getvalue().encode()).decode("ascii"), | |
| encoding="base64") | |
| last = _commit(base, pid_id, token, branch, "randomization log", [action]) | |
| if last.status_code < 400: | |
| return True | |
| # 400 and 409 are both how GitLab reports "someone wrote first" here. | |
| if last.status_code not in (400, 409): | |
| break | |
| _loud(f"roster row NOT written after {attempt} attempt(s): key={row.get(key)!r} " | |
| f"host={base.split('//')[-1].split('/')[0]} project={project} " | |
| f"status={getattr(last, 'status_code', '?')} " | |
| f"{getattr(last, 'text', '')[:200]}") | |
| return False | |
| def _file_exists(base, pid, token, branch, path): | |
| """Is `path` already in the repo on `branch`? | |
| HEAD, not GET: a session msgpack is hundreds of kilobytes and the answer | |
| needed here is one bit. None means the question could not be asked (a | |
| network error), which callers treat as "unknown" and resolve by trying | |
| both verbs. | |
| """ | |
| try: | |
| r = requests.head( | |
| f"{base}/api/v4/projects/{pid}/repository/files/{quote(path, safe='')}", | |
| params={"ref": branch}, headers={"PRIVATE-TOKEN": token}, timeout=15) | |
| if r.status_code == 404: | |
| return False | |
| if r.status_code < 400: | |
| return True | |
| return None | |
| except Exception: | |
| return None | |
| def _commit(base, pid, token, branch, message, actions): | |
| url = f"{base}/api/v4/projects/{pid}/repository/commits" | |
| return requests.post( | |
| url, headers={"PRIVATE-TOKEN": token}, | |
| json={"branch": branch, "commit_message": message, "actions": actions}, | |
| timeout=30, | |
| ) | |
| def _default_branch(base, pid, token): | |
| """Ask GitLab what the repo's default branch is (so master/main 'just works').""" | |
| try: | |
| r = requests.get(f"{base}/api/v4/projects/{pid}", | |
| headers={"PRIVATE-TOKEN": token}, timeout=15) | |
| if r.status_code < 400: | |
| return r.json().get("default_branch") | |
| except Exception: | |
| pass | |
| return None | |
| def _commit_one_by_one(base, pid, token, branch, msg, actions, verbose=False): | |
| """Commit each action on its own, create then update, and report whether | |
| every one of them landed. | |
| The fallback for a combined commit that was refused: a participant's data | |
| file is worth more than the tidiness of one commit, and a single path the | |
| server will not take must not take the rest down with it. | |
| """ | |
| all_ok = True | |
| for a in actions: | |
| r = _commit(base, pid, token, branch, msg, [a]) | |
| if r.status_code >= 400: | |
| flipped = dict(a, action=("create" if a["action"] == "update" else "update")) | |
| r = _commit(base, pid, token, branch, msg, [flipped]) | |
| if r.status_code >= 400: | |
| all_ok = False | |
| _loud(f"push FAILED for {a['file_path']}: status={r.status_code} " | |
| f"{r.text[:200]}") | |
| elif verbose: | |
| print(f"[gitlab] {a['file_path']} status={r.status_code}") | |
| return all_ok | |
| def push_to_gitlab(file_paths, subdir="data", verbose=False, name_map=None): | |
| """Commit the given local files into <repo>/<subdir>/. Returns True on success. | |
| name_map: optional {local_basename: dest_basename} to rename files in the repo | |
| (e.g. to embed pid + date/time in the stored filename).""" | |
| name_map = name_map or {} | |
| # .strip() guards against trailing newlines/spaces pasted into env vars or | |
| # HF Space secrets (a newline in a token makes the HTTP header invalid). | |
| token = os.getenv("GITLAB_TOKEN", "").strip() | |
| project = os.getenv("GITLAB_PROJECT", "").strip() | |
| base = os.getenv("GITLAB_URL", GITLAB_URL_DEFAULT).strip().rstrip("/") | |
| if not token or not project or requests is None: | |
| _loud("missing GITLAB_TOKEN / GITLAB_PROJECT (or requests) -> NOT SAVING") | |
| return False | |
| pid = quote(project, safe="") | |
| branch = (os.getenv("GITLAB_BRANCH", "") or "").strip() or _default_branch(base, pid, token) or "master" | |
| actions = [] | |
| for fp in file_paths: | |
| if not os.path.exists(fp): | |
| continue | |
| with open(fp, "rb") as fh: | |
| content = base64.b64encode(fh.read()).decode("ascii") | |
| base_name = os.path.basename(fp) | |
| dest_name = name_map.get(base_name, base_name) | |
| dest_path = f"{subdir}/{dest_name}" | |
| # Per file, because a commit is atomic and these files do not arrive | |
| # together. A session pushes its msgpack and CSV every couple of | |
| # minutes, so by the end of the session those two exist and the | |
| # metadata JSON, written once at the end, does not. One "create" list | |
| # was refused for the two that existed and one "update" list for the | |
| # one that did not, so the LAST push of every session -- the only one | |
| # that carries the final questionnaires -- was rejected twice and | |
| # landed nothing. Thirty-odd sessions, not one metadata file, and | |
| # every stored msgpack frozen at its last periodic push. | |
| exists = _file_exists(base, pid, token, branch, dest_path) | |
| actions.append({ | |
| "action": "update" if exists else "create", | |
| "file_path": dest_path, | |
| "content": content, | |
| "encoding": "base64", | |
| }) | |
| if not actions: | |
| return False | |
| msg = f"data: {subdir}" | |
| r = _commit(base, pid, token, branch, msg, actions) | |
| if r.status_code >= 400: | |
| # Whatever the existence check said, the commit disagreed: flip every | |
| # verb and try once more, then file by file so that one unwritable | |
| # path cannot discard the others. | |
| flipped = [dict(a, action=("create" if a["action"] == "update" else "update")) | |
| for a in actions] | |
| r = _commit(base, pid, token, branch, msg, flipped) | |
| if r.status_code >= 400 and len(actions) > 1: | |
| return _commit_one_by_one(base, pid, token, branch, msg, actions, verbose) | |
| ok = r.status_code < 400 | |
| if verbose: | |
| print(f"[gitlab] branch={branch} status={r.status_code} {r.text[:300]}") | |
| if not ok: | |
| # Loud whether or not the caller asked. push_current_data calls this | |
| # without verbose and ignores the return value -- by design, since a | |
| # save hiccup must never interrupt a participant -- so a silent False | |
| # was the only trace that a session's data had not been saved. | |
| _loud(f"push FAILED: host={base.split('//')[-1].split('/')[0]} " | |
| f"project={project} branch={branch} status={r.status_code} " | |
| f"{r.text[:200]}") | |
| return ok | |