Tonic/l-android-control
1
1import os2import warnings3import webbrowser4from pathlib import Path5from typing import Any6 7from gradio_client import Client8 9from trackio import context_vars, deploy, utils10from trackio.imports import import_csv, import_tf_events11from trackio.run import Run12from trackio.sqlite_storage import SQLiteStorage13from trackio.ui import demo14from trackio.utils import TRACKIO_DIR, TRACKIO_LOGO_DIR15 16__version__ = Path(__file__).parent.joinpath("version.txt").read_text().strip()17 18__all__ = ["init", "log", "finish", "show", "import_csv", "import_tf_events"]19 20 21config = {}22 23 24def init(25 project: str,26 name: str | None = None,27 space_id: str | None = None,28 dataset_id: str | None = None,29 config: dict | None = None,30 resume: str = "never",31 settings: Any = None,32) -> Run:33 """34 Creates a new Trackio project and returns a Run object.35 36 Args:37 project: The name of the project (can be an existing project to continue tracking or a new project to start tracking from scratch).38 name: The name of the run (if not provided, a default name will be generated).39 space_id: If provided, the project will be logged to a Hugging Face Space instead of a local directory. Should be a complete Space name like "username/reponame" or "orgname/reponame", or just "reponame" in which case the Space will be created in the currently-logged-in Hugging Face user's namespace. If the Space does not exist, it will be created. If the Space already exists, the project will be logged to it.40 dataset_id: If a space_id is provided, a persistent Hugging Face Dataset will be created and the metrics will be synced to it every 5 minutes. Specify a Dataset with name like "username/datasetname" or "orgname/datasetname", or "datasetname" (uses currently-logged-in Hugging Face user's namespace), or None (uses the same name as the Space but with the "_dataset" suffix). If the Dataset does not exist, it will be created. If the Dataset already exists, the project will be appended to it.41 config: A dictionary of configuration options. Provided for compatibility with wandb.init()42 resume: Controls how to handle resuming a run. Can be one of:43 - "must": Must resume the run with the given name, raises error if run doesn't exist44 - "allow": Resume the run if it exists, otherwise create a new run45 - "never": Never resume a run, always create a new one46 settings: Not used. Provided for compatibility with wandb.init()47 """48 if settings is not None:49 warnings.warn(50 "* Warning: settings is not used. Provided for compatibility with wandb.init(). Please create an issue at: https://github.com/gradio-app/trackio/issues if you need a specific feature implemented."51 )52 53 if space_id is None and dataset_id is not None:54 raise ValueError("Must provide a `space_id` when `dataset_id` is provided.")55 space_id, dataset_id = utils.preprocess_space_and_dataset_ids(space_id, dataset_id)56 url = context_vars.current_server.get()57 58 if url is None:59 if space_id is None:60 _, url, _ = demo.launch(61 show_api=False,62 inline=False,63 quiet=True,64 prevent_thread_lock=True,65 show_error=True,66 )67 else:68 url = space_id69 context_vars.current_server.set(url)70 71 if (72 context_vars.current_project.get() is None73 or context_vars.current_project.get() != project74 ):75 print(f"* Trackio project initialized: {project}")76 77 if dataset_id is not None:78 os.environ["TRACKIO_DATASET_ID"] = dataset_id79 print(80 f"* Trackio metrics will be synced to Hugging Face Dataset: {dataset_id}"81 )82 if space_id is None:83 print(f"* Trackio metrics logged to: {TRACKIO_DIR}")84 utils.print_dashboard_instructions(project)85 else:86 deploy.create_space_if_not_exists(space_id, dataset_id)87 print(88 f"* View dashboard by going to: {deploy.SPACE_URL.format(space_id=space_id)}"89 )90 context_vars.current_project.set(project)91 92 client = None93 if not space_id:94 client = Client(url, verbose=False)95 96 if resume == "must":97 if name is None:98 raise ValueError("Must provide a run name when resume='must'")99 if name not in SQLiteStorage.get_runs(project):100 raise ValueError(f"Run '{name}' does not exist in project '{project}'")101 elif resume == "allow":102 if name is not None and name in SQLiteStorage.get_runs(project):103 print(f"* Resuming existing run: {name}")104 elif resume == "never":105 if name is not None and name in SQLiteStorage.get_runs(project):106 name = None107 else:108 raise ValueError("resume must be one of: 'must', 'allow', or 'never'")109 110 run = Run(111 url=url,112 project=project,113 client=client,114 name=name,115 config=config,116 )117 context_vars.current_run.set(run)118 globals()["config"] = run.config119 return run120 121 122def log(metrics: dict, step: int | None = None) -> None:123 """124 Logs metrics to the current run.125 126 Args:127 metrics: A dictionary of metrics to log.128 step: The step number. If not provided, the step will be incremented automatically.129 """130 run = context_vars.current_run.get()131 if run is None:132 raise RuntimeError("Call trackio.init() before trackio.log().")133 run.log(134 metrics=metrics,135 step=step,136 )137 138 139def finish():140 """141 Finishes the current run.142 """143 run = context_vars.current_run.get()144 if run is None:145 raise RuntimeError("Call trackio.init() before trackio.finish().")146 run.finish()147 148 149def show(project: str | None = None):150 """151 Launches the Trackio dashboard.152 153 Args:154 project: The name of the project whose runs to show. If not provided, all projects will be shown and the user can select one.155 """156 _, url, share_url = demo.launch(157 show_api=False,158 quiet=True,159 inline=False,160 prevent_thread_lock=True,161 favicon_path=TRACKIO_LOGO_DIR / "trackio_logo_light.png",162 allowed_paths=[TRACKIO_LOGO_DIR],163 )164 base_url = share_url + "/" if share_url else url165 dashboard_url = base_url + f"?project={project}" if project else base_url166 print(f"* Trackio UI launched at: {dashboard_url}")167 webbrowser.open(dashboard_url)168 utils.block_except_in_notebook()169 