Spaces:
Sleeping
Sleeping
Download gitlab_save.py from princessamygdala/CityWalk: direct link, hf CLI and curl.
- Browser
- Download file 5.95 kB
-
https://huggingface.co/spaces/princessamygdala/CityWalk/resolve/main/gitlab_save.py
- Command line
-
hf download hf://spaces/princessamygdala/CityWalk/gitlab_save.py
-
curl -L -o gitlab_save.py https://huggingface.co/spaces/princessamygdala/CityWalk/resolve/main/gitlab_save.py
5.95 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"): | |
| """Upsert one participant row in a growing CSV in the repo (read-modify-write). | |
| One row per pid: a new pid is appended; an existing pid is UPDATED in place (so the | |
| latest progress/completion is reflected). Skips the commit when nothing changed. | |
| """ | |
| 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 [] | |
| for k in row: # add any new columns, preserving order | |
| if k not in cols: | |
| cols.append(k) | |
| idx = next( | |
| (i for i, r in enumerate(rdr) if str(r.get("pid")) == str(row.get("pid"))), | |
| None, | |
| ) | |
| if idx is not None: # update this participant's row in place | |
| merged = {**rdr[idx], **row} | |
| if all(str(rdr[idx].get(k, "")) == str(merged.get(k, "")) for k in cols): | |
| return True # nothing changed -> no commit needed | |
| rdr[idx] = merged | |
| else: | |
| rdr.append(row) | |
| rows = rdr | |
| 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): | |
| """Commit the given local files into <repo>/<subdir>/. Returns True on success.""" | |
| # .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") | |
| actions.append( | |
| { | |
| "action": "create", | |
| "file_path": f"{subdir}/{os.path.basename(fp)}", | |
| "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 | |