greenaihack 0.0.2__tar.gz → 0.0.4__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: greenaihack
3
- Version: 0.0.2
3
+ Version: 0.0.4
4
4
  Summary: Student CLI for Green AI Hack
5
5
  Requires-Dist: cryptography>=44
6
6
  Requires-Dist: httpx>=0.28.1
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "greenaihack"
7
- version = "0.0.2"
7
+ version = "0.0.4"
8
8
  description = "Student CLI for Green AI Hack"
9
9
  readme = "PYPI.md"
10
10
  requires-python = ">=3.12"
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "greenaihack"
7
- version = "0.0.2"
7
+ version = "0.0.4"
8
8
  description = "Student CLI for Green AI Hack"
9
9
  readme = "PYPI.md" # Public PyPI page. README.md is for contributors and is not published.
10
10
  requires-python = ">=3.12"
@@ -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,16 @@ 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
+ results_panel,
41
+ status_panel,
42
+ step,
35
43
  success,
44
+ use_stderr,
36
45
  warn,
37
46
  welcome,
38
47
  working,
@@ -173,8 +182,8 @@ def preview(root, register, team):
173
182
  else "offer to commit these files (no collaboration remote found)"
174
183
  )
175
184
  info("\n[bold]Without --dry-run, this would:[/]")
176
- for step in steps:
177
- info(f" • {markup(step)}")
185
+ for planned in steps:
186
+ info(f" • {markup(planned)}")
178
187
 
179
188
 
180
189
  def connect(command, api_override, dry_run=False):
@@ -204,7 +213,9 @@ def connect(command, api_override, dry_run=False):
204
213
  return 0
205
214
  name = f"[bold]{markup(team['name'])}[/]"
206
215
  success(f"Team {name} is registered" if register else f"Signed in to team {name}")
207
- with working("Setting up this machine…"):
216
+ with step(
217
+ "Setting up this machine…", "Configured storage and the submission remote"
218
+ ):
208
219
  directory = machine_directory(root, api, team["id"])
209
220
  save_credentials(directory, api, result)
210
221
  private_path, public_key = identity(directory)
@@ -212,11 +223,11 @@ def connect(command, api_override, dry_run=False):
212
223
  "/device-keys", {"public_key": public_key}, token=result["session_token"]
213
224
  )
214
225
  written = configure(root, api, result, directory, private_path, register)
215
- success("Configured storage and the submission remote")
216
226
  pushed = True
217
227
  if register:
218
- with working("Locking Python dependencies (uv lock)…"):
228
+ with step("Locking Python dependencies (uv lock)…") as locking:
219
229
  locked = lock(root)
230
+ locking.done = "Locked Python dependencies" if locked else None
220
231
  if not locked:
221
232
  warn("uv lock failed; run uv lock and commit uv.lock before submitting")
222
233
  pushed = publish(root, written)
@@ -251,7 +262,13 @@ def options(
251
262
  ),
252
263
  ] = False,
253
264
  ):
254
- pass
265
+ import sys
266
+
267
+ # Windows pipes use the locale code page; never crash on a log character.
268
+ for stream in (sys.stdout, sys.stderr):
269
+ if hasattr(stream, "reconfigure"):
270
+ stream.reconfigure(errors="replace")
271
+ use_stderr(False)
255
272
 
256
273
 
257
274
  ApiUrl = Annotated[
@@ -262,6 +279,25 @@ ApiUrl = Annotated[
262
279
  ),
263
280
  ]
264
281
 
282
+ JsonOutput = Annotated[
283
+ bool,
284
+ typer.Option(
285
+ "--json",
286
+ help="Print the raw API response as JSON on stdout; progress goes to stderr.",
287
+ ),
288
+ ]
289
+
290
+ # Pipeline states after which an evaluation no longer changes.
291
+ FINISHED = {"success", "failed", "canceled", "skipped", "trigger_uncertain"}
292
+
293
+ SubmissionId = Annotated[
294
+ str | None,
295
+ typer.Argument(
296
+ help="Submission ID; defaults to the latest submission made on this machine",
297
+ show_default=False,
298
+ ),
299
+ ]
300
+
265
301
  DryRun = Annotated[
266
302
  bool,
267
303
  typer.Option(
@@ -308,79 +344,198 @@ def submit(
308
344
  "--name", help="Experiment name; generated automatically when omitted"
309
345
  ),
310
346
  ] = None,
347
+ json_output: JsonOutput = False,
311
348
  ):
312
349
  """Upload models and submit committed source for evaluation."""
313
350
  from .submission import submit as send
314
351
 
315
352
  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
- )
353
+ error("Use --resume alone; --model and --no-model are mutually exclusive")
320
354
  raise typer.Exit(2)
321
- _submission_call(lambda: send(script, [] if no_model else model, name, resume))
355
+ use_stderr(json_output)
356
+ result = _submission_call(
357
+ lambda: send(script, [] if no_model else model, name, resume),
358
+ failure="Submission failed; check local configuration",
359
+ interrupted=(
360
+ "Interrupted. If a submission ID is shown above, resume with "
361
+ f"{COMMAND} submit --resume ID"
362
+ ),
363
+ )
364
+ if json_output:
365
+ _print_json(result)
366
+ elif result.get("id"):
367
+ next_steps(result["id"], result.get("state"))
322
368
 
323
369
 
324
370
  @app.command()
325
371
  def status(
326
- submission_id: str,
372
+ submission_id: SubmissionId = None,
327
373
  wait: Annotated[
328
- bool, typer.Option("--wait", help="Poll until evaluation completes")
374
+ bool,
375
+ typer.Option(
376
+ "--wait",
377
+ help="Poll until evaluation completes; exit with code 1 unless it succeeds",
378
+ ),
329
379
  ] = False,
380
+ json_output: JsonOutput = False,
330
381
  ):
331
382
  """Retrieve current evaluation status."""
383
+ from .submission import saved_manifest
332
384
  from .submission import status as fetch
333
385
 
386
+ use_stderr(json_output)
387
+ submission_id = _resolve(submission_id)
388
+
334
389
  def poll():
335
390
  import time
336
391
 
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)
392
+ started = time.monotonic()
393
+ with working("Checking evaluation status…") as spinner:
394
+ while True:
395
+ value = fetch(submission_id)
396
+ # Read the fields here so a partial response is a handled error.
397
+ value["id"], value["state"]
398
+ if not wait or value["state"] in FINISHED:
399
+ return value
400
+ # Poll every 5 seconds; refresh the elapsed time every second.
401
+ for _ in range(5):
402
+ elapsed = _duration(time.monotonic() - started)
403
+ spinner.update(
404
+ f"Waiting for the evaluation: {badge(value['state'])} "
405
+ f"[dim]· {elapsed} elapsed[/]"
406
+ )
407
+ time.sleep(1)
408
+
409
+ value = _submission_call(
410
+ poll,
411
+ failure="Could not retrieve the status; check local configuration",
412
+ interrupted=(
413
+ "Stopped waiting; the evaluation keeps running. Check again with "
414
+ f"{COMMAND} status {submission_id}"
415
+ if wait
416
+ else "Interrupted"
417
+ ),
418
+ )
419
+ if json_output:
420
+ _print_json(value)
421
+ else:
422
+ status_panel(value, saved_manifest(submission_id))
423
+ next_steps(value["id"], value["state"])
424
+ if wait and value["state"] != "success":
425
+ raise typer.Exit(1)
351
426
 
352
427
 
353
428
  @app.command()
354
- def logs(submission_id: str):
429
+ def logs(
430
+ submission_id: SubmissionId = None,
431
+ job: Annotated[
432
+ str | None, typer.Option("--job", help="Show only the job with this name")
433
+ ] = None,
434
+ ):
355
435
  """Retrieve completed evaluation logs."""
356
436
  from .submission import status as fetch
357
437
 
358
- _submission_call(lambda: fetch(submission_id, logs=True))
438
+ submission_id = _resolve(submission_id)
439
+ jobs = _submission_call(
440
+ lambda: [
441
+ {"name": entry["name"], "status": entry["status"], "log": entry["log"]}
442
+ for entry in fetch(submission_id, logs=True)["jobs"]
443
+ ],
444
+ failure="Could not retrieve the logs; check local configuration",
445
+ loading="Fetching logs…",
446
+ )
447
+ if job is not None:
448
+ names = [entry["name"] for entry in jobs]
449
+ jobs = [entry for entry in jobs if entry["name"] == job]
450
+ if not jobs:
451
+ error(f"No job named {job}; available: {', '.join(names) or 'none'}")
452
+ raise typer.Exit(2)
453
+ job_logs(jobs)
359
454
 
360
455
 
361
456
  @app.command()
362
- def results(submission_id: str):
363
- """Retrieve inference predictions (unscored)."""
457
+ def results(submission_id: SubmissionId = None, json_output: JsonOutput = False):
458
+ """Show accuracy and environmental impacts of a finished submission."""
459
+ from .submission import saved_manifest
364
460
  from .submission import status as fetch
365
461
 
366
- _submission_call(lambda: fetch(submission_id, results=True))
462
+ use_stderr(json_output)
463
+ submission_id = _resolve(submission_id)
464
+ response = _submission_call(
465
+ lambda: fetch(submission_id, results=True),
466
+ failure="Could not retrieve the results; check local configuration",
467
+ loading="Fetching results…",
468
+ )
469
+ value = response.get("results") if isinstance(response, dict) else None
470
+ if not isinstance(value, dict):
471
+ # Older servers returned raw predictions; never print them.
472
+ error(
473
+ "The Green AI Hack server is outdated and does not report accuracy "
474
+ "and impacts yet; ask the organizers"
475
+ if isinstance(response, dict) and "predictions" in response
476
+ else "The server returned unexpected results; ask the organizers"
477
+ )
478
+ raise typer.Exit(2)
479
+ if json_output:
480
+ _print_json(response)
481
+ else:
482
+ results_panel(value, saved_manifest(submission_id))
483
+
484
+
485
+ def _resolve(submission_id):
486
+ """Default to this machine's latest submission, saying which one it is."""
487
+ if submission_id:
488
+ return submission_id
489
+ from .submission import latest
367
490
 
491
+ manifest, created = _submission_call(
492
+ latest, failure="Could not read local submissions; pass a submission ID"
493
+ )
494
+ import time
495
+
496
+ note(
497
+ "[dim]Latest submission from this machine:[/] "
498
+ f"[bold]{markup(manifest['name'])}[/] "
499
+ f"[dim]({_ago(time.time() - created)}, {markup(manifest['id'])})[/]"
500
+ )
501
+ return manifest["id"]
368
502
 
369
- def _submission_call(action):
503
+
504
+ def _ago(seconds):
505
+ minutes = int(seconds // 60)
506
+ if minutes < 1:
507
+ return "just now"
508
+ if minutes < 60:
509
+ return f"{minutes} min ago"
510
+ hours = minutes // 60
511
+ return f"{hours} h ago" if hours < 24 else f"{hours // 24} d ago"
512
+
513
+
514
+ def _duration(seconds):
515
+ minutes, seconds = divmod(int(seconds), 60)
516
+ return f"{minutes}m {seconds:02d}s" if minutes else f"{seconds}s"
517
+
518
+
519
+ def _print_json(value):
370
520
  import json
371
521
 
522
+ typer.echo(json.dumps(value, indent=2))
523
+
524
+
525
+ def _submission_call(action, failure, interrupted="Interrupted", loading=None):
372
526
  try:
373
- typer.echo(json.dumps(action(), indent=2))
527
+ if loading:
528
+ with working(loading):
529
+ return action()
530
+ return action()
374
531
  except KeyboardInterrupt:
375
- typer.echo("Interrupted; reconnect with status SUBMISSION_ID", err=True)
532
+ warn(interrupted)
376
533
  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
- )
534
+ except SetupError as exc:
535
+ error(str(exc))
536
+ raise typer.Exit(2) from None
537
+ except (OSError, ValueError, KeyError, TypeError):
538
+ error(failure)
384
539
  raise typer.Exit(2) from None
385
540
 
386
541
 
@@ -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
 
@@ -129,13 +147,46 @@ def write_ini(path, parser):
129
147
  atomic_write(path, stream.getvalue())
130
148
 
131
149
 
150
+ EVAL_STARTER = '''"""Starter inference script: replace predict() with your model.
151
+
152
+ The evaluation sets GREENAIHACK_TEST_DATA to a CSV file with columns id,text.
153
+ Write predictions.json with one 0/1 prediction per row, in the same order.
154
+ """
155
+
156
+ import csv
157
+ import json
158
+ import os
159
+ import sys
160
+ from pathlib import Path
161
+
162
+ SAMPLE = Path("data/sample_inputs.csv")
163
+
164
+
165
+ def predict(text):
166
+ return 0 # Placeholder: replace with your model.
167
+
168
+
169
+ def main():
170
+ path = Path(os.environ.get("GREENAIHACK_TEST_DATA") or SAMPLE)
171
+ if not path.is_file():
172
+ sys.exit(
173
+ f"{path} not found: download the public sample to {SAMPLE} "
174
+ "(see the participant guide) or set GREENAIHACK_TEST_DATA."
175
+ )
176
+ with path.open(newline="", encoding="utf-8") as file:
177
+ predictions = [predict(row["text"]) for row in csv.DictReader(file)]
178
+ Path("predictions.json").write_text(json.dumps({"predictions": predictions}))
179
+
180
+
181
+ if __name__ == "__main__":
182
+ main()
183
+ '''
184
+
132
185
  STARTER = {
133
186
  "pyproject.toml": (
134
187
  '[project]\nname = "greenaihack-team"\nversion = "0.1.0"\nrequires-python = ">=3.12"\ndependencies = []\n\n[tool.uv]\npackage = false\n'
135
188
  ),
136
- "my_eval.py": (
137
- '"""Replace this public-sample inference fixture with your model."""\nimport json\nfrom pathlib import Path\n\ndef main():\n Path("predictions.json").write_text(json.dumps({"predictions": [0, 1, 0]}))\n\n\nif __name__ == "__main__":\n main()\n'
138
- ),
189
+ "my_eval.py": EVAL_STARTER,
139
190
  "models/.gitkeep": "",
140
191
  ".gitlab-ci.yml": (
141
192
  "# The submission project uses organizer-controlled CI configuration.\n# Evaluation is triggered through the API; pushes do not schedule jobs.\nworkflow:\n rules:\n - when: never\n"