greenaihack 0.0.3__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.3
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.3"
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.3"
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"
@@ -37,6 +37,7 @@ from .ui import (
37
37
  note,
38
38
  prompt,
39
39
  require_terminal,
40
+ results_panel,
40
41
  status_panel,
41
42
  step,
42
43
  success,
@@ -453,19 +454,32 @@ def logs(
453
454
 
454
455
 
455
456
  @app.command()
456
- def results(submission_id: SubmissionId = None):
457
- """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
458
460
  from .submission import status as fetch
459
461
 
460
- use_stderr() # stdout holds only the predictions JSON.
462
+ use_stderr(json_output)
461
463
  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
- )
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
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))
469
483
 
470
484
 
471
485
  def _resolve(submission_id):
@@ -147,13 +147,46 @@ def write_ini(path, parser):
147
147
  atomic_write(path, stream.getvalue())
148
148
 
149
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
+
150
185
  STARTER = {
151
186
  "pyproject.toml": (
152
187
  '[project]\nname = "greenaihack-team"\nversion = "0.1.0"\nrequires-python = ">=3.12"\ndependencies = []\n\n[tool.uv]\npackage = false\n'
153
188
  ),
154
- "my_eval.py": (
155
- '"""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'
156
- ),
189
+ "my_eval.py": EVAL_STARTER,
157
190
  "models/.gitkeep": "",
158
191
  ".gitlab-ci.yml": (
159
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"
@@ -284,10 +284,122 @@ def status_panel(result, manifest=None):
284
284
  _panel(details, f"Submission {escape(name)}" if name else "Submission")
285
285
 
286
286
 
287
+ def _number(value):
288
+ """A finite real number, or None (bools and malformed values are not)."""
289
+ import math
290
+
291
+ if isinstance(value, bool) or not isinstance(value, int | float):
292
+ return None
293
+ return value if math.isfinite(value) else None
294
+
295
+
296
+ def _significant(value):
297
+ """Three significant digits without scientific notation."""
298
+ import math
299
+
300
+ value = float(f"{value:.3g}") # Round first: 0.9996 reads 1.00, not 1.000.
301
+ if value == 0:
302
+ return "0"
303
+ decimals = max(0, 2 - math.floor(math.log10(abs(value))))
304
+ return f"{value:,.{decimals}f}"
305
+
306
+
307
+ # Display units as (factor from the stored unit, label), largest first.
308
+ _ENERGY = [(1, "kWh"), (1e3, "Wh"), (1e6, "mWh")]
309
+ _GWP = [(1, "kg CO2eq"), (1e3, "g CO2eq"), (1e6, "mg CO2eq")]
310
+
311
+
312
+ def _unit(value, units):
313
+ """Pick the largest unit in which value reads at least 1 (zero: Wh, g)."""
314
+ if value == 0:
315
+ return units[1]
316
+ for factor, label in units:
317
+ if float(f"{abs(value) * factor:.3g}") >= 1: # As displayed, rounded.
318
+ return factor, label
319
+ return units[-1]
320
+
321
+
322
+ def _quantity(value, units, factor_label=None):
323
+ factor, label = factor_label or _unit(value, units)
324
+ return f"{_significant(value * factor)} {label}"
325
+
326
+
327
+ def _seconds(value):
328
+ if value < 60:
329
+ return f"{_significant(value)} s"
330
+ minutes, seconds = divmod(round(value), 60)
331
+ return f"{minutes} min {seconds:02d} s"
332
+
333
+
334
+ def results_panel(results, manifest=None):
335
+ """Summarize accuracy and environmental impacts of an evaluation."""
336
+ details = Table.grid(padding=(0, 2))
337
+ accuracy = _number(results.get("accuracy"))
338
+ if accuracy is not None:
339
+ details.add_row("[dim]Accuracy[/]", f"[bold]{accuracy * 100:.2f} %[/]")
340
+ duration = _number(results.get("duration_s"))
341
+ if duration is not None:
342
+ details.add_row("[dim]Duration[/]", _seconds(duration))
343
+ energy = results.get("energy_kwh")
344
+ energy = energy if isinstance(energy, dict) else {}
345
+ total = _number(energy.get("total"))
346
+ if total is not None:
347
+ unit = _unit(total, _ENERGY)
348
+ parts = [
349
+ f"{name.upper()} {_quantity(part, _ENERGY, unit)}"
350
+ for name in ("cpu", "ram", "gpu")
351
+ if (part := _number(energy.get(name))) is not None
352
+ ]
353
+ breakdown = f" [dim]{' · '.join(parts)}[/]" if parts else ""
354
+ details.add_row("[dim]Energy[/]", _quantity(total, _ENERGY, unit) + breakdown)
355
+ gwp = {
356
+ key: _number(results.get(f"{key}_gwp_kgco2eq"))
357
+ for key in ("total", "usage", "embodied")
358
+ }
359
+ if gwp["total"] is not None:
360
+ unit = _unit(gwp["total"], _GWP)
361
+ parts = [
362
+ f"{key} {_quantity(gwp[key], _GWP, unit)}"
363
+ for key in ("usage", "embodied")
364
+ if gwp[key] is not None
365
+ ]
366
+ breakdown = f" [dim]{' + '.join(parts)}[/]" if parts else ""
367
+ details.add_row(
368
+ "[dim]Carbon[/]", f"[bold]{_quantity(gwp['total'], _GWP, unit)}[/]{breakdown}"
369
+ )
370
+ dataset = results.get("dataset")
371
+ dataset = dataset if isinstance(dataset, dict) else {}
372
+ rows = _number(dataset.get("rows"))
373
+ if rows is not None:
374
+ name = dataset.get("name")
375
+ label = f"{escape(name)} · " if isinstance(name, str) else ""
376
+ details.add_row("[dim]Dataset[/]", f"{label}{int(rows):,} rows")
377
+ measurement = results.get("measurement")
378
+ measurement = measurement if isinstance(measurement, dict) else {}
379
+ profile = measurement.get("hardware_profile")
380
+ if isinstance(profile, str):
381
+ cpu = measurement.get("cpu_model")
382
+ cpu = f" [dim]{escape(cpu)}[/]" if isinstance(cpu, str) and cpu else ""
383
+ details.add_row("[dim]Hardware[/]", escape(profile) + cpu)
384
+ if isinstance(results.get("commit"), str):
385
+ details.add_row("[dim]Commit[/]", escape(results["commit"][:7]))
386
+ if isinstance(results.get("script"), str):
387
+ details.add_row("[dim]Script[/]", escape(results["script"]))
388
+ if isinstance(results.get("models"), list):
389
+ details.add_row("[dim]Models[/]", _models(map(str, results["models"])))
390
+ name = manifest["name"] if manifest else None
391
+ _panel(details, f"Results {escape(name)}" if name else "Results")
392
+ console.print(
393
+ "[dim]Usage is measured with CodeCarbon while your script runs (an "
394
+ "estimate on shared runners); embodied impact is the hardware's "
395
+ "manufacturing footprint amortised over the same time.[/]\n"
396
+ )
397
+
398
+
287
399
  def next_steps(identifier, state):
288
400
  """Suggest the commands that make sense for a submission in this state."""
289
401
  if state == "success":
290
- hints = [("Read the logs", "logs"), ("See predictions", "results")]
402
+ hints = [("See accuracy and impacts", "results"), ("Read the logs", "logs")]
291
403
  elif state in {"failed", "canceled", "skipped"}:
292
404
  hints = [("See what happened", "logs")]
293
405
  elif state == "trigger_uncertain":
File without changes