greenaihack 0.0.1__tar.gz → 0.0.3__tar.gz

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,15 @@
1
+ Metadata-Version: 2.3
2
+ Name: greenaihack
3
+ Version: 0.0.3
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
+ # Green AI Hack
14
+
15
+ Command-line tool for participants in the [Green AI Hack](https://greenaihack.org).
@@ -0,0 +1,3 @@
1
+ # Green AI Hack
2
+
3
+ Command-line tool for participants in the [Green AI Hack](https://greenaihack.org).
@@ -4,9 +4,9 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "greenaihack"
7
- version = "0.0.1"
7
+ version = "0.0.3"
8
8
  description = "Student CLI for Green AI Hack"
9
- readme = "README.md"
9
+ readme = "PYPI.md"
10
10
  requires-python = ">=3.12"
11
11
  dependencies = [
12
12
  "cryptography>=44",
@@ -4,9 +4,9 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "greenaihack"
7
- version = "0.0.1"
7
+ version = "0.0.3"
8
8
  description = "Student CLI for Green AI Hack"
9
- readme = "README.md"
9
+ readme = "PYPI.md" # Public PyPI page. README.md is for contributors and is not published.
10
10
  requires-python = ">=3.12"
11
11
  dependencies = [
12
12
  "cryptography>=44",
@@ -23,6 +23,8 @@ from .project import (
23
23
  setup_changes,
24
24
  )
25
25
  from .ui import (
26
+ COMMAND,
27
+ badge,
26
28
  choose,
27
29
  confirm,
28
30
  done,
@@ -30,9 +32,15 @@ from .ui import (
30
32
  dry_run_notice,
31
33
  error,
32
34
  info,
35
+ job_logs,
36
+ next_steps,
37
+ note,
33
38
  prompt,
34
39
  require_terminal,
40
+ status_panel,
41
+ step,
35
42
  success,
43
+ use_stderr,
36
44
  warn,
37
45
  welcome,
38
46
  working,
@@ -173,8 +181,8 @@ def preview(root, register, team):
173
181
  else "offer to commit these files (no collaboration remote found)"
174
182
  )
175
183
  info("\n[bold]Without --dry-run, this would:[/]")
176
- for step in steps:
177
- info(f" • {markup(step)}")
184
+ for planned in steps:
185
+ info(f" • {markup(planned)}")
178
186
 
179
187
 
180
188
  def connect(command, api_override, dry_run=False):
@@ -204,7 +212,9 @@ def connect(command, api_override, dry_run=False):
204
212
  return 0
205
213
  name = f"[bold]{markup(team['name'])}[/]"
206
214
  success(f"Team {name} is registered" if register else f"Signed in to team {name}")
207
- with working("Setting up this machine…"):
215
+ with step(
216
+ "Setting up this machine…", "Configured storage and the submission remote"
217
+ ):
208
218
  directory = machine_directory(root, api, team["id"])
209
219
  save_credentials(directory, api, result)
210
220
  private_path, public_key = identity(directory)
@@ -212,11 +222,11 @@ def connect(command, api_override, dry_run=False):
212
222
  "/device-keys", {"public_key": public_key}, token=result["session_token"]
213
223
  )
214
224
  written = configure(root, api, result, directory, private_path, register)
215
- success("Configured storage and the submission remote")
216
225
  pushed = True
217
226
  if register:
218
- with working("Locking Python dependencies (uv lock)…"):
227
+ with step("Locking Python dependencies (uv lock)…") as locking:
219
228
  locked = lock(root)
229
+ locking.done = "Locked Python dependencies" if locked else None
220
230
  if not locked:
221
231
  warn("uv lock failed; run uv lock and commit uv.lock before submitting")
222
232
  pushed = publish(root, written)
@@ -251,7 +261,13 @@ def options(
251
261
  ),
252
262
  ] = False,
253
263
  ):
254
- pass
264
+ import sys
265
+
266
+ # Windows pipes use the locale code page; never crash on a log character.
267
+ for stream in (sys.stdout, sys.stderr):
268
+ if hasattr(stream, "reconfigure"):
269
+ stream.reconfigure(errors="replace")
270
+ use_stderr(False)
255
271
 
256
272
 
257
273
  ApiUrl = Annotated[
@@ -262,6 +278,25 @@ ApiUrl = Annotated[
262
278
  ),
263
279
  ]
264
280
 
281
+ JsonOutput = Annotated[
282
+ bool,
283
+ typer.Option(
284
+ "--json",
285
+ help="Print the raw API response as JSON on stdout; progress goes to stderr.",
286
+ ),
287
+ ]
288
+
289
+ # Pipeline states after which an evaluation no longer changes.
290
+ FINISHED = {"success", "failed", "canceled", "skipped", "trigger_uncertain"}
291
+
292
+ SubmissionId = Annotated[
293
+ str | None,
294
+ typer.Argument(
295
+ help="Submission ID; defaults to the latest submission made on this machine",
296
+ show_default=False,
297
+ ),
298
+ ]
299
+
265
300
  DryRun = Annotated[
266
301
  bool,
267
302
  typer.Option(
@@ -308,79 +343,185 @@ def submit(
308
343
  "--name", help="Experiment name; generated automatically when omitted"
309
344
  ),
310
345
  ] = None,
346
+ json_output: JsonOutput = False,
311
347
  ):
312
348
  """Upload models and submit committed source for evaluation."""
313
349
  from .submission import submit as send
314
350
 
315
351
  if (no_model and model) or (resume and (script or model or name or no_model)):
316
- typer.echo(
317
- "Use --resume alone; --model and --no-model are mutually exclusive",
318
- err=True,
319
- )
352
+ error("Use --resume alone; --model and --no-model are mutually exclusive")
320
353
  raise typer.Exit(2)
321
- _submission_call(lambda: send(script, [] if no_model else model, name, resume))
354
+ use_stderr(json_output)
355
+ result = _submission_call(
356
+ lambda: send(script, [] if no_model else model, name, resume),
357
+ failure="Submission failed; check local configuration",
358
+ interrupted=(
359
+ "Interrupted. If a submission ID is shown above, resume with "
360
+ f"{COMMAND} submit --resume ID"
361
+ ),
362
+ )
363
+ if json_output:
364
+ _print_json(result)
365
+ elif result.get("id"):
366
+ next_steps(result["id"], result.get("state"))
322
367
 
323
368
 
324
369
  @app.command()
325
370
  def status(
326
- submission_id: str,
371
+ submission_id: SubmissionId = None,
327
372
  wait: Annotated[
328
- bool, typer.Option("--wait", help="Poll until evaluation completes")
373
+ bool,
374
+ typer.Option(
375
+ "--wait",
376
+ help="Poll until evaluation completes; exit with code 1 unless it succeeds",
377
+ ),
329
378
  ] = False,
379
+ json_output: JsonOutput = False,
330
380
  ):
331
381
  """Retrieve current evaluation status."""
382
+ from .submission import saved_manifest
332
383
  from .submission import status as fetch
333
384
 
385
+ use_stderr(json_output)
386
+ submission_id = _resolve(submission_id)
387
+
334
388
  def poll():
335
389
  import time
336
390
 
337
- while True:
338
- value = fetch(submission_id)
339
- if not wait or value["state"] in {
340
- "success",
341
- "failed",
342
- "canceled",
343
- "skipped",
344
- "trigger_uncertain",
345
- }:
346
- return value
347
- typer.echo(f"Evaluation: {value['state']}")
348
- time.sleep(5)
349
-
350
- _submission_call(poll)
391
+ started = time.monotonic()
392
+ with working("Checking evaluation status…") as spinner:
393
+ while True:
394
+ value = fetch(submission_id)
395
+ # Read the fields here so a partial response is a handled error.
396
+ value["id"], value["state"]
397
+ if not wait or value["state"] in FINISHED:
398
+ return value
399
+ # Poll every 5 seconds; refresh the elapsed time every second.
400
+ for _ in range(5):
401
+ elapsed = _duration(time.monotonic() - started)
402
+ spinner.update(
403
+ f"Waiting for the evaluation: {badge(value['state'])} "
404
+ f"[dim]· {elapsed} elapsed[/]"
405
+ )
406
+ time.sleep(1)
407
+
408
+ value = _submission_call(
409
+ poll,
410
+ failure="Could not retrieve the status; check local configuration",
411
+ interrupted=(
412
+ "Stopped waiting; the evaluation keeps running. Check again with "
413
+ f"{COMMAND} status {submission_id}"
414
+ if wait
415
+ else "Interrupted"
416
+ ),
417
+ )
418
+ if json_output:
419
+ _print_json(value)
420
+ else:
421
+ status_panel(value, saved_manifest(submission_id))
422
+ next_steps(value["id"], value["state"])
423
+ if wait and value["state"] != "success":
424
+ raise typer.Exit(1)
351
425
 
352
426
 
353
427
  @app.command()
354
- def logs(submission_id: str):
428
+ def logs(
429
+ submission_id: SubmissionId = None,
430
+ job: Annotated[
431
+ str | None, typer.Option("--job", help="Show only the job with this name")
432
+ ] = None,
433
+ ):
355
434
  """Retrieve completed evaluation logs."""
356
435
  from .submission import status as fetch
357
436
 
358
- _submission_call(lambda: fetch(submission_id, logs=True))
437
+ submission_id = _resolve(submission_id)
438
+ jobs = _submission_call(
439
+ lambda: [
440
+ {"name": entry["name"], "status": entry["status"], "log": entry["log"]}
441
+ for entry in fetch(submission_id, logs=True)["jobs"]
442
+ ],
443
+ failure="Could not retrieve the logs; check local configuration",
444
+ loading="Fetching logs…",
445
+ )
446
+ if job is not None:
447
+ names = [entry["name"] for entry in jobs]
448
+ jobs = [entry for entry in jobs if entry["name"] == job]
449
+ if not jobs:
450
+ error(f"No job named {job}; available: {', '.join(names) or 'none'}")
451
+ raise typer.Exit(2)
452
+ job_logs(jobs)
359
453
 
360
454
 
361
455
  @app.command()
362
- def results(submission_id: str):
456
+ def results(submission_id: SubmissionId = None):
363
457
  """Retrieve inference predictions (unscored)."""
364
458
  from .submission import status as fetch
365
459
 
366
- _submission_call(lambda: fetch(submission_id, results=True))
460
+ use_stderr() # stdout holds only the predictions JSON.
461
+ submission_id = _resolve(submission_id)
462
+ _print_json(
463
+ _submission_call(
464
+ lambda: fetch(submission_id, results=True),
465
+ failure="Could not retrieve the results; check local configuration",
466
+ loading="Fetching predictions…",
467
+ )
468
+ )
469
+
470
+
471
+ def _resolve(submission_id):
472
+ """Default to this machine's latest submission, saying which one it is."""
473
+ if submission_id:
474
+ return submission_id
475
+ from .submission import latest
476
+
477
+ manifest, created = _submission_call(
478
+ latest, failure="Could not read local submissions; pass a submission ID"
479
+ )
480
+ import time
481
+
482
+ note(
483
+ "[dim]Latest submission from this machine:[/] "
484
+ f"[bold]{markup(manifest['name'])}[/] "
485
+ f"[dim]({_ago(time.time() - created)}, {markup(manifest['id'])})[/]"
486
+ )
487
+ return manifest["id"]
488
+
489
+
490
+ def _ago(seconds):
491
+ minutes = int(seconds // 60)
492
+ if minutes < 1:
493
+ return "just now"
494
+ if minutes < 60:
495
+ return f"{minutes} min ago"
496
+ hours = minutes // 60
497
+ return f"{hours} h ago" if hours < 24 else f"{hours // 24} d ago"
367
498
 
368
499
 
369
- def _submission_call(action):
500
+ def _duration(seconds):
501
+ minutes, seconds = divmod(int(seconds), 60)
502
+ return f"{minutes}m {seconds:02d}s" if minutes else f"{seconds}s"
503
+
504
+
505
+ def _print_json(value):
370
506
  import json
371
507
 
508
+ typer.echo(json.dumps(value, indent=2))
509
+
510
+
511
+ def _submission_call(action, failure, interrupted="Interrupted", loading=None):
372
512
  try:
373
- typer.echo(json.dumps(action(), indent=2))
513
+ if loading:
514
+ with working(loading):
515
+ return action()
516
+ return action()
374
517
  except KeyboardInterrupt:
375
- typer.echo("Interrupted; reconnect with status SUBMISSION_ID", err=True)
518
+ warn(interrupted)
376
519
  raise typer.Exit(130) from None
377
- except (SetupError, OSError, ValueError, KeyError, TypeError) as exc:
378
- typer.echo(
379
- str(exc)
380
- if isinstance(exc, SetupError)
381
- else "Submission failed; check local configuration",
382
- err=True,
383
- )
520
+ except SetupError as exc:
521
+ error(str(exc))
522
+ raise typer.Exit(2) from None
523
+ except (OSError, ValueError, KeyError, TypeError):
524
+ error(failure)
384
525
  raise typer.Exit(2) from None
385
526
 
386
527
 
@@ -86,6 +86,24 @@ GITIGNORE = [
86
86
  "/.dvc/tmp/",
87
87
  "/.venv/",
88
88
  "__pycache__/",
89
+ ".ipynb_checkpoints/",
90
+ ".DS_Store",
91
+ # Outputs of local runs.
92
+ "/predictions.json",
93
+ "emissions.csv",
94
+ # Model weights travel through DVC, never Git.
95
+ "*.bin",
96
+ "*.safetensors",
97
+ "*.pt",
98
+ "*.pth",
99
+ "*.ckpt",
100
+ "*.onnx",
101
+ "*.gguf",
102
+ "*.h5",
103
+ "*.keras",
104
+ "*.tflite",
105
+ "*.pkl",
106
+ "*.joblib",
89
107
  ]
90
108
  DVC_GITIGNORE = ["/config.local", "/cache", "/tmp"]
91
109