Buckets:

download
raw
19.1 kB
import os
import signal
import sys
import time
from pathlib import Path
from typing import Optional
import typer
from rich import print
from rich.prompt import Confirm
from typing_extensions import Annotated
from codecarbon import __app_name__, __version__
from codecarbon.cli.cli_utils import (
create_new_config_file,
get_api_endpoint,
get_config,
get_existing_exp_id,
overwrite_local_config,
)
API_URL = os.environ.get("API_URL", "https://dashboard.codecarbon.io/api")
DEFAULT_PROJECT_ID = "e60afa92-17b7-4720-91a0-1ae91e409ba1"
DEFAULT_ORGANIzATION_ID = "e60afa92-17b7-4720-91a0-1ae91e409ba1"
codecarbon = typer.Typer(no_args_is_help=True)
def main():
"""
Main entry point for the CodeCarbon CLI application.
This function catches any exceptions raised during the execution of the CLI commands
and prints an error message in red using Rich's print function.
"""
try:
codecarbon()
except Exception as e:
print(f"[bold red]Error:[/bold red] {e}")
raise sys.exit(1)
def _api_call(action: str, func, *args, **kwargs):
"""
Run a call to the Code Carbon API, turning the errors it now raises into a
readable message and a clean exit instead of a traceback.
:action: what was being attempted, used as the first part of the message.
"""
try:
return func(*args, **kwargs)
except Exception as e:
print(f"[yellow]{action}[/yellow]. (error: {e})")
raise typer.Exit(1)
def _version_callback(value: bool) -> None:
if value:
print(f"{__app_name__} v{__version__}")
raise typer.Exit()
@codecarbon.callback()
def version(
version: Optional[bool] = typer.Option(
None,
"--version",
"-v",
help="Show the application's version and exit.",
callback=_version_callback,
is_eager=True,
),
) -> None:
return
def show_config(path: Path = Path("./.codecarbon.config")) -> None:
from codecarbon.cli.auth import get_access_token
from codecarbon.core.api_client import ApiClient
d = get_config(path)
print("Current configuration : \n")
print("Config file content : ")
print(d)
try:
api_endpoint = get_api_endpoint(path)
api = ApiClient(endpoint_url=api_endpoint)
api.set_access_token(get_access_token())
if "organization_id" not in d:
print(
"No organization_id in config, follow setup instruction to complete your configuration file!",
)
else:
org = api.get_organization(d["organization_id"])
if "project_id" not in d:
print(
"No project_id in config, follow setup instruction to complete your configuration file!",
)
else:
project = api.get_project(d["project_id"])
if "experiment_id" not in d:
print(
"No experiment_id in config, follow setup instruction to complete your configuration file!",
)
else:
experiment = api.get_experiment(d["experiment_id"])
print("\nExperiment :")
print(experiment)
print("\nProject :")
print(project)
print("\nOrganization :")
print(org)
except Exception as e:
print(
f"[yellow]Could not validate remote configuration details[/yellow]. You can continue with local configuration setup. (error: {e})"
)
@codecarbon.command(
"test-api", short_help="Make an authenticated GET request to an API endpoint"
)
def api_get():
"""
ex: test-api
"""
from codecarbon.cli.auth import get_access_token
from codecarbon.core.api_client import ApiClient
api_endpoint = get_api_endpoint()
api = ApiClient(endpoint_url=api_endpoint)
api.set_access_token(get_access_token())
organizations = _api_call("API request failed", api.get_list_organizations)
print(organizations)
@codecarbon.command("login", short_help="Login to CodeCarbon")
def login():
from codecarbon.cli.auth import authorize, get_access_token
from codecarbon.core.api_client import ApiClient
authorize()
api_endpoint = get_api_endpoint()
api = ApiClient(endpoint_url=api_endpoint)
access_token = get_access_token()
api.set_access_token(access_token)
_api_call("Authentication check failed", api.check_auth)
def get_api_key(project_id: str):
import requests
from codecarbon.cli.auth import get_access_token
api_endpoint = get_api_endpoint()
api_endpoint = api_endpoint.rstrip("/")
req = requests.post(
f"{api_endpoint}/projects/{project_id}/api-tokens",
json={
"project_id": project_id,
"name": "api token",
"x_token": "???",
},
headers={"Authorization": f"Bearer {get_access_token()}"},
)
req.raise_for_status()
api_key = req.json()["token"]
return api_key
@codecarbon.command("get-token", short_help="Get project token")
def get_token(project_id: str):
# api = ApiClient(endpoint_url=API_URL) # TODO: get endpoint from config
# api.set_access_token(get_access_token())
token = get_api_key(project_id)
print("Your token: " + token)
print("Add it to the api_key field in your configuration file")
@codecarbon.command("config", short_help="Generate or show config")
def config():
"""
Initialize CodeCarbon, this will prompt you for configuration of Organisation/Team/Project/Experiment.
"""
from codecarbon.cli.auth import get_access_token
from codecarbon.core.api_client import ApiClient, get_datetime_with_timezone
from codecarbon.core.schemas import (
ExperimentCreate,
OrganizationCreate,
ProjectCreate,
)
print("Welcome to CodeCarbon configuration wizard")
home = Path.home()
global_path = (home / ".codecarbon.config").expanduser().resolve()
if global_path.exists():
print("Existing global config file found :")
show_config(global_path)
use_config = questionary_prompt(
"Use existing global ~/.codecarbon.config to configure or create a new file somewhere else ?",
["~/.codecarbon.config", "Create New Config"],
default="~/.codecarbon.config",
)
if use_config == "~/.codecarbon.config":
modify = Confirm.ask("Do you want to modify the existing config file ?")
if modify:
print(f"Modifying existing config file {global_path}:")
file_path = global_path
else:
print(f"Using already existing global config file {global_path}")
return
else:
file_path = create_new_config_file()
else:
file_path = create_new_config_file()
api_endpoint = get_api_endpoint(file_path)
api_endpoint = typer.prompt(
f"Current API endpoint is {api_endpoint}. Press enter to continue or input other url",
type=str,
default=api_endpoint,
)
overwrite_local_config("api_endpoint", api_endpoint, path=file_path)
api = ApiClient(endpoint_url=api_endpoint)
api.set_access_token(get_access_token())
organizations = _api_call(
"Could not list organizations from API. Please check your login and API endpoint",
api.get_list_organizations,
)
org = questionary_prompt(
"Pick existing organization from list or Create new organization ?",
[org["name"] for org in organizations] + ["Create New Organization"],
default="Create New Organization",
)
if org == "Create New Organization":
org_name = typer.prompt("Organization name", default="Code Carbon user test")
org_description = typer.prompt(
"Organization description", default="Code Carbon user test"
)
organization_create = OrganizationCreate(
name=org_name,
description=org_description,
)
organization = _api_call(
"Could not create the organization",
api.create_organization,
organization=organization_create,
)
print(f"Created organization : {organization}")
else:
organization = [orga for orga in organizations if orga["name"] == org][0]
org_id = organization["id"]
overwrite_local_config("organization_id", org_id, path=file_path)
projects = _api_call(
"Could not list projects from API",
api.list_projects_from_organization,
org_id,
)
project_names = [project["name"] for project in projects]
project = questionary_prompt(
"Pick existing project from list or Create new project ?",
project_names + ["Create New Project"],
default="Create New Project",
)
if project == "Create New Project":
project_name = typer.prompt("Project name", default="Code Carbon user test")
project_description = typer.prompt(
"Project description", default="Code Carbon user test"
)
project_create = ProjectCreate(
name=project_name,
description=project_description,
organization_id=org_id,
)
project = _api_call(
"Could not create the project", api.create_project, project=project_create
)
print(f"Created project : {project}")
else:
project = [p for p in projects if p["name"] == project][0]
project_id = project["id"]
overwrite_local_config("project_id", project_id, path=file_path)
experiments = _api_call(
"Could not list experiments from API",
api.list_experiments_from_project,
project_id,
)
experiments_names = [experiment["name"] for experiment in experiments]
experiment = questionary_prompt(
"Pick existing experiment from list or Create new experiment ?",
experiments_names + ["Create New Experiment"],
default="Create New Experiment",
)
if experiment == "Create New Experiment":
print("Creating new experiment")
exp_name = typer.prompt("Experiment name :", default="Code Carbon user test")
exp_description = typer.prompt(
"Experiment description :",
default="Code Carbon user test ",
)
exp_on_cloud = Confirm.ask("Is this experiment running on the cloud ?")
if exp_on_cloud is True:
cloud_provider = typer.prompt(
"Cloud provider (AWS, GCP, Azure, ...)", default="AWS"
)
cloud_region = typer.prompt(
"Cloud region (eu-west-1, us-east-1, ...)", default="eu-west-1"
)
else:
cloud_provider = None
cloud_region = None
country_name = typer.prompt("Country name :", default="Auto")
country_iso_code = typer.prompt("Country ISO code :", default="Auto")
region = typer.prompt("Region :", default="Auto")
if country_name == "Auto":
country_name = None
if country_iso_code == "Auto":
country_iso_code = None
if region == "Auto":
region = None
experiment_create = ExperimentCreate(
timestamp=get_datetime_with_timezone(),
name=exp_name,
description=exp_description,
on_cloud=exp_on_cloud,
project_id=project["id"],
country_name=country_name,
country_iso_code=country_iso_code,
region=region,
cloud_provider=cloud_provider,
cloud_region=cloud_region,
)
experiment = _api_call(
"Could not create the experiment",
api.add_experiment,
experiment=experiment_create,
)
else:
experiment = [e for e in experiments if e["name"] == experiment][0]
overwrite_local_config("experiment_id", experiment["id"], path=file_path)
api_key = _api_call("Could not get the project API key", get_api_key, project_id)
overwrite_local_config("api_key", api_key, path=file_path)
show_config(file_path)
print(
"Consult [link=https://docs.codecarbon.io/latest/how-to/configuration/]configuration documentation[/link] for more configuration options"
)
def _cli_provided(ctx, name: str) -> bool:
"""
Whether the option `name` was typed on the command line (or set through its
environment variable) rather than left at its Typer default.
Options left at their default must not be forwarded to the tracker: doing so
would silently override the values coming from `.codecarbon.config` and the
`CODECARBON_*` environment variables, which the tracker reads itself.
"""
get_source = getattr(ctx, "get_parameter_source", None)
if get_source is None:
# `monitor` called directly from Python, not through Click: every value
# given is explicit.
return True
source = get_source(name)
return source is None or source.name in ("COMMANDLINE", "ENVIRONMENT")
def _external_config() -> dict:
"""The configuration files and CODECARBON_* variables, as a plain dict."""
from codecarbon.core.config import get_hierarchical_config
try:
return dict(get_hierarchical_config())
except Exception:
return {}
@codecarbon.command(
"monitor",
short_help="Monitor your machine's carbon emissions.",
context_settings={"allow_extra_args": True, "ignore_unknown_options": True},
)
def monitor(
ctx: typer.Context,
measure_power_secs: Annotated[
int,
typer.Option(help="Interval between two measures."),
] = 10,
api_call_interval: Annotated[
int,
typer.Option(help="Number of measures between API calls."),
] = 30,
api: Annotated[
bool,
typer.Option(help="Choose to call Code Carbon API or not"),
] = True,
offline: Annotated[bool, typer.Option(help="Run in offline mode")] = False,
country_iso_code: Annotated[
str,
typer.Option(help="3-letter country ISO code for offline mode"),
] = None,
region: Annotated[
str,
typer.Option(help="Region/province for offline mode"),
] = None,
log_level: Annotated[
str,
typer.Option(help="Log level (critical, error, warning, info, debug)"),
] = "error",
):
"""Monitor your machine's carbon emissions."""
external_conf = _external_config()
# Shared tracker args so monitor and run_and_monitor behave the same.
# Only the options actually given are forwarded: the others are left to the
# tracker, which resolves them from the configuration file and environment.
cli_defaults = (
("measure_power_secs", measure_power_secs),
("api_call_interval", api_call_interval),
("log_level", log_level),
)
tracker_args = {
name: value for name, value in cli_defaults if _cli_provided(ctx, name)
}
for name, value in cli_defaults:
if name not in tracker_args and name not in external_conf:
# Nothing configures it: keep the defaults advertised by `--help`
# (and an unattended monitor quiet) instead of the tracker's own.
tracker_args[name] = value
# Set up the tracker arguments based on mode (offline vs online) and validate required args for each mode
if offline:
if not country_iso_code and not external_conf.get("country_iso_code"):
print(
"ERROR: Country ISO code is required for offline mode. Add it to your configuration or provide it via the command line: `--country-iso-code FRA`",
file=sys.stderr,
)
raise typer.Exit(1)
tracker_args = {
**tracker_args,
**({"country_iso_code": country_iso_code} if country_iso_code else {}),
**({"region": region} if region else {}),
}
else:
experiment_id = get_existing_exp_id()
if api and experiment_id is None:
print(
"ERROR: No experiment id. Set CODECARBON_EXPERIMENT_ID, call 'codecarbon config' first, or run in offline mode with `--offline --country-iso-code FRA`.",
file=sys.stderr,
)
raise typer.Exit(1)
tracker_args = {**tracker_args, "save_to_api": api}
from codecarbon.emissions_tracker import EmissionsTracker, OfflineEmissionsTracker
# If extra args are provided (e.g. `codecarbon monitor -- my_script.py`), delegate to `run_and_monitor`
if getattr(ctx, "args", None):
from codecarbon.cli.monitor import run_and_monitor
return run_and_monitor(ctx, offline=offline, **tracker_args)
# Instantiate the tracker
if offline:
tracker = OfflineEmissionsTracker(**tracker_args)
else:
tracker = EmissionsTracker(**tracker_args)
def signal_handler(signum, frame):
print("\nReceived signal to stop. Saving emissions data...")
tracker.stop()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
print("CodeCarbon is going in an infinite loop to monitor this machine.")
print("Press Ctrl+C to stop and save emissions data.")
tracker.start()
try:
while True:
if (
hasattr(tracker, "_another_instance_already_running")
and tracker._another_instance_already_running
):
print("Another instance of CodeCarbon is already running. Exiting.")
break
time.sleep(300)
except Exception as e:
print(f"\nError occurred: {e}")
tracker.stop()
raise e
@codecarbon.command("detect", short_help="Detect hardware and print information.")
def detect():
"""
Detects hardware and prints information without running any measurements.
"""
from codecarbon.emissions_tracker import EmissionsTracker
print("Detecting hardware...")
tracker = EmissionsTracker(save_to_file=False)
hardware_info = tracker.get_detected_hardware()
print("\nDetected Hardware and System Information:")
print(f"- Available RAM: {hardware_info['ram_total_size']:.3f} GB")
print(
f"- CPU count: {hardware_info['cpu_count']} thread(s) in {hardware_info['cpu_physical_count']} physical CPU(s)"
)
print(f"- CPU model: {hardware_info['cpu_model']}")
print(f"- GPU count: {hardware_info['gpu_count']}")
gpu_model_str = hardware_info["gpu_model"]
if hardware_info.get("gpu_ids"):
gpu_model_str += (
f" BUT only tracking these GPU ids : {hardware_info['gpu_ids']}"
)
print(f"- GPU model: {gpu_model_str}")
def questionary_prompt(prompt, list_options, default):
import questionary
value = questionary.select(
prompt,
list_options,
default,
).ask()
return value
if __name__ == "__main__":
main()

Xet Storage Details

Size:
19.1 kB
·
Xet hash:
18c7e8114b904c191fb60a3941b9633421dddb325486683f566f730c8e9b7d26

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.