princessamygdala
Claude Opus 4.8 (1M context)
Scaffold ReactorRoom: observational-learning-of-empathy NiceWebRL task
63879a2 Download gitlab_save.py from princessamygdala/ReactorRoom: direct link, hf CLI and curl.
- Browser
- Download file 5.32 kB
-
https://huggingface.co/spaces/princessamygdala/ReactorRoom/resolve/main/gitlab_save.py
- Command line
-
hf download hf://spaces/princessamygdala/ReactorRoom/gitlab_save.py
-
curl -L -o gitlab_save.py https://huggingface.co/spaces/princessamygdala/ReactorRoom/resolve/main/gitlab_save.py
5.32 kB
| """ | |
| Push a participant's data files to a GitLab repo (e.g. gitlab.pavlovia.org) 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.pavlovia.org" | |
| 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 | |
| def _env(): | |
| return (os.getenv("GITLAB_TOKEN", "").strip(), | |
| os.getenv("GITLAB_PROJECT", "").strip(), | |
| os.getenv("GITLAB_URL", "https://gitlab.pavlovia.org").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 append_to_log(row, path="randomization_log.csv"): | |
| """Append one row to a growing CSV in the repo (read-modify-write). One row per pid.""" | |
| token, project, base, branch = _env() | |
| if not token or not project or requests is None: | |
| return False | |
| pid_id = quote(project, safe="") | |
| branch = branch or _default_branch(base, pid_id, token) or "main" | |
| existing = _get_raw(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("pid")) == str(row.get("pid")) for r in rdr): | |
| return True # already logged this participant | |
| rows = rdr + [row] | |
| action = "update" | |
| else: | |
| cols = list(row.keys()) | |
| rows = [row] | |
| 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}) | |
| content = base64.b64encode(buf.getvalue().encode()).decode("ascii") | |
| r = _commit(base, pid_id, token, branch, "randomization log", | |
| [{"action": action, "file_path": path, "content": content, "encoding": "base64"}]) | |
| return r.status_code < 400 | |
| 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 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", "https://gitlab.pavlovia.org").strip().rstrip("/") | |
| if not token or not project or requests is None: | |
| if verbose: | |
| print("[gitlab] missing GITLAB_TOKEN / GITLAB_PROJECT (or requests) -> skipping") | |
| 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) | |
| actions.append({ | |
| "action": "create", | |
| "file_path": f"{subdir}/{dest_name}", | |
| "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: | |
| # files may already exist (e.g. a re-run) -> retry as updates | |
| for a in actions: | |
| a["action"] = "update" | |
| r = _commit(base, pid, token, branch, msg, actions) | |
| if verbose: | |
| print(f"[gitlab] branch={branch} status={r.status_code} {r.text[:300]}") | |
| return r.status_code < 400 | |