greenaihack 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,260 @@
1
+ """Build durable isolated submissions without changing the student's checkout."""
2
+
3
+ import json
4
+ import shutil
5
+ import subprocess
6
+ from pathlib import Path, PurePosixPath
7
+ from uuid import uuid4
8
+
9
+ from . import __version__
10
+ from .client import Client
11
+ from .local import SetupError, atomic_write, machine_directory, repository, run
12
+ from .project import append_lines, load
13
+
14
+
15
+ def command(args, cwd):
16
+ try:
17
+ completed = subprocess.run(
18
+ args, cwd=cwd, capture_output=True, timeout=1800, check=False
19
+ )
20
+ except (OSError, subprocess.TimeoutExpired):
21
+ raise SetupError(f"{args[0]} could not complete; retry with --resume") from None
22
+ if completed.returncode:
23
+ raise SetupError(
24
+ f"{args[0]} {args[1]} failed; check credentials, connectivity and project configuration"
25
+ )
26
+ return completed.stdout.decode("utf-8", errors="replace").strip()
27
+
28
+
29
+ def context():
30
+ root = repository()
31
+ shared = load(root)
32
+ if not shared:
33
+ raise SetupError("Register or log in before submitting")
34
+ directory = machine_directory(root, shared["api_url"], shared["team_id"])
35
+ try:
36
+ session = json.loads((directory / "session.json").read_text())
37
+ except (OSError, ValueError):
38
+ raise SetupError("Log in on this machine before submitting") from None
39
+ return root, shared, directory, Client(shared["api_url"]), session["session_token"]
40
+
41
+
42
+ def relative(root, value):
43
+ root = root.resolve()
44
+ path = Path(value)
45
+ if path.is_absolute() or any(c in value for c in ("\\", "\n", "\r", "\x00")):
46
+ raise SetupError("Use repository-relative paths with forward slashes")
47
+ parts = PurePosixPath(value).parts
48
+ if not parts or any(p in {".", "..", ".git", ".dvc"} for p in parts):
49
+ raise SetupError("Invalid submission path")
50
+ current = root
51
+ for part in parts:
52
+ current = current / part
53
+ if current.is_symlink():
54
+ raise SetupError("Submission paths must not contain symlinks")
55
+ if not current.exists() or not current.resolve().is_relative_to(root):
56
+ raise SetupError(f"Missing submission path: {value}")
57
+ if current.is_dir() and any(p.is_symlink() for p in current.rglob("*")):
58
+ raise SetupError("Model directories must not contain symlinks")
59
+ return PurePosixPath(*parts).as_posix()
60
+
61
+
62
+ def submit(script=None, models=None, name=None, resume=None):
63
+ root, shared, directory, client, token = context()
64
+ if resume:
65
+ from uuid import UUID
66
+
67
+ identifier = str(UUID(resume))
68
+ bundle = directory / "submissions" / identifier
69
+ if not (bundle / "request.json").exists():
70
+ raise SetupError("No completed local submission bundle exists for this ID")
71
+ else:
72
+ defaults = shared.get("defaults", {})
73
+ script = script or defaults.get("script")
74
+ if not script:
75
+ raise SetupError("Provide --script or configure defaults.script")
76
+ script = relative(root, script)
77
+ models = [
78
+ relative(root, m)
79
+ for m in (models if models is not None else defaults.get("models", []))
80
+ ]
81
+ for i, model in enumerate(models):
82
+ if any(
83
+ model == other
84
+ or model.startswith(other + "/")
85
+ or other.startswith(model + "/")
86
+ for other in models[:i]
87
+ ):
88
+ raise SetupError("Selected models must not overlap")
89
+ if script == model or script.startswith(model + "/"):
90
+ raise SetupError("Script cannot be inside a selected model")
91
+ # Tracked changes are always source changes, including tracked weights.
92
+ if run(["git", "diff", "HEAD", "--name-only"], cwd=root):
93
+ raise SetupError("Commit tracked changes before submitting")
94
+ untracked = run(
95
+ [
96
+ "git",
97
+ "-c",
98
+ "core.quotepath=false",
99
+ "ls-files",
100
+ "--others",
101
+ "--exclude-standard",
102
+ ],
103
+ cwd=root,
104
+ ).splitlines()
105
+ if any(
106
+ not any(p == m or p.startswith(m + "/") for m in models) for p in untracked
107
+ ):
108
+ raise SetupError(
109
+ "Commit or ignore untracked source files before submitting"
110
+ )
111
+ tracked = set(
112
+ run(
113
+ ["git", "-c", "core.quotepath=false", "ls-files"], cwd=root
114
+ ).splitlines()
115
+ )
116
+ if script not in tracked or not {"pyproject.toml", "uv.lock"}.issubset(tracked):
117
+ raise SetupError(
118
+ "Commit the script, pyproject.toml and uv.lock before submitting"
119
+ )
120
+ if any(p == m or p.startswith(m + "/") for m in models for p in tracked):
121
+ raise SetupError(
122
+ "Selected weights must be outside Git tracking; use DVC for model files"
123
+ )
124
+ if "greenaihack-submission.json" in tracked or ".dvc/config.local" in tracked:
125
+ raise SetupError(
126
+ "Submission manifest and local DVC config must not be tracked"
127
+ )
128
+ for path in tracked:
129
+ if not (root / path).is_file() or (root / path).is_symlink():
130
+ raise SetupError("Tracked symlinks and submodules are unsupported")
131
+ identifier = str(uuid4())
132
+ bundle = directory / "submissions" / identifier
133
+ bundle.mkdir(parents=True)
134
+ workspace = bundle / "workspace"
135
+ command(
136
+ [
137
+ "git",
138
+ "clone",
139
+ "--no-hardlinks",
140
+ "--no-checkout",
141
+ str(root),
142
+ str(workspace),
143
+ ],
144
+ root,
145
+ )
146
+ source = run(["git", "rev-parse", "HEAD"], cwd=root)
147
+ command(["git", "checkout", "--detach", source], workspace)
148
+ for model in models:
149
+ target = workspace / model
150
+ target.parent.mkdir(parents=True, exist_ok=True)
151
+ if (root / model).is_dir():
152
+ shutil.copytree(root / model, target)
153
+ else:
154
+ shutil.copy2(root / model, target)
155
+ manifest = {
156
+ "schema_version": 1,
157
+ "id": identifier,
158
+ "source_commit": source,
159
+ "script": script,
160
+ "models": models,
161
+ "client_version": __version__,
162
+ "name": name or "experiment-" + identifier[:8],
163
+ }
164
+ atomic_write(
165
+ workspace / "greenaihack-submission.json",
166
+ json.dumps(manifest, indent=2) + "\n",
167
+ )
168
+ atomic_write(bundle / "manifest.json", json.dumps(manifest))
169
+ # Save before network operations so upload/push/API failures are recoverable.
170
+ atomic_write(
171
+ bundle / "request.json",
172
+ json.dumps({"id": identifier, "manifest": manifest}),
173
+ )
174
+ import typer
175
+
176
+ typer.echo(f"Submission {identifier}; retry with submit --resume {identifier}")
177
+ workspace = bundle / "workspace"
178
+ payload = json.loads((bundle / "request.json").read_text())
179
+ manifest = payload["manifest"]
180
+ if "commit" not in payload and command(
181
+ ["git", "ls-tree", "--name-only", "HEAD", "--", "greenaihack-submission.json"],
182
+ workspace,
183
+ ):
184
+ payload["commit"] = command(["git", "rev-parse", "HEAD"], workspace)
185
+ atomic_write(bundle / "request.json", json.dumps(payload))
186
+ if "commit" not in payload:
187
+ local = root / ".dvc" / "config.local"
188
+ if local.exists():
189
+ shutil.copy2(local, workspace / ".dvc" / "config.local")
190
+ dvc = [
191
+ "uv",
192
+ "tool",
193
+ "run",
194
+ "--python",
195
+ "3.12",
196
+ "--from",
197
+ "dvc[s3]==3.67.1",
198
+ "dvc",
199
+ ]
200
+ exceptions = []
201
+ for model in manifest["models"]:
202
+ parent = PurePosixPath(model).parent
203
+ for directory in reversed([parent, *parent.parents]):
204
+ if str(directory) != ".":
205
+ exceptions.append("!/" + directory.as_posix() + "/")
206
+ exceptions.append("!/" + model + ".dvc")
207
+ if exceptions:
208
+ append_lines(workspace / ".gitignore", exceptions)
209
+ for model in manifest["models"]:
210
+ command(dvc + ["add", "--", model], workspace)
211
+ if manifest["models"]:
212
+ command(
213
+ dvc + ["push", "-r", shared.get("dvc_remote", "greenaihack")], workspace
214
+ )
215
+ (workspace / ".dvc" / "config.local").unlink(missing_ok=True)
216
+ command(["git", "add", "--all"], workspace)
217
+ command(
218
+ [
219
+ "git",
220
+ "-c",
221
+ "user.name=Green AI Hack",
222
+ "-c",
223
+ "user.email=submissions@greenaihack.invalid",
224
+ "commit",
225
+ "-m",
226
+ "feat: prepare submission " + identifier,
227
+ ],
228
+ workspace,
229
+ )
230
+ payload["commit"] = command(["git", "rev-parse", "HEAD"], workspace)
231
+ atomic_write(bundle / "request.json", json.dumps(payload))
232
+ remote = run(
233
+ ["git", "remote", "get-url", shared.get("submission_remote", "greenaihack")],
234
+ cwd=root,
235
+ )
236
+ command(
237
+ [
238
+ "git",
239
+ "push",
240
+ remote,
241
+ payload["commit"] + ":refs/heads/submissions/" + identifier,
242
+ ],
243
+ workspace,
244
+ )
245
+ return client.request("/submissions", payload, token=token)
246
+
247
+
248
+ def status(identifier, logs=False, results=False):
249
+ from uuid import UUID
250
+
251
+ identifier = str(UUID(identifier))
252
+ _, _, _, client, token = context()
253
+ return client.request(
254
+ "/submissions/"
255
+ + identifier
256
+ + ("/logs" if logs else "/results" if results else ""),
257
+ None,
258
+ token=token,
259
+ method="GET",
260
+ )
greenaihack/ui.py ADDED
@@ -0,0 +1,179 @@
1
+ """Interactive prompts and friendly terminal output for register and login."""
2
+
3
+ import sys
4
+ from contextlib import contextmanager
5
+
6
+ import typer
7
+ from rich.console import Console
8
+ from rich.markup import escape
9
+ from rich.panel import Panel
10
+ from rich.table import Table
11
+
12
+ from .local import SetupError
13
+
14
+ GREEN = "#2e9d5b"
15
+ DOCS_URL = "https://docs.greenaihack.org/"
16
+
17
+ console = Console(highlight=False)
18
+ errors = Console(stderr=True, highlight=False)
19
+
20
+
21
+ def require_terminal():
22
+ if not sys.stdin.isatty():
23
+ raise SetupError("Registration and login require an interactive terminal")
24
+
25
+
26
+ @contextmanager
27
+ def _interruptible():
28
+ # Typer turns Ctrl-C/EOF into Abort; keep the CLI's interrupt handling.
29
+ try:
30
+ yield
31
+ except typer.Abort:
32
+ raise KeyboardInterrupt from None
33
+
34
+
35
+ def _ask(label, **options):
36
+ with _interruptible():
37
+ return typer.prompt(typer.style(label, bold=True), **options)
38
+
39
+
40
+ def prompt(label, secret=False, validate=None):
41
+ """Ask until the answer is non-empty and validate (if any) returns None."""
42
+ require_terminal()
43
+ while True:
44
+ value = _ask(label, hide_input=secret)
45
+ value = value if secret else value.strip()
46
+ problem = f"{label} is required" if not value else validate and validate(value)
47
+ if not problem:
48
+ return value
49
+ warn(problem)
50
+
51
+
52
+ def choose(items, label):
53
+ """Show a numbered list and return the index of the selected item."""
54
+ require_terminal()
55
+ console.print(f"[bold]Select your {label.lower()}:[/]")
56
+ for index, item in enumerate(items, 1):
57
+ console.print(f" [bold {GREEN}]{index}[/] {escape(item)}")
58
+ while True:
59
+ choice = _ask(f"{label} number", default="1").strip()
60
+ if choice.isdigit() and 1 <= int(choice) <= len(items):
61
+ return int(choice) - 1
62
+ warn(f"Enter a number between 1 and {len(items)}")
63
+
64
+
65
+ def confirm(label, default=True):
66
+ require_terminal()
67
+ with _interruptible():
68
+ return typer.confirm(typer.style(label, bold=True), default=default)
69
+
70
+
71
+ def welcome(command):
72
+ if command == "register":
73
+ body = (
74
+ "Let's register your team and prepare this repository.\n\n"
75
+ "You will need:\n"
76
+ " • the [bold]event secret[/] from the organizers\n"
77
+ " • a [bold]team name[/]\n"
78
+ " • a [bold]team password[/] (12+ characters) to share with teammates"
79
+ )
80
+ else:
81
+ body = (
82
+ "Let's connect this machine to your team.\n\n"
83
+ "Ask your captain for the [bold]team password[/]."
84
+ )
85
+ console.print()
86
+ console.print(
87
+ Panel(
88
+ body,
89
+ title=f"[bold {GREEN}]Welcome to Green AI Hack![/]",
90
+ border_style=GREEN,
91
+ expand=False,
92
+ )
93
+ )
94
+ console.print()
95
+
96
+
97
+ def dry_run_notice():
98
+ console.print(
99
+ Panel(
100
+ "Nothing is sent to the API and nothing on this machine or in this\n"
101
+ "repository is changed. API answers are sample data.",
102
+ title="[bold yellow]Dry run[/]",
103
+ border_style="yellow",
104
+ expand=False,
105
+ )
106
+ )
107
+ console.print()
108
+
109
+
110
+ def info(message):
111
+ console.print(message)
112
+
113
+
114
+ def success(message):
115
+ console.print(f"[bold {GREEN}]✓[/] {message}")
116
+
117
+
118
+ def warn(message):
119
+ errors.print(f"[bold yellow]![/] {escape(message)}")
120
+
121
+
122
+ def error(message):
123
+ errors.print(f"[bold red]✗ Error:[/] {escape(message)}")
124
+
125
+
126
+ @contextmanager
127
+ def working(message):
128
+ with console.status(message, spinner="dots", spinner_style=GREEN):
129
+ yield
130
+
131
+
132
+ def _summary(title, team_name, event_id):
133
+ details = Table.grid(padding=(0, 2))
134
+ details.add_row("[dim]Team[/]", f"[bold]{escape(team_name)}[/]")
135
+ details.add_row("[dim]Event[/]", escape(event_id))
136
+ console.print()
137
+ console.print(
138
+ Panel(
139
+ details,
140
+ title=f"[bold {GREEN}]{title}[/]",
141
+ border_style=GREEN,
142
+ expand=False,
143
+ )
144
+ )
145
+
146
+
147
+ def dry_run_done(team_name, event_id):
148
+ _summary("Dry run complete", team_name, event_id)
149
+ console.print(
150
+ "\nRun the same command without [bold]--dry-run[/] to do it for real.\n"
151
+ )
152
+
153
+
154
+ def done(command, team_name, event_id, pushed):
155
+ register = command == "register"
156
+ title = "Your team is registered!" if register else "You're all set!"
157
+ _summary(title, team_name, event_id)
158
+ steps = []
159
+ if register and not pushed:
160
+ steps.append(
161
+ "Commit and push the new setup files to your collaboration repository."
162
+ )
163
+ if register:
164
+ steps.append(
165
+ "Teammates clone the repository and run "
166
+ "[bold]uvx greenaihack@latest login[/]."
167
+ )
168
+ steps.append(
169
+ "Edit [bold]my_eval.py[/], commit, then run "
170
+ "[bold]uvx greenaihack@latest submit[/]."
171
+ )
172
+ console.print("\n[bold]Next steps[/]")
173
+ for index, step in enumerate(steps, 1):
174
+ console.print(f" {index}. {step}")
175
+ console.print(f"\nParticipant guide: [link={DOCS_URL}]{DOCS_URL}[/link]")
176
+ console.print(
177
+ "[dim]Credentials and the SSH key are stored outside the repository.[/]"
178
+ )
179
+ console.print(f"\n[bold {GREEN}]Happy hacking![/]\n")
@@ -0,0 +1,45 @@
1
+ Metadata-Version: 2.3
2
+ Name: greenaihack
3
+ Version: 0.0.1
4
+ Summary: Student CLI for Green AI Hack
5
+ Requires-Dist: cryptography>=44
6
+ Requires-Dist: httpx>=0.28.1
7
+ Requires-Dist: platformdirs>=4.14.5
8
+ Requires-Dist: rich>=13
9
+ Requires-Dist: typer>=0.16,<1
10
+ Requires-Python: >=3.12
11
+ Description-Content-Type: text/markdown
12
+
13
+ # greenaihack
14
+
15
+ Cross-platform CLI for registering a Green AI Hack team and connecting teammates
16
+ to its GitLab submission project and Scaleway/DVC storage. No student GitLab
17
+ account is required. Submission supports DVC model uploads, isolated GitLab branches and API-triggered
18
+ evaluation. See [runner setup and inference contract](../infra/runner/README.md).
19
+
20
+ ```bash
21
+ uvx greenaihack@latest register
22
+ uvx greenaihack@latest login
23
+ ```
24
+
25
+ Run in the team's existing Git repository. Registration uses `https://api.greenaihack.org` by default.
26
+ It lists the open events to pick from, then prompts for the event secret, team
27
+ name and password. It then lists the shared configuration and starter files it
28
+ created and offers to commit only those and push them to the current branch on
29
+ the collaboration remote (never to the `greenaihack` submission remote).
30
+ Teammates clone that repository and log in with the team password. The CLI
31
+ keeps credentials outside tracked files and preserves the collaboration remote.
32
+ Git and OpenSSH must be available; no separate DVC installation is required.
33
+
34
+ Add `--dry-run` to `register` or `login` to try them: they prompt as usual but
35
+ answer API calls with sample data and change no files, credentials, remotes or
36
+ commits.
37
+
38
+ Use `GREENAIHACK_API_URL` or `--api-url` to override the API address. Secrets are
39
+ entered interactively without echo; they are not command-line flags. Read the
40
+ root README for credential locations, retry behavior and the shared file list.
41
+
42
+ Use `@latest` to check for updates on every invocation. Bare `uvx greenaihack`
43
+ may reuse a cached version. This package is not yet published.
44
+
45
+ For development: `uv run --package greenaihack greenaihack --help`.
@@ -0,0 +1,12 @@
1
+ greenaihack/__init__.py,sha256=EUxYpXDdLWl934QUacPubsaNcjoAFSEDVKyMZ77TKyw,172
2
+ greenaihack/cli.py,sha256=f8GjhFpTxGeAqF3vMHBO3r6fgM7wOI9cWPDT_7Xj5so,12486
3
+ greenaihack/client.py,sha256=45jfb3goH89bECRxXtq72VfNQFmdNoWxnexMLjCfWDc,4103
4
+ greenaihack/dryrun.py,sha256=tEa-s35Ytn9W5_OvMAhohR4ohRwS7aHji1VsrHrUZxU,2113
5
+ greenaihack/local.py,sha256=_JlnrGjVYoEqY0mBQBF25FPDFYNWRHZVR72vBdizP1c,6523
6
+ greenaihack/project.py,sha256=4wZjNhC5DfcPcMYX8ul9wI5ckiAaflk7FycKr-0cstA,11886
7
+ greenaihack/submission.py,sha256=Vj5i7UvP-TfpcQQ4bD0GGQ_rehIuVHuu2lUdtvK203I,9801
8
+ greenaihack/ui.py,sha256=9llK4IgPqCQgPSA4AahCQe_RYdZXegthQbiDtNSvblM,5197
9
+ greenaihack-0.0.1.dist-info/WHEEL,sha256=G_-rrEibZr7OEM7zdH1dSO6s-VdjfnS5PA4CLAdI9Vw,80
10
+ greenaihack-0.0.1.dist-info/entry_points.txt,sha256=Bxxao-zWZ_-2z2TaZnpQ2nwijOfRHSPwNRg7G4iT7FM,53
11
+ greenaihack-0.0.1.dist-info/METADATA,sha256=vER6b6qZoFgwopoVYDulahKpxrZTqJsEmrtdE4KLBWY,2008
12
+ greenaihack-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.9
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ greenaihack = greenaihack.cli:app
3
+