saba9 HF Staff commited on
Commit
f5294e6
·
verified ·
1 Parent(s): a06d1d1

Upload folder using huggingface_hub

Browse files
Files changed (49) hide show
  1. .gitattributes +1 -0
  2. __init__.py +237 -0
  3. __pycache__/__init__.cpython-312.pyc +0 -0
  4. __pycache__/__init__.cpython-313.pyc +0 -0
  5. __pycache__/cli.cpython-312.pyc +0 -0
  6. __pycache__/commit_scheduler.cpython-312.pyc +0 -0
  7. __pycache__/commit_scheduler.cpython-313.pyc +0 -0
  8. __pycache__/context_vars.cpython-312.pyc +0 -0
  9. __pycache__/context_vars.cpython-313.pyc +0 -0
  10. __pycache__/deploy.cpython-312.pyc +0 -0
  11. __pycache__/deploy.cpython-313.pyc +0 -0
  12. __pycache__/dummy_commit_scheduler.cpython-312.pyc +0 -0
  13. __pycache__/dummy_commit_scheduler.cpython-313.pyc +0 -0
  14. __pycache__/file_storage.cpython-312.pyc +0 -0
  15. __pycache__/imports.cpython-312.pyc +0 -0
  16. __pycache__/imports.cpython-313.pyc +0 -0
  17. __pycache__/media.cpython-312.pyc +0 -0
  18. __pycache__/run.cpython-312.pyc +0 -0
  19. __pycache__/run.cpython-313.pyc +0 -0
  20. __pycache__/sqlite_storage.cpython-312.pyc +0 -0
  21. __pycache__/sqlite_storage.cpython-313.pyc +0 -0
  22. __pycache__/typehints.cpython-312.pyc +0 -0
  23. __pycache__/ui.cpython-312.pyc +0 -0
  24. __pycache__/ui.cpython-313.pyc +0 -0
  25. __pycache__/utils.cpython-312.pyc +0 -0
  26. __pycache__/utils.cpython-313.pyc +0 -0
  27. assets/trackio_logo_dark.png +0 -0
  28. assets/trackio_logo_light.png +0 -0
  29. assets/trackio_logo_old.png +3 -0
  30. assets/trackio_logo_type_dark.png +0 -0
  31. assets/trackio_logo_type_dark_transparent.png +0 -0
  32. assets/trackio_logo_type_light.png +0 -0
  33. assets/trackio_logo_type_light_transparent.png +0 -0
  34. cli.py +32 -0
  35. commit_scheduler.py +391 -0
  36. context_vars.py +15 -0
  37. deploy.py +173 -0
  38. dummy_commit_scheduler.py +12 -0
  39. file_storage.py +72 -0
  40. imports.py +288 -0
  41. media.py +230 -0
  42. py.typed +0 -0
  43. run.py +154 -0
  44. run_context.py +6 -0
  45. sqlite_storage.py +389 -0
  46. typehints.py +17 -0
  47. ui.py +731 -0
  48. utils.py +574 -0
  49. version.txt +1 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ assets/trackio_logo_old.png filter=lfs diff=lfs merge=lfs -text
__init__.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import os
3
+ import warnings
4
+ import webbrowser
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from gradio.blocks import BUILT_IN_THEMES
9
+ from gradio.themes import Default as DefaultTheme
10
+ from gradio.themes import ThemeClass
11
+ from gradio_client import Client
12
+
13
+ from trackio import context_vars, deploy, utils
14
+ from trackio.imports import import_csv, import_tf_events
15
+ from trackio.media import TrackioImage, TrackioVideo
16
+ from trackio.run import Run
17
+ from trackio.sqlite_storage import SQLiteStorage
18
+ from trackio.ui import demo
19
+ from trackio.utils import TRACKIO_DIR, TRACKIO_LOGO_DIR
20
+
21
+ __version__ = Path(__file__).parent.joinpath("version.txt").read_text().strip()
22
+
23
+ __all__ = ["init", "log", "finish", "show", "import_csv", "import_tf_events", "Image"]
24
+
25
+ Image = TrackioImage
26
+ Video = TrackioVideo
27
+
28
+
29
+ config = {}
30
+
31
+ DEFAULT_THEME = "citrus"
32
+
33
+
34
+ def init(
35
+ project: str,
36
+ name: str | None = None,
37
+ space_id: str | None = None,
38
+ dataset_id: str | None = None,
39
+ config: dict | None = None,
40
+ resume: str = "never",
41
+ settings: Any = None,
42
+ ) -> Run:
43
+ """
44
+ Creates a new Trackio project and returns a [`Run`] object.
45
+
46
+ Args:
47
+ project (`str`):
48
+ The name of the project (can be an existing project to continue tracking or
49
+ a new project to start tracking from scratch).
50
+ name (`str` or `None`, *optional*, defaults to `None`):
51
+ The name of the run (if not provided, a default name will be generated).
52
+ space_id (`str` or `None`, *optional*, defaults to `None`):
53
+ If provided, the project will be logged to a Hugging Face Space instead of
54
+ a local directory. Should be a complete Space name like
55
+ `"username/reponame"` or `"orgname/reponame"`, or just `"reponame"` in which
56
+ case the Space will be created in the currently-logged-in Hugging Face
57
+ user's namespace. If the Space does not exist, it will be created. If the
58
+ Space already exists, the project will be logged to it.
59
+ dataset_id (`str` or `None`, *optional*, defaults to `None`):
60
+ If a `space_id` is provided, a persistent Hugging Face Dataset will be
61
+ created and the metrics will be synced to it every 5 minutes. Specify a
62
+ Dataset with name like `"username/datasetname"` or `"orgname/datasetname"`,
63
+ or `"datasetname"` (uses currently-logged-in Hugging Face user's namespace),
64
+ or `None` (uses the same name as the Space but with the `"_dataset"`
65
+ suffix). If the Dataset does not exist, it will be created. If the Dataset
66
+ already exists, the project will be appended to it.
67
+ config (`dict` or `None`, *optional*, defaults to `None`):
68
+ A dictionary of configuration options. Provided for compatibility with
69
+ `wandb.init()`.
70
+ resume (`str`, *optional*, defaults to `"never"`):
71
+ Controls how to handle resuming a run. Can be one of:
72
+
73
+ - `"must"`: Must resume the run with the given name, raises error if run
74
+ doesn't exist
75
+ - `"allow"`: Resume the run if it exists, otherwise create a new run
76
+ - `"never"`: Never resume a run, always create a new one
77
+ settings (`Any`, *optional*, defaults to `None`):
78
+ Not used. Provided for compatibility with `wandb.init()`.
79
+
80
+ Returns:
81
+ `Run`: A [`Run`] object that can be used to log metrics and finish the run.
82
+ """
83
+ if settings is not None:
84
+ warnings.warn(
85
+ "* 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."
86
+ )
87
+
88
+ if space_id is None and dataset_id is not None:
89
+ raise ValueError("Must provide a `space_id` when `dataset_id` is provided.")
90
+ space_id, dataset_id = utils.preprocess_space_and_dataset_ids(space_id, dataset_id)
91
+ url = context_vars.current_server.get()
92
+
93
+ if url is None:
94
+ if space_id is None:
95
+ _, url, _ = demo.launch(
96
+ show_api=False,
97
+ inline=False,
98
+ quiet=True,
99
+ prevent_thread_lock=True,
100
+ show_error=True,
101
+ )
102
+ else:
103
+ url = space_id
104
+ context_vars.current_server.set(url)
105
+
106
+ if (
107
+ context_vars.current_project.get() is None
108
+ or context_vars.current_project.get() != project
109
+ ):
110
+ print(f"* Trackio project initialized: {project}")
111
+
112
+ if dataset_id is not None:
113
+ os.environ["TRACKIO_DATASET_ID"] = dataset_id
114
+ print(
115
+ f"* Trackio metrics will be synced to Hugging Face Dataset: {dataset_id}"
116
+ )
117
+ if space_id is None:
118
+ print(f"* Trackio metrics logged to: {TRACKIO_DIR}")
119
+ utils.print_dashboard_instructions(project)
120
+ else:
121
+ deploy.create_space_if_not_exists(space_id, dataset_id)
122
+ print(
123
+ f"* View dashboard by going to: {deploy.SPACE_URL.format(space_id=space_id)}"
124
+ )
125
+ context_vars.current_project.set(project)
126
+
127
+ client = None
128
+ if not space_id:
129
+ client = Client(url, verbose=False)
130
+
131
+ if resume == "must":
132
+ if name is None:
133
+ raise ValueError("Must provide a run name when resume='must'")
134
+ if name not in SQLiteStorage.get_runs(project):
135
+ raise ValueError(f"Run '{name}' does not exist in project '{project}'")
136
+ elif resume == "allow":
137
+ if name is not None and name in SQLiteStorage.get_runs(project):
138
+ print(f"* Resuming existing run: {name}")
139
+ elif resume == "never":
140
+ if name is not None and name in SQLiteStorage.get_runs(project):
141
+ name = None
142
+ else:
143
+ raise ValueError("resume must be one of: 'must', 'allow', or 'never'")
144
+
145
+ run = Run(
146
+ url=url,
147
+ project=project,
148
+ client=client,
149
+ name=name,
150
+ config=config,
151
+ space_id=space_id,
152
+ )
153
+ context_vars.current_run.set(run)
154
+ globals()["config"] = run.config
155
+ return run
156
+
157
+
158
+ def log(metrics: dict, step: int | None = None) -> None:
159
+ """
160
+ Logs metrics to the current run.
161
+
162
+ Args:
163
+ metrics (`dict`):
164
+ A dictionary of metrics to log.
165
+ step (`int` or `None`, *optional*, defaults to `None`):
166
+ The step number. If not provided, the step will be incremented
167
+ automatically.
168
+ """
169
+ run = context_vars.current_run.get()
170
+ if run is None:
171
+ raise RuntimeError("Call trackio.init() before trackio.log().")
172
+ run.log(
173
+ metrics=metrics,
174
+ step=step,
175
+ )
176
+
177
+
178
+ def finish():
179
+ """
180
+ Finishes the current run.
181
+ """
182
+ run = context_vars.current_run.get()
183
+ if run is None:
184
+ raise RuntimeError("Call trackio.init() before trackio.finish().")
185
+ run.finish()
186
+
187
+
188
+ def show(project: str | None = None, theme: str | ThemeClass = DEFAULT_THEME):
189
+ """
190
+ Launches the Trackio dashboard.
191
+
192
+ Args:
193
+ project (`str` or `None`, *optional*, defaults to `None`):
194
+ The name of the project whose runs to show. If not provided, all projects
195
+ will be shown and the user can select one.
196
+ theme (`str` or `ThemeClass`, *optional*, defaults to `"citrus"`):
197
+ A Gradio Theme to use for the dashboard instead of the default `"citrus"`,
198
+ can be a built-in theme (e.g. `'soft'`, `'default'`), a theme from the Hub
199
+ (e.g. `"gstaff/xkcd"`), or a custom Theme class.
200
+ """
201
+ if theme != DEFAULT_THEME:
202
+ # TODO: It's a little hacky to reproduce this theme-setting logic from Gradio Blocks,
203
+ # but in Gradio 6.0, the theme will be set in `launch()` instead, which means that we
204
+ # will be able to remove this code.
205
+ if isinstance(theme, str):
206
+ if theme.lower() in BUILT_IN_THEMES:
207
+ theme = BUILT_IN_THEMES[theme.lower()]
208
+ else:
209
+ try:
210
+ theme = ThemeClass.from_hub(theme)
211
+ except Exception as e:
212
+ warnings.warn(f"Cannot load {theme}. Caught Exception: {str(e)}")
213
+ theme = DefaultTheme()
214
+ if not isinstance(theme, ThemeClass):
215
+ warnings.warn("Theme should be a class loaded from gradio.themes")
216
+ theme = DefaultTheme()
217
+ demo.theme: ThemeClass = theme
218
+ demo.theme_css = theme._get_theme_css()
219
+ demo.stylesheets = theme._stylesheets
220
+ theme_hasher = hashlib.sha256()
221
+ theme_hasher.update(demo.theme_css.encode("utf-8"))
222
+ demo.theme_hash = theme_hasher.hexdigest()
223
+
224
+ _, url, share_url = demo.launch(
225
+ show_api=False,
226
+ quiet=True,
227
+ inline=False,
228
+ prevent_thread_lock=True,
229
+ favicon_path=TRACKIO_LOGO_DIR / "trackio_logo_light.png",
230
+ allowed_paths=[TRACKIO_LOGO_DIR, TRACKIO_DIR],
231
+ )
232
+
233
+ base_url = share_url + "/" if share_url else url
234
+ dashboard_url = base_url + f"?project={project}" if project else base_url
235
+ print(f"* Trackio UI launched at: {dashboard_url}")
236
+ webbrowser.open(dashboard_url)
237
+ utils.block_except_in_notebook()
__pycache__/__init__.cpython-312.pyc ADDED
Binary file (10.9 kB). View file
 
__pycache__/__init__.cpython-313.pyc ADDED
Binary file (7.35 kB). View file
 
__pycache__/cli.cpython-312.pyc ADDED
Binary file (1.43 kB). View file
 
__pycache__/commit_scheduler.cpython-312.pyc ADDED
Binary file (18.8 kB). View file
 
__pycache__/commit_scheduler.cpython-313.pyc ADDED
Binary file (18.3 kB). View file
 
__pycache__/context_vars.cpython-312.pyc ADDED
Binary file (759 Bytes). View file
 
__pycache__/context_vars.cpython-313.pyc ADDED
Binary file (745 Bytes). View file
 
__pycache__/deploy.cpython-312.pyc ADDED
Binary file (6.5 kB). View file
 
__pycache__/deploy.cpython-313.pyc ADDED
Binary file (6.27 kB). View file
 
__pycache__/dummy_commit_scheduler.cpython-312.pyc ADDED
Binary file (1.01 kB). View file
 
__pycache__/dummy_commit_scheduler.cpython-313.pyc ADDED
Binary file (1.1 kB). View file
 
__pycache__/file_storage.cpython-312.pyc ADDED
Binary file (3.64 kB). View file
 
__pycache__/imports.cpython-312.pyc ADDED
Binary file (12.7 kB). View file
 
__pycache__/imports.cpython-313.pyc ADDED
Binary file (11.6 kB). View file
 
__pycache__/media.cpython-312.pyc ADDED
Binary file (11.7 kB). View file
 
__pycache__/run.cpython-312.pyc ADDED
Binary file (7.53 kB). View file
 
__pycache__/run.cpython-313.pyc ADDED
Binary file (1.37 kB). View file
 
__pycache__/sqlite_storage.cpython-312.pyc ADDED
Binary file (18.9 kB). View file
 
__pycache__/sqlite_storage.cpython-313.pyc ADDED
Binary file (13.8 kB). View file
 
__pycache__/typehints.cpython-312.pyc ADDED
Binary file (851 Bytes). View file
 
__pycache__/ui.cpython-312.pyc ADDED
Binary file (29 kB). View file
 
__pycache__/ui.cpython-313.pyc ADDED
Binary file (5.37 kB). View file
 
__pycache__/utils.cpython-312.pyc ADDED
Binary file (15.6 kB). View file
 
__pycache__/utils.cpython-313.pyc ADDED
Binary file (9.8 kB). View file
 
assets/trackio_logo_dark.png ADDED
assets/trackio_logo_light.png ADDED
assets/trackio_logo_old.png ADDED

Git LFS Details

  • SHA256: 3922c4d1e465270ad4d8abb12023f3beed5d9f7f338528a4c0ac21dcf358a1c8
  • Pointer size: 131 Bytes
  • Size of remote file: 487 kB
assets/trackio_logo_type_dark.png ADDED
assets/trackio_logo_type_dark_transparent.png ADDED
assets/trackio_logo_type_light.png ADDED
assets/trackio_logo_type_light_transparent.png ADDED
cli.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+
3
+ from trackio import show
4
+
5
+
6
+ def main():
7
+ parser = argparse.ArgumentParser(description="Trackio CLI")
8
+ subparsers = parser.add_subparsers(dest="command")
9
+
10
+ ui_parser = subparsers.add_parser(
11
+ "show", help="Show the Trackio dashboard UI for a project"
12
+ )
13
+ ui_parser.add_argument(
14
+ "--project", required=False, help="Project name to show in the dashboard"
15
+ )
16
+ ui_parser.add_argument(
17
+ "--theme",
18
+ required=False,
19
+ default="citrus",
20
+ help="A Gradio Theme to use for the dashboard instead of the default 'citrus', can be a built-in theme (e.g. 'soft', 'default'), a theme from the Hub (e.g. 'gstaff/xkcd').",
21
+ )
22
+
23
+ args = parser.parse_args()
24
+
25
+ if args.command == "show":
26
+ show(args.project, args.theme)
27
+ else:
28
+ parser.print_help()
29
+
30
+
31
+ if __name__ == "__main__":
32
+ main()
commit_scheduler.py ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Originally copied from https://github.com/huggingface/huggingface_hub/blob/d0a948fc2a32ed6e557042a95ef3e4af97ec4a7c/src/huggingface_hub/_commit_scheduler.py
2
+
3
+ import atexit
4
+ import logging
5
+ import os
6
+ import time
7
+ from concurrent.futures import Future
8
+ from dataclasses import dataclass
9
+ from io import SEEK_END, SEEK_SET, BytesIO
10
+ from pathlib import Path
11
+ from threading import Lock, Thread
12
+ from typing import Callable, Dict, List, Optional, Union
13
+
14
+ from huggingface_hub.hf_api import (
15
+ DEFAULT_IGNORE_PATTERNS,
16
+ CommitInfo,
17
+ CommitOperationAdd,
18
+ HfApi,
19
+ )
20
+ from huggingface_hub.utils import filter_repo_objects
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class _FileToUpload:
27
+ """Temporary dataclass to store info about files to upload. Not meant to be used directly."""
28
+
29
+ local_path: Path
30
+ path_in_repo: str
31
+ size_limit: int
32
+ last_modified: float
33
+
34
+
35
+ class CommitScheduler:
36
+ """
37
+ Scheduler to upload a local folder to the Hub at regular intervals (e.g. push to hub every 5 minutes).
38
+
39
+ The recommended way to use the scheduler is to use it as a context manager. This ensures that the scheduler is
40
+ properly stopped and the last commit is triggered when the script ends. The scheduler can also be stopped manually
41
+ with the `stop` method. Checkout the [upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#scheduled-uploads)
42
+ to learn more about how to use it.
43
+
44
+ Args:
45
+ repo_id (`str`):
46
+ The id of the repo to commit to.
47
+ folder_path (`str` or `Path`):
48
+ Path to the local folder to upload regularly.
49
+ every (`int` or `float`, *optional*):
50
+ The number of minutes between each commit. Defaults to 5 minutes.
51
+ path_in_repo (`str`, *optional*):
52
+ Relative path of the directory in the repo, for example: `"checkpoints/"`. Defaults to the root folder
53
+ of the repository.
54
+ repo_type (`str`, *optional*):
55
+ The type of the repo to commit to. Defaults to `model`.
56
+ revision (`str`, *optional*):
57
+ The revision of the repo to commit to. Defaults to `main`.
58
+ private (`bool`, *optional*):
59
+ Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.
60
+ token (`str`, *optional*):
61
+ The token to use to commit to the repo. Defaults to the token saved on the machine.
62
+ allow_patterns (`List[str]` or `str`, *optional*):
63
+ If provided, only files matching at least one pattern are uploaded.
64
+ ignore_patterns (`List[str]` or `str`, *optional*):
65
+ If provided, files matching any of the patterns are not uploaded.
66
+ squash_history (`bool`, *optional*):
67
+ Whether to squash the history of the repo after each commit. Defaults to `False`. Squashing commits is
68
+ useful to avoid degraded performances on the repo when it grows too large.
69
+ hf_api (`HfApi`, *optional*):
70
+ The [`HfApi`] client to use to commit to the Hub. Can be set with custom settings (user agent, token,...).
71
+ on_before_commit (`Callable[[], None]`, *optional*):
72
+ If specified, a function that will be called before the CommitScheduler lists files to create a commit.
73
+
74
+ Example:
75
+ ```py
76
+ >>> from pathlib import Path
77
+ >>> from huggingface_hub import CommitScheduler
78
+
79
+ # Scheduler uploads every 10 minutes
80
+ >>> csv_path = Path("watched_folder/data.csv")
81
+ >>> CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path=csv_path.parent, every=10)
82
+
83
+ >>> with csv_path.open("a") as f:
84
+ ... f.write("first line")
85
+
86
+ # Some time later (...)
87
+ >>> with csv_path.open("a") as f:
88
+ ... f.write("second line")
89
+ ```
90
+
91
+ Example using a context manager:
92
+ ```py
93
+ >>> from pathlib import Path
94
+ >>> from huggingface_hub import CommitScheduler
95
+
96
+ >>> with CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path="watched_folder", every=10) as scheduler:
97
+ ... csv_path = Path("watched_folder/data.csv")
98
+ ... with csv_path.open("a") as f:
99
+ ... f.write("first line")
100
+ ... (...)
101
+ ... with csv_path.open("a") as f:
102
+ ... f.write("second line")
103
+
104
+ # Scheduler is now stopped and last commit have been triggered
105
+ ```
106
+ """
107
+
108
+ def __init__(
109
+ self,
110
+ *,
111
+ repo_id: str,
112
+ folder_path: Union[str, Path],
113
+ every: Union[int, float] = 5,
114
+ path_in_repo: Optional[str] = None,
115
+ repo_type: Optional[str] = None,
116
+ revision: Optional[str] = None,
117
+ private: Optional[bool] = None,
118
+ token: Optional[str] = None,
119
+ allow_patterns: Optional[Union[List[str], str]] = None,
120
+ ignore_patterns: Optional[Union[List[str], str]] = None,
121
+ squash_history: bool = False,
122
+ hf_api: Optional["HfApi"] = None,
123
+ on_before_commit: Optional[Callable[[], None]] = None,
124
+ ) -> None:
125
+ self.api = hf_api or HfApi(token=token)
126
+ self.on_before_commit = on_before_commit
127
+
128
+ # Folder
129
+ self.folder_path = Path(folder_path).expanduser().resolve()
130
+ self.path_in_repo = path_in_repo or ""
131
+ self.allow_patterns = allow_patterns
132
+
133
+ if ignore_patterns is None:
134
+ ignore_patterns = []
135
+ elif isinstance(ignore_patterns, str):
136
+ ignore_patterns = [ignore_patterns]
137
+ self.ignore_patterns = ignore_patterns + DEFAULT_IGNORE_PATTERNS
138
+
139
+ if self.folder_path.is_file():
140
+ raise ValueError(
141
+ f"'folder_path' must be a directory, not a file: '{self.folder_path}'."
142
+ )
143
+ self.folder_path.mkdir(parents=True, exist_ok=True)
144
+
145
+ # Repository
146
+ repo_url = self.api.create_repo(
147
+ repo_id=repo_id, private=private, repo_type=repo_type, exist_ok=True
148
+ )
149
+ self.repo_id = repo_url.repo_id
150
+ self.repo_type = repo_type
151
+ self.revision = revision
152
+ self.token = token
153
+
154
+ self.last_uploaded: Dict[Path, float] = {}
155
+ self.last_push_time: float | None = None
156
+
157
+ if not every > 0:
158
+ raise ValueError(f"'every' must be a positive integer, not '{every}'.")
159
+ self.lock = Lock()
160
+ self.every = every
161
+ self.squash_history = squash_history
162
+
163
+ logger.info(
164
+ f"Scheduled job to push '{self.folder_path}' to '{self.repo_id}' every {self.every} minutes."
165
+ )
166
+ self._scheduler_thread = Thread(target=self._run_scheduler, daemon=True)
167
+ self._scheduler_thread.start()
168
+ atexit.register(self._push_to_hub)
169
+
170
+ self.__stopped = False
171
+
172
+ def stop(self) -> None:
173
+ """Stop the scheduler.
174
+
175
+ A stopped scheduler cannot be restarted. Mostly for tests purposes.
176
+ """
177
+ self.__stopped = True
178
+
179
+ def __enter__(self) -> "CommitScheduler":
180
+ return self
181
+
182
+ def __exit__(self, exc_type, exc_value, traceback) -> None:
183
+ # Upload last changes before exiting
184
+ self.trigger().result()
185
+ self.stop()
186
+ return
187
+
188
+ def _run_scheduler(self) -> None:
189
+ """Dumb thread waiting between each scheduled push to Hub."""
190
+ while True:
191
+ self.last_future = self.trigger()
192
+ time.sleep(self.every * 60)
193
+ if self.__stopped:
194
+ break
195
+
196
+ def trigger(self) -> Future:
197
+ """Trigger a `push_to_hub` and return a future.
198
+
199
+ This method is automatically called every `every` minutes. You can also call it manually to trigger a commit
200
+ immediately, without waiting for the next scheduled commit.
201
+ """
202
+ return self.api.run_as_future(self._push_to_hub)
203
+
204
+ def _push_to_hub(self) -> Optional[CommitInfo]:
205
+ if self.__stopped: # If stopped, already scheduled commits are ignored
206
+ return None
207
+
208
+ logger.info("(Background) scheduled commit triggered.")
209
+ try:
210
+ value = self.push_to_hub()
211
+ if self.squash_history:
212
+ logger.info("(Background) squashing repo history.")
213
+ self.api.super_squash_history(
214
+ repo_id=self.repo_id, repo_type=self.repo_type, branch=self.revision
215
+ )
216
+ return value
217
+ except Exception as e:
218
+ logger.error(
219
+ f"Error while pushing to Hub: {e}"
220
+ ) # Depending on the setup, error might be silenced
221
+ raise
222
+
223
+ def push_to_hub(self) -> Optional[CommitInfo]:
224
+ """
225
+ Push folder to the Hub and return the commit info.
226
+
227
+ <Tip warning={true}>
228
+
229
+ This method is not meant to be called directly. It is run in the background by the scheduler, respecting a
230
+ queue mechanism to avoid concurrent commits. Making a direct call to the method might lead to concurrency
231
+ issues.
232
+
233
+ </Tip>
234
+
235
+ The default behavior of `push_to_hub` is to assume an append-only folder. It lists all files in the folder and
236
+ uploads only changed files. If no changes are found, the method returns without committing anything. If you want
237
+ to change this behavior, you can inherit from [`CommitScheduler`] and override this method. This can be useful
238
+ for example to compress data together in a single file before committing. For more details and examples, check
239
+ out our [integration guide](https://huggingface.co/docs/huggingface_hub/main/en/guides/upload#scheduled-uploads).
240
+ """
241
+ # Check files to upload (with lock)
242
+ with self.lock:
243
+ if self.on_before_commit is not None:
244
+ self.on_before_commit()
245
+
246
+ logger.debug("Listing files to upload for scheduled commit.")
247
+
248
+ # List files from folder (taken from `_prepare_upload_folder_additions`)
249
+ relpath_to_abspath = {
250
+ path.relative_to(self.folder_path).as_posix(): path
251
+ for path in sorted(
252
+ self.folder_path.glob("**/*")
253
+ ) # sorted to be deterministic
254
+ if path.is_file()
255
+ }
256
+ prefix = f"{self.path_in_repo.strip('/')}/" if self.path_in_repo else ""
257
+
258
+ # Filter with pattern + filter out unchanged files + retrieve current file size
259
+ files_to_upload: List[_FileToUpload] = []
260
+ for relpath in filter_repo_objects(
261
+ relpath_to_abspath.keys(),
262
+ allow_patterns=self.allow_patterns,
263
+ ignore_patterns=self.ignore_patterns,
264
+ ):
265
+ local_path = relpath_to_abspath[relpath]
266
+ stat = local_path.stat()
267
+ if (
268
+ self.last_uploaded.get(local_path) is None
269
+ or self.last_uploaded[local_path] != stat.st_mtime
270
+ ):
271
+ files_to_upload.append(
272
+ _FileToUpload(
273
+ local_path=local_path,
274
+ path_in_repo=prefix + relpath,
275
+ size_limit=stat.st_size,
276
+ last_modified=stat.st_mtime,
277
+ )
278
+ )
279
+
280
+ # Return if nothing to upload
281
+ if len(files_to_upload) == 0:
282
+ logger.debug("Dropping schedule commit: no changed file to upload.")
283
+ return None
284
+
285
+ # Convert `_FileToUpload` as `CommitOperationAdd` (=> compute file shas + limit to file size)
286
+ logger.debug("Removing unchanged files since previous scheduled commit.")
287
+ add_operations = [
288
+ CommitOperationAdd(
289
+ # TODO: Cap the file to its current size, even if the user append data to it while a scheduled commit is happening
290
+ # (requires an upstream fix for XET-535: `hf_xet` should support `BinaryIO` for upload)
291
+ path_or_fileobj=file_to_upload.local_path,
292
+ path_in_repo=file_to_upload.path_in_repo,
293
+ )
294
+ for file_to_upload in files_to_upload
295
+ ]
296
+
297
+ # Upload files (append mode expected - no need for lock)
298
+ logger.debug("Uploading files for scheduled commit.")
299
+ commit_info = self.api.create_commit(
300
+ repo_id=self.repo_id,
301
+ repo_type=self.repo_type,
302
+ operations=add_operations,
303
+ commit_message="Scheduled Commit",
304
+ revision=self.revision,
305
+ )
306
+
307
+ for file in files_to_upload:
308
+ self.last_uploaded[file.local_path] = file.last_modified
309
+
310
+ self.last_push_time = time.time()
311
+
312
+ return commit_info
313
+
314
+
315
+ class PartialFileIO(BytesIO):
316
+ """A file-like object that reads only the first part of a file.
317
+
318
+ Useful to upload a file to the Hub when the user might still be appending data to it. Only the first part of the
319
+ file is uploaded (i.e. the part that was available when the filesystem was first scanned).
320
+
321
+ In practice, only used internally by the CommitScheduler to regularly push a folder to the Hub with minimal
322
+ disturbance for the user. The object is passed to `CommitOperationAdd`.
323
+
324
+ Only supports `read`, `tell` and `seek` methods.
325
+
326
+ Args:
327
+ file_path (`str` or `Path`):
328
+ Path to the file to read.
329
+ size_limit (`int`):
330
+ The maximum number of bytes to read from the file. If the file is larger than this, only the first part
331
+ will be read (and uploaded).
332
+ """
333
+
334
+ def __init__(self, file_path: Union[str, Path], size_limit: int) -> None:
335
+ self._file_path = Path(file_path)
336
+ self._file = self._file_path.open("rb")
337
+ self._size_limit = min(size_limit, os.fstat(self._file.fileno()).st_size)
338
+
339
+ def __del__(self) -> None:
340
+ self._file.close()
341
+ return super().__del__()
342
+
343
+ def __repr__(self) -> str:
344
+ return (
345
+ f"<PartialFileIO file_path={self._file_path} size_limit={self._size_limit}>"
346
+ )
347
+
348
+ def __len__(self) -> int:
349
+ return self._size_limit
350
+
351
+ def __getattribute__(self, name: str):
352
+ if name.startswith("_") or name in (
353
+ "read",
354
+ "tell",
355
+ "seek",
356
+ ): # only 3 public methods supported
357
+ return super().__getattribute__(name)
358
+ raise NotImplementedError(f"PartialFileIO does not support '{name}'.")
359
+
360
+ def tell(self) -> int:
361
+ """Return the current file position."""
362
+ return self._file.tell()
363
+
364
+ def seek(self, __offset: int, __whence: int = SEEK_SET) -> int:
365
+ """Change the stream position to the given offset.
366
+
367
+ Behavior is the same as a regular file, except that the position is capped to the size limit.
368
+ """
369
+ if __whence == SEEK_END:
370
+ # SEEK_END => set from the truncated end
371
+ __offset = len(self) + __offset
372
+ __whence = SEEK_SET
373
+
374
+ pos = self._file.seek(__offset, __whence)
375
+ if pos > self._size_limit:
376
+ return self._file.seek(self._size_limit)
377
+ return pos
378
+
379
+ def read(self, __size: Optional[int] = -1) -> bytes:
380
+ """Read at most `__size` bytes from the file.
381
+
382
+ Behavior is the same as a regular file, except that it is capped to the size limit.
383
+ """
384
+ current = self._file.tell()
385
+ if __size is None or __size < 0:
386
+ # Read until file limit
387
+ truncated_size = self._size_limit - current
388
+ else:
389
+ # Read until file limit or __size
390
+ truncated_size = min(__size, self._size_limit - current)
391
+ return self._file.read(truncated_size)
context_vars.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextvars
2
+ from typing import TYPE_CHECKING
3
+
4
+ if TYPE_CHECKING:
5
+ from trackio.run import Run
6
+
7
+ current_run: contextvars.ContextVar["Run | None"] = contextvars.ContextVar(
8
+ "current_run", default=None
9
+ )
10
+ current_project: contextvars.ContextVar[str | None] = contextvars.ContextVar(
11
+ "current_project", default=None
12
+ )
13
+ current_server: contextvars.ContextVar[str | None] = contextvars.ContextVar(
14
+ "current_server", default=None
15
+ )
deploy.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import os
3
+ import time
4
+ from importlib.resources import files
5
+ from pathlib import Path
6
+
7
+ import gradio
8
+ import huggingface_hub
9
+ from gradio_client import Client, handle_file
10
+ from httpx import ReadTimeout
11
+ from huggingface_hub.errors import RepositoryNotFoundError
12
+ from requests import HTTPError
13
+
14
+ from trackio.sqlite_storage import SQLiteStorage
15
+
16
+ SPACE_URL = "https://huggingface.co/spaces/{space_id}"
17
+ PERSISTENT_STORAGE_DIR = "/data/.huggingface/trackio"
18
+
19
+
20
+ def deploy_as_space(
21
+ space_id: str,
22
+ dataset_id: str | None = None,
23
+ ):
24
+ if (
25
+ os.getenv("SYSTEM") == "spaces"
26
+ ): # in case a repo with this function is uploaded to spaces
27
+ return
28
+
29
+ trackio_path = files("trackio")
30
+
31
+ hf_api = huggingface_hub.HfApi()
32
+
33
+ try:
34
+ huggingface_hub.create_repo(
35
+ space_id,
36
+ space_sdk="gradio",
37
+ repo_type="space",
38
+ exist_ok=True,
39
+ )
40
+ except HTTPError as e:
41
+ if e.response.status_code in [401, 403]: # unauthorized or forbidden
42
+ print("Need 'write' access token to create a Spaces repo.")
43
+ huggingface_hub.login(add_to_git_credential=False)
44
+ huggingface_hub.create_repo(
45
+ space_id,
46
+ space_sdk="gradio",
47
+ repo_type="space",
48
+ exist_ok=True,
49
+ )
50
+ else:
51
+ raise ValueError(f"Failed to create Space: {e}")
52
+
53
+ with open(Path(trackio_path, "README.md"), "r") as f:
54
+ readme_content = f.read()
55
+ readme_content = readme_content.replace("{GRADIO_VERSION}", gradio.__version__)
56
+ readme_buffer = io.BytesIO(readme_content.encode("utf-8"))
57
+ hf_api.upload_file(
58
+ path_or_fileobj=readme_buffer,
59
+ path_in_repo="README.md",
60
+ repo_id=space_id,
61
+ repo_type="space",
62
+ )
63
+
64
+ # We can assume pandas, gradio, and huggingface-hub are already installed in a Gradio Space.
65
+ # Make sure necessary dependencies are installed by creating a requirements.txt.
66
+ requirements_content = """
67
+ pyarrow>=21.0
68
+ mediapy>=1.0.0
69
+ """
70
+ requirements_buffer = io.BytesIO(requirements_content.encode("utf-8"))
71
+ hf_api.upload_file(
72
+ path_or_fileobj=requirements_buffer,
73
+ path_in_repo="requirements.txt",
74
+ repo_id=space_id,
75
+ repo_type="space",
76
+ )
77
+
78
+ huggingface_hub.utils.disable_progress_bars()
79
+ hf_api.upload_folder(
80
+ repo_id=space_id,
81
+ repo_type="space",
82
+ folder_path=trackio_path,
83
+ ignore_patterns=["README.md"],
84
+ )
85
+
86
+ huggingface_hub.add_space_variable(space_id, "TRACKIO_DIR", PERSISTENT_STORAGE_DIR)
87
+ if hf_token := huggingface_hub.utils.get_token():
88
+ huggingface_hub.add_space_secret(space_id, "HF_TOKEN", hf_token)
89
+ if dataset_id is not None:
90
+ huggingface_hub.add_space_variable(space_id, "TRACKIO_DATASET_ID", dataset_id)
91
+
92
+
93
+ def create_space_if_not_exists(
94
+ space_id: str,
95
+ dataset_id: str | None = None,
96
+ ) -> None:
97
+ """
98
+ Creates a new Hugging Face Space if it does not exist. If a dataset_id is provided, it will be added as a space variable.
99
+
100
+ Args:
101
+ space_id: The ID of the Space to create.
102
+ dataset_id: The ID of the Dataset to add to the Space.
103
+ """
104
+ if "/" not in space_id:
105
+ raise ValueError(
106
+ f"Invalid space ID: {space_id}. Must be in the format: username/reponame or orgname/reponame."
107
+ )
108
+ if dataset_id is not None and "/" not in dataset_id:
109
+ raise ValueError(
110
+ f"Invalid dataset ID: {dataset_id}. Must be in the format: username/datasetname or orgname/datasetname."
111
+ )
112
+ try:
113
+ # huggingface_hub.repo_info(space_id, repo_type="space")
114
+ # print(f"* Found existing space: {SPACE_URL.format(space_id=space_id)}")
115
+ # if dataset_id is not None:
116
+ # huggingface_hub.add_space_variable(
117
+ # space_id, "TRACKIO_DATASET_ID", dataset_id
118
+ # )
119
+ # return
120
+ raise RepositoryNotFoundError("Space not found")
121
+ except RepositoryNotFoundError:
122
+ pass
123
+ except HTTPError as e:
124
+ if e.response.status_code in [401, 403]: # unauthorized or forbidden
125
+ print("Need 'write' access token to create a Spaces repo.")
126
+ huggingface_hub.login(add_to_git_credential=False)
127
+ huggingface_hub.add_space_variable(
128
+ space_id, "TRACKIO_DATASET_ID", dataset_id
129
+ )
130
+ else:
131
+ raise ValueError(f"Failed to create Space: {e}")
132
+
133
+ print(f"* Creating new space: {SPACE_URL.format(space_id=space_id)}")
134
+ deploy_as_space(space_id, dataset_id)
135
+
136
+
137
+ def wait_until_space_exists(
138
+ space_id: str,
139
+ ) -> None:
140
+ """
141
+ Blocks the current thread until the space exists.
142
+ May raise a TimeoutError if this takes quite a while.
143
+
144
+ Args:
145
+ space_id: The ID of the Space to wait for.
146
+ """
147
+ delay = 1
148
+ for _ in range(10):
149
+ try:
150
+ Client(space_id, verbose=False)
151
+ return
152
+ except (ReadTimeout, ValueError):
153
+ time.sleep(delay)
154
+ delay = min(delay * 2, 30)
155
+ raise TimeoutError("Waiting for space to exist took longer than expected")
156
+
157
+
158
+ def upload_db_to_space(project: str, space_id: str) -> None:
159
+ """
160
+ Uploads the database of a local Trackio project to a Hugging Face Space.
161
+
162
+ Args:
163
+ project: The name of the project to upload.
164
+ space_id: The ID of the Space to upload to.
165
+ """
166
+ db_path = SQLiteStorage.get_project_db_path(project)
167
+ client = Client(space_id, verbose=False)
168
+ client.predict(
169
+ api_name="/upload_db_to_space",
170
+ project=project,
171
+ uploaded_db=handle_file(db_path),
172
+ hf_token=huggingface_hub.utils.get_token(),
173
+ )
dummy_commit_scheduler.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # A dummy object to fit the interface of huggingface_hub's CommitScheduler
2
+ class DummyCommitSchedulerLock:
3
+ def __enter__(self):
4
+ return None
5
+
6
+ def __exit__(self, exception_type, exception_value, exception_traceback):
7
+ pass
8
+
9
+
10
+ class DummyCommitScheduler:
11
+ def __init__(self):
12
+ self.lock = DummyCommitSchedulerLock()
file_storage.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+
4
+ from PIL import Image as PILImage
5
+
6
+ try: # absolute imports when installed
7
+ from trackio.utils import TRACKIO_DIR, get_space
8
+ except ImportError: # relative imports for local execution on Spaces
9
+ from utils import TRACKIO_DIR, get_space
10
+
11
+
12
+ class FileStorage:
13
+ @staticmethod
14
+ def get_base_path() -> Path:
15
+ if get_space() is not None:
16
+ return Path("/home/user/app")
17
+ return TRACKIO_DIR
18
+
19
+ @staticmethod
20
+ def get_project_media_path(
21
+ project: str,
22
+ run: str | None = None,
23
+ step: int | None = None,
24
+ filename: str | None = None,
25
+ ) -> Path:
26
+ if filename is not None and step is None:
27
+ raise ValueError("filename requires step")
28
+ if step is not None and run is None:
29
+ raise ValueError("step requires run")
30
+
31
+ path = FileStorage.get_base_path() / "media" / project
32
+ if run:
33
+ path /= run
34
+ if step is not None:
35
+ path /= str(step)
36
+ if filename:
37
+ path /= filename
38
+ return path
39
+
40
+ @staticmethod
41
+ def init_project_media_path(
42
+ project: str, run: str | None = None, step: int | None = None
43
+ ) -> Path:
44
+ path = FileStorage.get_project_media_path(project, run, step)
45
+ path.mkdir(parents=True, exist_ok=True)
46
+ FileStorage.maybe_create_media_symlink()
47
+ return path
48
+
49
+ @staticmethod
50
+ def save_image(
51
+ image: PILImage.Image,
52
+ project: str,
53
+ run: str,
54
+ step: int,
55
+ filename: str,
56
+ format: str = "PNG",
57
+ ) -> Path:
58
+ path = FileStorage.init_project_media_path(project, run, step) / filename
59
+ image.save(path, format=format)
60
+ return path
61
+
62
+ @staticmethod
63
+ def get_image(project: str, run: str, step: int, filename: str) -> PILImage.Image:
64
+ path = FileStorage.get_project_media_path(project, run, step, filename)
65
+ if not path.exists():
66
+ raise FileNotFoundError(f"Image file not found: {path}")
67
+ return PILImage.open(path).convert("RGBA")
68
+
69
+ @staticmethod
70
+ def maybe_create_media_symlink() -> None:
71
+ if get_space() and not (TRACKIO_DIR / "media").exists():
72
+ os.symlink(FileStorage.get_base_path() / "media", TRACKIO_DIR / "media")
imports.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+
4
+ import pandas as pd
5
+
6
+ from trackio import deploy, utils
7
+ from trackio.sqlite_storage import SQLiteStorage
8
+
9
+
10
+ def import_csv(
11
+ csv_path: str | Path,
12
+ project: str,
13
+ name: str | None = None,
14
+ space_id: str | None = None,
15
+ dataset_id: str | None = None,
16
+ ) -> None:
17
+ """
18
+ Imports a CSV file into a Trackio project. The CSV file must contain a `"step"`
19
+ column, may optionally contain a `"timestamp"` column, and any other columns will be
20
+ treated as metrics. It should also include a header row with the column names.
21
+
22
+ TODO: call init() and return a Run object so that the user can continue to log metrics to it.
23
+
24
+ Args:
25
+ csv_path (`str` or `Path`):
26
+ The str or Path to the CSV file to import.
27
+ project (`str`):
28
+ The name of the project to import the CSV file into. Must not be an existing
29
+ project.
30
+ name (`str` or `None`, *optional*, defaults to `None`):
31
+ The name of the Run to import the CSV file into. If not provided, a default
32
+ name will be generated.
33
+ name (`str` or `None`, *optional*, defaults to `None`):
34
+ The name of the run (if not provided, a default name will be generated).
35
+ space_id (`str` or `None`, *optional*, defaults to `None`):
36
+ If provided, the project will be logged to a Hugging Face Space instead of a
37
+ local directory. Should be a complete Space name like `"username/reponame"`
38
+ or `"orgname/reponame"`, or just `"reponame"` in which case the Space will
39
+ be created in the currently-logged-in Hugging Face user's namespace. If the
40
+ Space does not exist, it will be created. If the Space already exists, the
41
+ project will be logged to it.
42
+ dataset_id (`str` or `None`, *optional*, defaults to `None`):
43
+ If provided, a persistent Hugging Face Dataset will be created and the
44
+ metrics will be synced to it every 5 minutes. Should be a complete Dataset
45
+ name like `"username/datasetname"` or `"orgname/datasetname"`, or just
46
+ `"datasetname"` in which case the Dataset will be created in the
47
+ currently-logged-in Hugging Face user's namespace. If the Dataset does not
48
+ exist, it will be created. If the Dataset already exists, the project will
49
+ be appended to it. If not provided, the metrics will be logged to a local
50
+ SQLite database, unless a `space_id` is provided, in which case a Dataset
51
+ will be automatically created with the same name as the Space but with the
52
+ `"_dataset"` suffix.
53
+ """
54
+ if SQLiteStorage.get_runs(project):
55
+ raise ValueError(
56
+ f"Project '{project}' already exists. Cannot import CSV into existing project."
57
+ )
58
+
59
+ csv_path = Path(csv_path)
60
+ if not csv_path.exists():
61
+ raise FileNotFoundError(f"CSV file not found: {csv_path}")
62
+
63
+ df = pd.read_csv(csv_path)
64
+ if df.empty:
65
+ raise ValueError("CSV file is empty")
66
+
67
+ column_mapping = utils.simplify_column_names(df.columns.tolist())
68
+ df = df.rename(columns=column_mapping)
69
+
70
+ step_column = None
71
+ for col in df.columns:
72
+ if col.lower() == "step":
73
+ step_column = col
74
+ break
75
+
76
+ if step_column is None:
77
+ raise ValueError("CSV file must contain a 'step' or 'Step' column")
78
+
79
+ if name is None:
80
+ name = csv_path.stem
81
+
82
+ metrics_list = []
83
+ steps = []
84
+ timestamps = []
85
+
86
+ numeric_columns = []
87
+ for column in df.columns:
88
+ if column == step_column:
89
+ continue
90
+ if column == "timestamp":
91
+ continue
92
+
93
+ try:
94
+ pd.to_numeric(df[column], errors="raise")
95
+ numeric_columns.append(column)
96
+ except (ValueError, TypeError):
97
+ continue
98
+
99
+ for _, row in df.iterrows():
100
+ metrics = {}
101
+ for column in numeric_columns:
102
+ value = row[column]
103
+ if bool(pd.notna(value)):
104
+ metrics[column] = float(value)
105
+
106
+ if metrics:
107
+ metrics_list.append(metrics)
108
+ steps.append(int(row[step_column]))
109
+
110
+ if "timestamp" in df.columns and bool(pd.notna(row["timestamp"])):
111
+ timestamps.append(str(row["timestamp"]))
112
+ else:
113
+ timestamps.append("")
114
+
115
+ if metrics_list:
116
+ SQLiteStorage.bulk_log(
117
+ project=project,
118
+ run=name,
119
+ metrics_list=metrics_list,
120
+ steps=steps,
121
+ timestamps=timestamps,
122
+ )
123
+
124
+ print(
125
+ f"* Imported {len(metrics_list)} rows from {csv_path} into project '{project}' as run '{name}'"
126
+ )
127
+ print(f"* Metrics found: {', '.join(metrics_list[0].keys())}")
128
+
129
+ space_id, dataset_id = utils.preprocess_space_and_dataset_ids(space_id, dataset_id)
130
+ if dataset_id is not None:
131
+ os.environ["TRACKIO_DATASET_ID"] = dataset_id
132
+ print(f"* Trackio metrics will be synced to Hugging Face Dataset: {dataset_id}")
133
+
134
+ if space_id is None:
135
+ utils.print_dashboard_instructions(project)
136
+ else:
137
+ deploy.create_space_if_not_exists(space_id, dataset_id)
138
+ deploy.wait_until_space_exists(space_id)
139
+ deploy.upload_db_to_space(project, space_id)
140
+ print(
141
+ f"* View dashboard by going to: {deploy.SPACE_URL.format(space_id=space_id)}"
142
+ )
143
+
144
+
145
+ def import_tf_events(
146
+ log_dir: str | Path,
147
+ project: str,
148
+ name: str | None = None,
149
+ space_id: str | None = None,
150
+ dataset_id: str | None = None,
151
+ ) -> None:
152
+ """
153
+ Imports TensorFlow Events files from a directory into a Trackio project. Each
154
+ subdirectory in the log directory will be imported as a separate run.
155
+
156
+ Args:
157
+ log_dir (`str` or `Path`):
158
+ The str or Path to the directory containing TensorFlow Events files.
159
+ project (`str`):
160
+ The name of the project to import the TensorFlow Events files into. Must not
161
+ be an existing project.
162
+ name (`str` or `None`, *optional*, defaults to `None`):
163
+ The name prefix for runs (if not provided, will use directory names). Each
164
+ subdirectory will create a separate run.
165
+ space_id (`str` or `None`, *optional*, defaults to `None`):
166
+ If provided, the project will be logged to a Hugging Face Space instead of a
167
+ local directory. Should be a complete Space name like `"username/reponame"`
168
+ or `"orgname/reponame"`, or just `"reponame"` in which case the Space will
169
+ be created in the currently-logged-in Hugging Face user's namespace. If the
170
+ Space does not exist, it will be created. If the Space already exists, the
171
+ project will be logged to it.
172
+ dataset_id (`str` or `None`, *optional*, defaults to `None`):
173
+ If provided, a persistent Hugging Face Dataset will be created and the
174
+ metrics will be synced to it every 5 minutes. Should be a complete Dataset
175
+ name like `"username/datasetname"` or `"orgname/datasetname"`, or just
176
+ `"datasetname"` in which case the Dataset will be created in the
177
+ currently-logged-in Hugging Face user's namespace. If the Dataset does not
178
+ exist, it will be created. If the Dataset already exists, the project will
179
+ be appended to it. If not provided, the metrics will be logged to a local
180
+ SQLite database, unless a `space_id` is provided, in which case a Dataset
181
+ will be automatically created with the same name as the Space but with the
182
+ `"_dataset"` suffix.
183
+ """
184
+ try:
185
+ from tbparse import SummaryReader
186
+ except ImportError:
187
+ raise ImportError(
188
+ "The `tbparse` package is not installed but is required for `import_tf_events`. Please install trackio with the `tensorboard` extra: `pip install trackio[tensorboard]`."
189
+ )
190
+
191
+ if SQLiteStorage.get_runs(project):
192
+ raise ValueError(
193
+ f"Project '{project}' already exists. Cannot import TF events into existing project."
194
+ )
195
+
196
+ path = Path(log_dir)
197
+ if not path.exists():
198
+ raise FileNotFoundError(f"TF events directory not found: {path}")
199
+
200
+ # Use tbparse to read all tfevents files in the directory structure
201
+ reader = SummaryReader(str(path), extra_columns={"dir_name"})
202
+ df = reader.scalars
203
+
204
+ if df.empty:
205
+ raise ValueError(f"No TensorFlow events data found in {path}")
206
+
207
+ total_imported = 0
208
+ imported_runs = []
209
+
210
+ # Group by dir_name to create separate runs
211
+ for dir_name, group_df in df.groupby("dir_name"):
212
+ try:
213
+ # Determine run name based on directory name
214
+ if dir_name == "":
215
+ run_name = "main" # For files in the root directory
216
+ else:
217
+ run_name = dir_name # Use directory name
218
+
219
+ if name:
220
+ run_name = f"{name}_{run_name}"
221
+
222
+ if group_df.empty:
223
+ print(f"* Skipping directory {dir_name}: no scalar data found")
224
+ continue
225
+
226
+ metrics_list = []
227
+ steps = []
228
+ timestamps = []
229
+
230
+ for _, row in group_df.iterrows():
231
+ # Convert row values to appropriate types
232
+ tag = str(row["tag"])
233
+ value = float(row["value"])
234
+ step = int(row["step"])
235
+
236
+ metrics = {tag: value}
237
+ metrics_list.append(metrics)
238
+ steps.append(step)
239
+
240
+ # Use wall_time if present, else fallback
241
+ if "wall_time" in group_df.columns and not bool(
242
+ pd.isna(row["wall_time"])
243
+ ):
244
+ timestamps.append(str(row["wall_time"]))
245
+ else:
246
+ timestamps.append("")
247
+
248
+ if metrics_list:
249
+ SQLiteStorage.bulk_log(
250
+ project=project,
251
+ run=str(run_name),
252
+ metrics_list=metrics_list,
253
+ steps=steps,
254
+ timestamps=timestamps,
255
+ )
256
+
257
+ total_imported += len(metrics_list)
258
+ imported_runs.append(run_name)
259
+
260
+ print(
261
+ f"* Imported {len(metrics_list)} scalar events from directory '{dir_name}' as run '{run_name}'"
262
+ )
263
+ print(f"* Metrics in this run: {', '.join(set(group_df['tag']))}")
264
+
265
+ except Exception as e:
266
+ print(f"* Error processing directory {dir_name}: {e}")
267
+ continue
268
+
269
+ if not imported_runs:
270
+ raise ValueError("No valid TensorFlow events data could be imported")
271
+
272
+ print(f"* Total imported events: {total_imported}")
273
+ print(f"* Created runs: {', '.join(imported_runs)}")
274
+
275
+ space_id, dataset_id = utils.preprocess_space_and_dataset_ids(space_id, dataset_id)
276
+ if dataset_id is not None:
277
+ os.environ["TRACKIO_DATASET_ID"] = dataset_id
278
+ print(f"* Trackio metrics will be synced to Hugging Face Dataset: {dataset_id}")
279
+
280
+ if space_id is None:
281
+ utils.print_dashboard_instructions(project)
282
+ else:
283
+ deploy.create_space_if_not_exists(space_id, dataset_id)
284
+ deploy.wait_until_space_exists(space_id)
285
+ deploy.upload_db_to_space(project, space_id)
286
+ print(
287
+ f"* View dashboard by going to: {deploy.SPACE_URL.format(space_id=space_id)}"
288
+ )
media.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ from threading import local
4
+ import uuid
5
+ from pathlib import Path
6
+ from typing import Literal
7
+
8
+ import numpy as np
9
+ from PIL import Image as PILImage
10
+ import mediapy as mp
11
+
12
+
13
+ try: # absolute imports when installed
14
+ from trackio.file_storage import FileStorage
15
+ from trackio.utils import TRACKIO_DIR
16
+ except ImportError: # relative imports for local execution on Spaces
17
+ from file_storage import FileStorage
18
+ from utils import TRACKIO_DIR
19
+
20
+ class TrackioImage:
21
+ """
22
+ Creates an image that can be logged with trackio.
23
+
24
+ Demo: fake-training-images
25
+ """
26
+
27
+ TYPE = "trackio.image"
28
+
29
+ def __init__(
30
+ self, value: str | np.ndarray | PILImage.Image, caption: str | None = None
31
+ ):
32
+ """
33
+ Parameters:
34
+ value: A string path to an image, a numpy array, or a PIL Image.
35
+ caption: A string caption for the image.
36
+ """
37
+ self.caption = caption
38
+ self._pil = TrackioImage._as_pil(value)
39
+ self._file_path: Path | None = None
40
+ self._file_format: str | None = None
41
+
42
+ @staticmethod
43
+ def _as_pil(value: str | np.ndarray | PILImage.Image) -> PILImage.Image:
44
+ try:
45
+ if isinstance(value, str):
46
+ return PILImage.open(value).convert("RGBA")
47
+ elif isinstance(value, np.ndarray):
48
+ arr = np.asarray(value).astype("uint8")
49
+ return PILImage.fromarray(arr).convert("RGBA")
50
+ elif isinstance(value, PILImage.Image):
51
+ return value.convert("RGBA")
52
+ except Exception as e:
53
+ raise ValueError(f"Failed to process image data: {value}") from e
54
+
55
+ def _save(self, project: str, run: str, step: int = 0, format: str = "PNG") -> str:
56
+ if not self._file_path:
57
+ # Save image as {TRACKIO_DIR}/media/{project}/{run}/{step}/{uuid}.{ext}
58
+ filename = f"{uuid.uuid4()}.{format.lower()}"
59
+ path = FileStorage.save_image(
60
+ self._pil, project, run, step, filename, format=format
61
+ )
62
+ self._file_path = path.relative_to(TRACKIO_DIR)
63
+ self._file_format = format
64
+ return str(self._file_path)
65
+
66
+ def _get_relative_file_path(self) -> Path | None:
67
+ return self._file_path
68
+
69
+ def _get_absolute_file_path(self) -> Path | None:
70
+ return TRACKIO_DIR / self._file_path
71
+
72
+ def _to_dict(self) -> dict:
73
+ if not self._file_path:
74
+ raise ValueError("Image must be saved to file before serialization")
75
+ return {
76
+ "_type": self.TYPE,
77
+ "file_path": str(self._get_relative_file_path()),
78
+ "file_format": self._file_format,
79
+ "caption": self.caption,
80
+ }
81
+
82
+ @classmethod
83
+ def _from_dict(cls, obj: dict) -> "TrackioImage":
84
+ if not isinstance(obj, dict):
85
+ raise TypeError(f"Expected dict, got {type(obj).__name__}")
86
+ if obj.get("_type") != cls.TYPE:
87
+ raise ValueError(f"Wrong _type: {obj.get('_type')!r}")
88
+
89
+ file_path = obj.get("file_path")
90
+ if not isinstance(file_path, str):
91
+ raise TypeError(
92
+ f"'file_path' must be string, got {type(file_path).__name__}"
93
+ )
94
+
95
+ absolute_path = TRACKIO_DIR / file_path
96
+ try:
97
+ if not absolute_path.is_file():
98
+ raise ValueError(f"Image file not found: {file_path}")
99
+ pil = PILImage.open(absolute_path).convert("RGBA")
100
+ instance = cls(pil, caption=obj.get("caption"))
101
+ instance._file_path = Path(file_path)
102
+ instance._file_format = obj.get("file_format")
103
+ return instance
104
+ except Exception as e:
105
+ raise ValueError(f"Failed to load image from file: {absolute_path}") from e
106
+
107
+ TrackioVideoSourceType = str | Path | np.ndarray
108
+ TrackioVideoFormatType = Literal["gif", "mp4", "webm", "ogg"]
109
+
110
+ class TrackioVideo:
111
+ """
112
+ Creates a video that can be logged with trackio.
113
+
114
+ Demo: video-demo
115
+ """
116
+
117
+ TYPE = "trackio.video"
118
+
119
+ def __init__(self,
120
+ value: TrackioVideoSourceType,
121
+ caption: str | None = None,
122
+ fps: int | None = None,
123
+ format: TrackioVideoFormatType | None = None,
124
+ ):
125
+ self._value = value
126
+ self._caption = caption
127
+ self._fps = fps
128
+ self._format = format
129
+ self._file_path: Path | None = None
130
+
131
+ @property
132
+ def _codec(self) -> str | None:
133
+ match self._format:
134
+ case "gif":
135
+ return "gif"
136
+ case "mp4":
137
+ return "h264"
138
+ case "webm" | "ogg":
139
+ return "vp9"
140
+ case _:
141
+ return None
142
+
143
+ def _save(self, project: str, run: str, step: int = 0):
144
+ if self._file_path:
145
+ return
146
+
147
+ media_dir = FileStorage.init_project_media_path(project, run, step)
148
+ filename = f"{uuid.uuid4()}.{self._file_extension()}"
149
+ media_path = media_dir / filename
150
+ if isinstance(self._value, np.ndarray):
151
+ video = TrackioVideo._process_ndarray(self._value)
152
+ mp.write_video(media_path, video, fps=self._fps, codec=self._codec)
153
+ elif isinstance(self._value, str | Path):
154
+ if os.path.isfile(self._value):
155
+ shutil.copy(self._value, media_path)
156
+ else:
157
+ raise ValueError(f"File not found: {self._value}")
158
+ self._file_path = media_path.relative_to(TRACKIO_DIR)
159
+
160
+ def _get_absolute_file_path(self) -> Path | None:
161
+ return TRACKIO_DIR / self._file_path
162
+
163
+ def _file_extension(self) -> str:
164
+ if self._format is None:
165
+ if self._file_path is None:
166
+ raise ValueError("File format not specified and no file path provided")
167
+ return self._file_path.suffix[1:].lower()
168
+ return self._format
169
+
170
+ # def _gen_upload_file_path(self, project: str, run: str, step: int) -> Path:
171
+ # if self._upload_file_path:
172
+ # return self._upload_file_path
173
+ # filename = f"{uuid.uuid4()}.{self._file_extension()}"
174
+ # dir = FileStorage.init_project_media_path(project, run, step)
175
+ # return Path.home() / dir.relative_to(TRACKIO_DIR) / filename
176
+
177
+ @staticmethod
178
+ def _process_ndarray(value: np.ndarray) -> np.ndarray:
179
+ # Verify value is either 4D (single video) or 5D array (batched videos).
180
+ # Expected format: (frames, channels, height, width) for 4D or (batch, frames, channels, height, width) for 5D
181
+ if value.ndim < 4:
182
+ raise ValueError("Video requires at least 4 dimensions (frames, channels, height, width)")
183
+ if value.ndim > 5:
184
+ raise ValueError("Videos can have at most 5 dimensions (batch, frames, channels, height, width)")
185
+ if value.ndim == 4:
186
+ # Reshape to 5D with single batch: (1, frames, channels, height, width)
187
+ value = value[np.newaxis, ...]
188
+
189
+ value = TrackioVideo._tile_batched_videos(value)
190
+
191
+ # Convert final result from (F, H, W, C) to (F, C, H, W) for mediapy
192
+ value = np.transpose(value, (0, 3, 1, 2))
193
+
194
+ return value
195
+
196
+ @staticmethod
197
+ def _tile_batched_videos(video: np.ndarray) -> np.ndarray:
198
+ """
199
+ Tiles a batch of videos into a grid of videos.
200
+
201
+ Input format: (batch, frames, channels, height, width) - original FCHW format
202
+ Output format: (frames, total_height, total_width, channels)
203
+ """
204
+ batch_size, frames, channels, height, width = video.shape
205
+
206
+ next_pow2 = 1 << (batch_size - 1).bit_length()
207
+ if batch_size != next_pow2:
208
+ pad_len = next_pow2 - batch_size
209
+ pad_shape = (pad_len, frames, channels, height, width)
210
+ padding = np.zeros(pad_shape, dtype=video.dtype)
211
+ video = np.concatenate((video, padding), axis=0)
212
+ batch_size = next_pow2
213
+
214
+ n_rows = 1 << ((batch_size.bit_length() - 1) // 2)
215
+ n_cols = batch_size // n_rows
216
+
217
+ # Reshape to grid layout: (n_rows, n_cols, frames, channels, height, width)
218
+ video = video.reshape(n_rows, n_cols, frames, channels, height, width)
219
+
220
+ # Rearrange dimensions to (frames, total_height, total_width, channels)
221
+ video = video.transpose(2, 0, 4, 1, 5, 3)
222
+ video = video.reshape(frames, n_rows * height, n_cols * width, channels)
223
+ return video
224
+
225
+ def _to_dict(self) -> dict:
226
+ return {
227
+ "_type": self.TYPE,
228
+ "file_path": str(self._file_path),
229
+ "caption": self._caption,
230
+ }
py.typed ADDED
File without changes
run.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import threading
2
+ import time
3
+
4
+ import huggingface_hub
5
+ from gradio_client import Client, handle_file
6
+
7
+ from trackio.media import TrackioImage, TrackioVideo
8
+ from trackio.sqlite_storage import SQLiteStorage
9
+ from trackio.typehints import LogEntry, UploadEntry
10
+ from trackio.utils import RESERVED_KEYS, fibo, generate_readable_name
11
+
12
+ BATCH_SEND_INTERVAL = 0.5
13
+
14
+
15
+ class Run:
16
+ def __init__(
17
+ self,
18
+ url: str,
19
+ project: str,
20
+ client: Client | None,
21
+ name: str | None = None,
22
+ config: dict | None = None,
23
+ space_id: str | None = None,
24
+ ):
25
+ self.url = url
26
+ self.project = project
27
+ self._client_lock = threading.Lock()
28
+ self._client_thread = None
29
+ self._client = client
30
+ self._space_id = space_id
31
+ self.name = name or generate_readable_name(
32
+ SQLiteStorage.get_runs(project), space_id
33
+ )
34
+ self.config = config or {}
35
+ self._queued_logs: list[LogEntry] = []
36
+ self._queued_uploads: list[UploadEntry] = []
37
+ self._stop_flag = threading.Event()
38
+
39
+ self._client_thread = threading.Thread(target=self._init_client_background)
40
+ self._client_thread.daemon = True
41
+ self._client_thread.start()
42
+
43
+ def _batch_sender(self):
44
+ """Send batched logs every BATCH_SEND_INTERVAL."""
45
+ while not self._stop_flag.is_set() or len(self._queued_logs) > 0:
46
+ # If the stop flag has been set, then just quickly send all
47
+ # the logs and exit.
48
+ if not self._stop_flag.is_set():
49
+ time.sleep(BATCH_SEND_INTERVAL)
50
+
51
+ with self._client_lock:
52
+ if self._queued_logs and self._client is not None:
53
+ logs_to_send = self._queued_logs.copy()
54
+ self._queued_logs.clear()
55
+ self._client.predict(
56
+ api_name="/bulk_log",
57
+ logs=logs_to_send,
58
+ hf_token=huggingface_hub.utils.get_token(),
59
+ )
60
+ if self._queued_uploads and self._client is not None:
61
+ uploads_to_send = self._queued_uploads.copy()
62
+ self._queued_uploads.clear()
63
+ self._client.predict(
64
+ api_name="/bulk_upload_media",
65
+ uploads=uploads_to_send,
66
+ hf_token=huggingface_hub.utils.get_token(),
67
+ )
68
+
69
+ def _init_client_background(self):
70
+ if self._client is None:
71
+ fib = fibo()
72
+ for sleep_coefficient in fib:
73
+ try:
74
+ client = Client(self.url, verbose=False)
75
+
76
+ with self._client_lock:
77
+ self._client = client
78
+ break
79
+ except Exception:
80
+ pass
81
+ if sleep_coefficient is not None:
82
+ time.sleep(0.1 * sleep_coefficient)
83
+
84
+ self._batch_sender()
85
+
86
+ def _process_media(self, metrics, step: int | None) -> dict:
87
+ """
88
+ Serialize media in metrics and upload to space if needed.
89
+ """
90
+ serializable_metrics = {}
91
+ if not step:
92
+ step = 0
93
+ for key, value in metrics.items():
94
+ if isinstance(value, TrackioImage):
95
+ value._save(self.project, self.name, step)
96
+ serializable_metrics[key] = value._to_dict()
97
+ if self._space_id:
98
+ # Upload local media when deploying to space
99
+ upload_entry: UploadEntry = {
100
+ "project": self.project,
101
+ "run": self.name,
102
+ "step": step,
103
+ "uploaded_file": handle_file(value._get_absolute_file_path()),
104
+ }
105
+ with self._client_lock:
106
+ self._queued_uploads.append(upload_entry)
107
+ elif isinstance(value, TrackioVideo):
108
+ value._save(self.project, self.name, step)
109
+ if self._space_id:
110
+ serializable_metrics[key] = value._to_dict()
111
+ upload_entry: UploadEntry = {
112
+ "project": self.project,
113
+ "run": self.name,
114
+ "step": step,
115
+ "uploaded_file": handle_file(value._get_absolute_file_path()),
116
+ }
117
+ with self._client_lock:
118
+ self._queued_uploads.append(upload_entry)
119
+ else:
120
+ serializable_metrics[key] = value._to_dict()
121
+ else:
122
+ serializable_metrics[key] = value
123
+ return serializable_metrics
124
+
125
+ def log(self, metrics: dict, step: int | None = None):
126
+ for k in metrics.keys():
127
+ if k in RESERVED_KEYS or k.startswith("__"):
128
+ raise ValueError(
129
+ f"Please do not use this reserved key as a metric: {k}"
130
+ )
131
+
132
+ metrics = self._process_media(metrics, step)
133
+ log_entry: LogEntry = {
134
+ "project": self.project,
135
+ "run": self.name,
136
+ "metrics": metrics,
137
+ "step": step,
138
+ }
139
+
140
+ with self._client_lock:
141
+ self._queued_logs.append(log_entry)
142
+
143
+ def finish(self):
144
+ """Cleanup when run is finished."""
145
+ self._stop_flag.set()
146
+
147
+ # Wait for the batch sender to finish before joining the client thread.
148
+ time.sleep(2 * BATCH_SEND_INTERVAL)
149
+
150
+ if self._client_thread is not None:
151
+ print(
152
+ f"* Run finished. Uploading logs to Trackio Space: {self.url} (please wait...)"
153
+ )
154
+ self._client_thread.join()
run_context.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+
3
+ @dataclass
4
+ class RunContext:
5
+ project: str
6
+ name: str
sqlite_storage.py ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import sqlite3
4
+ from datetime import datetime
5
+ from pathlib import Path
6
+ from threading import Lock
7
+
8
+ import huggingface_hub as hf
9
+ import pandas as pd
10
+
11
+
12
+ try: # absolute imports when installed
13
+ from trackio.commit_scheduler import CommitScheduler
14
+ from trackio.dummy_commit_scheduler import DummyCommitScheduler
15
+ from trackio.utils import TRACKIO_DIR
16
+ from trackio.file_storage import FileStorage
17
+ except Exception: # relative imports for local execution on Spaces
18
+ from commit_scheduler import CommitScheduler
19
+ from dummy_commit_scheduler import DummyCommitScheduler
20
+ from utils import TRACKIO_DIR
21
+ from file_storage import FileStorage
22
+
23
+
24
+ class SQLiteStorage:
25
+ _dataset_import_attempted = False
26
+ _current_scheduler: CommitScheduler | DummyCommitScheduler | None = None
27
+ _scheduler_lock = Lock()
28
+
29
+ @staticmethod
30
+ def _get_connection(db_path: Path) -> sqlite3.Connection:
31
+ conn = sqlite3.connect(str(db_path))
32
+ conn.row_factory = sqlite3.Row
33
+ return conn
34
+
35
+ @staticmethod
36
+ def get_project_db_filename(project: str) -> Path:
37
+ """Get the database filename for a specific project."""
38
+ safe_project_name = "".join(
39
+ c for c in project if c.isalnum() or c in ("-", "_")
40
+ ).rstrip()
41
+ if not safe_project_name:
42
+ safe_project_name = "default"
43
+ return f"{safe_project_name}.db"
44
+
45
+ @staticmethod
46
+ def get_project_db_path(project: str) -> Path:
47
+ """Get the database path for a specific project."""
48
+ filename = SQLiteStorage.get_project_db_filename(project)
49
+ return TRACKIO_DIR / filename
50
+
51
+ @staticmethod
52
+ def init_db(project: str) -> Path:
53
+ """
54
+ Initialize the SQLite database with required tables.
55
+ If there is a dataset ID provided, copies from that dataset instead.
56
+ Returns the database path.
57
+ """
58
+ db_path = SQLiteStorage.get_project_db_path(project)
59
+ db_path.parent.mkdir(parents=True, exist_ok=True)
60
+ with SQLiteStorage.get_scheduler().lock:
61
+ with sqlite3.connect(db_path) as conn:
62
+ cursor = conn.cursor()
63
+ cursor.execute("""
64
+ CREATE TABLE IF NOT EXISTS metrics (
65
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
66
+ timestamp TEXT NOT NULL,
67
+ run_name TEXT NOT NULL,
68
+ step INTEGER NOT NULL,
69
+ metrics TEXT NOT NULL
70
+ )
71
+ """)
72
+ cursor.execute(
73
+ """
74
+ CREATE INDEX IF NOT EXISTS idx_metrics_run_step
75
+ ON metrics(run_name, step)
76
+ """
77
+ )
78
+ conn.commit()
79
+ return db_path
80
+
81
+ @staticmethod
82
+ def export_to_parquet():
83
+ """
84
+ Exports all projects' DB files as Parquet under the same path but with extension ".parquet".
85
+ """
86
+ # don't attempt to export (potentially wrong/blank) data before importing for the first time
87
+ if not SQLiteStorage._dataset_import_attempted:
88
+ return
89
+ all_paths = os.listdir(TRACKIO_DIR)
90
+ db_paths = [f for f in all_paths if f.endswith(".db")]
91
+ for db_path in db_paths:
92
+ db_path = TRACKIO_DIR / db_path
93
+ parquet_path = db_path.with_suffix(".parquet")
94
+ if (not parquet_path.exists()) or (
95
+ db_path.stat().st_mtime > parquet_path.stat().st_mtime
96
+ ):
97
+ with sqlite3.connect(db_path) as conn:
98
+ df = pd.read_sql("SELECT * from metrics", conn)
99
+ # break out the single JSON metrics column into individual columns
100
+ metrics = df["metrics"].copy()
101
+ metrics = pd.DataFrame(
102
+ metrics.apply(json.loads).values.tolist(), index=df.index
103
+ )
104
+ del df["metrics"]
105
+ for col in metrics.columns:
106
+ df[col] = metrics[col]
107
+ df.to_parquet(parquet_path)
108
+
109
+ @staticmethod
110
+ def import_from_parquet():
111
+ """
112
+ Imports to all DB files that have matching files under the same path but with extension ".parquet".
113
+ """
114
+ all_paths = os.listdir(TRACKIO_DIR)
115
+ parquet_paths = [f for f in all_paths if f.endswith(".parquet")]
116
+ for parquet_path in parquet_paths:
117
+ parquet_path = TRACKIO_DIR / parquet_path
118
+ db_path = parquet_path.with_suffix(".db")
119
+ df = pd.read_parquet(parquet_path)
120
+ with sqlite3.connect(db_path) as conn:
121
+ # fix up df to have a single JSON metrics column
122
+ if "metrics" not in df.columns:
123
+ # separate other columns from metrics
124
+ metrics = df.copy()
125
+ other_cols = ["id", "timestamp", "run_name", "step"]
126
+ df = df[other_cols]
127
+ for col in other_cols:
128
+ del metrics[col]
129
+ # combine them all into a single metrics col
130
+ metrics = json.loads(metrics.to_json(orient="records"))
131
+ df["metrics"] = [json.dumps(row) for row in metrics]
132
+ df.to_sql("metrics", conn, if_exists="replace", index=False)
133
+
134
+ @staticmethod
135
+ def get_scheduler():
136
+ """
137
+ Get the scheduler for the database based on the environment variables.
138
+ This applies to both local and Spaces.
139
+ """
140
+ with SQLiteStorage._scheduler_lock:
141
+ if SQLiteStorage._current_scheduler is not None:
142
+ return SQLiteStorage._current_scheduler
143
+ hf_token = os.environ.get("HF_TOKEN")
144
+ dataset_id = os.environ.get("TRACKIO_DATASET_ID")
145
+ space_repo_name = os.environ.get("SPACE_REPO_NAME")
146
+ if dataset_id is None or space_repo_name is None:
147
+ scheduler = DummyCommitScheduler()
148
+ else:
149
+ scheduler = CommitScheduler(
150
+ repo_id=dataset_id,
151
+ repo_type="dataset",
152
+ folder_path=TRACKIO_DIR,
153
+ private=True,
154
+ allow_patterns=["*.parquet", "media/**/*"],
155
+ squash_history=True,
156
+ token=hf_token,
157
+ on_before_commit=SQLiteStorage.export_to_parquet,
158
+ )
159
+ SQLiteStorage._current_scheduler = scheduler
160
+ return scheduler
161
+
162
+ @staticmethod
163
+ def log(project: str, run: str, metrics: dict, step: int | None = None):
164
+ """
165
+ Safely log metrics to the database. Before logging, this method will ensure the database exists
166
+ and is set up with the correct tables. It also uses the scheduler to lock the database so
167
+ that there is no race condition when logging / syncing to the Hugging Face Dataset.
168
+ """
169
+ db_path = SQLiteStorage.init_db(project)
170
+
171
+ with SQLiteStorage.get_scheduler().lock:
172
+ with SQLiteStorage._get_connection(db_path) as conn:
173
+ cursor = conn.cursor()
174
+
175
+ cursor.execute(
176
+ """
177
+ SELECT MAX(step)
178
+ FROM metrics
179
+ WHERE run_name = ?
180
+ """,
181
+ (run,),
182
+ )
183
+ last_step = cursor.fetchone()[0]
184
+ if step is None:
185
+ current_step = 0 if last_step is None else last_step + 1
186
+ else:
187
+ current_step = step
188
+
189
+ current_timestamp = datetime.now().isoformat()
190
+
191
+ cursor.execute(
192
+ """
193
+ INSERT INTO metrics
194
+ (timestamp, run_name, step, metrics)
195
+ VALUES (?, ?, ?, ?)
196
+ """,
197
+ (
198
+ current_timestamp,
199
+ run,
200
+ current_step,
201
+ json.dumps(metrics),
202
+ ),
203
+ )
204
+ conn.commit()
205
+
206
+ @staticmethod
207
+ def bulk_log(
208
+ project: str,
209
+ run: str,
210
+ metrics_list: list[dict],
211
+ steps: list[int] | None = None,
212
+ timestamps: list[str] | None = None,
213
+ ):
214
+ """Bulk log metrics to the database with specified steps and timestamps."""
215
+ if not metrics_list:
216
+ return
217
+
218
+ if timestamps is None:
219
+ timestamps = [datetime.now().isoformat()] * len(metrics_list)
220
+
221
+ db_path = SQLiteStorage.init_db(project)
222
+ with SQLiteStorage.get_scheduler().lock:
223
+ with SQLiteStorage._get_connection(db_path) as conn:
224
+ cursor = conn.cursor()
225
+
226
+ if steps is None:
227
+ steps = list(range(len(metrics_list)))
228
+ elif any(s is None for s in steps):
229
+ cursor.execute(
230
+ "SELECT MAX(step) FROM metrics WHERE run_name = ?", (run,)
231
+ )
232
+ last_step = cursor.fetchone()[0]
233
+ current_step = 0 if last_step is None else last_step + 1
234
+
235
+ processed_steps = []
236
+ for step in steps:
237
+ if step is None:
238
+ processed_steps.append(current_step)
239
+ current_step += 1
240
+ else:
241
+ processed_steps.append(step)
242
+ steps = processed_steps
243
+
244
+ if len(metrics_list) != len(steps) or len(metrics_list) != len(
245
+ timestamps
246
+ ):
247
+ raise ValueError(
248
+ "metrics_list, steps, and timestamps must have the same length"
249
+ )
250
+
251
+ data = []
252
+ for i, metrics in enumerate(metrics_list):
253
+ data.append(
254
+ (
255
+ timestamps[i],
256
+ run,
257
+ steps[i],
258
+ json.dumps(metrics),
259
+ )
260
+ )
261
+
262
+ cursor.executemany(
263
+ """
264
+ INSERT INTO metrics
265
+ (timestamp, run_name, step, metrics)
266
+ VALUES (?, ?, ?, ?)
267
+ """,
268
+ data,
269
+ )
270
+ conn.commit()
271
+
272
+ @staticmethod
273
+ def get_logs(project: str, run: str) -> list[dict]:
274
+ """Retrieve logs for a specific run. Logs include the step count (int) and the timestamp (datetime object)."""
275
+ db_path = SQLiteStorage.get_project_db_path(project)
276
+ if not db_path.exists():
277
+ return []
278
+
279
+ with SQLiteStorage._get_connection(db_path) as conn:
280
+ cursor = conn.cursor()
281
+ cursor.execute(
282
+ """
283
+ SELECT timestamp, step, metrics
284
+ FROM metrics
285
+ WHERE run_name = ?
286
+ ORDER BY timestamp
287
+ """,
288
+ (run,),
289
+ )
290
+
291
+ rows = cursor.fetchall()
292
+ results = []
293
+ for row in rows:
294
+ metrics = json.loads(row["metrics"])
295
+ metrics["timestamp"] = row["timestamp"]
296
+ metrics["step"] = row["step"]
297
+ results.append(metrics)
298
+ return results
299
+
300
+ @staticmethod
301
+ def load_from_dataset():
302
+ dataset_id = os.environ.get("TRACKIO_DATASET_ID")
303
+ space_repo_name = os.environ.get("SPACE_REPO_NAME")
304
+ if dataset_id is not None and space_repo_name is not None:
305
+ hfapi = hf.HfApi()
306
+ updated = False
307
+ if not TRACKIO_DIR.exists():
308
+ TRACKIO_DIR.mkdir(parents=True, exist_ok=True)
309
+ with SQLiteStorage.get_scheduler().lock:
310
+ try:
311
+ files = hfapi.list_repo_files(dataset_id, repo_type="dataset")
312
+ for file in files:
313
+ is_media = file.startswith("media/")
314
+ is_parquet = file.endswith(".parquet")
315
+ # Download parquet and media assets
316
+ if is_media or is_parquet:
317
+ local_dir = TRACKIO_DIR if is_parquet else FileStorage.get_base_path()
318
+ hf.hf_hub_download(
319
+ dataset_id, file, repo_type="dataset", local_dir=local_dir
320
+ )
321
+ updated = True
322
+ except hf.errors.EntryNotFoundError:
323
+ pass
324
+ except hf.errors.RepositoryNotFoundError:
325
+ pass
326
+ if updated:
327
+ SQLiteStorage.import_from_parquet()
328
+ SQLiteStorage._dataset_import_attempted = True
329
+
330
+ @staticmethod
331
+ def get_projects() -> list[str]:
332
+ """
333
+ Get list of all projects by scanning the database files in the trackio directory.
334
+ """
335
+ if not SQLiteStorage._dataset_import_attempted:
336
+ SQLiteStorage.load_from_dataset()
337
+
338
+ projects: set[str] = set()
339
+ if not TRACKIO_DIR.exists():
340
+ return []
341
+
342
+ for db_file in TRACKIO_DIR.glob("*.db"):
343
+ project_name = db_file.stem
344
+ projects.add(project_name)
345
+ return sorted(projects)
346
+
347
+ @staticmethod
348
+ def get_runs(project: str) -> list[str]:
349
+ """Get list of all runs for a project."""
350
+ db_path = SQLiteStorage.get_project_db_path(project)
351
+ if not db_path.exists():
352
+ return []
353
+
354
+ with SQLiteStorage._get_connection(db_path) as conn:
355
+ cursor = conn.cursor()
356
+ cursor.execute(
357
+ "SELECT DISTINCT run_name FROM metrics",
358
+ )
359
+ return [row[0] for row in cursor.fetchall()]
360
+
361
+ @staticmethod
362
+ def get_max_steps_for_runs(project: str, runs: list[str]) -> dict[str, int]:
363
+ """Efficiently get the maximum step for multiple runs in a single query."""
364
+ db_path = SQLiteStorage.get_project_db_path(project)
365
+ if not db_path.exists():
366
+ return {run: 0 for run in runs}
367
+
368
+ with SQLiteStorage._get_connection(db_path) as conn:
369
+ cursor = conn.cursor()
370
+ placeholders = ",".join("?" * len(runs))
371
+ cursor.execute(
372
+ f"""
373
+ SELECT run_name, MAX(step) as max_step
374
+ FROM metrics
375
+ WHERE run_name IN ({placeholders})
376
+ GROUP BY run_name
377
+ """,
378
+ runs,
379
+ )
380
+
381
+ results = {run: 0 for run in runs} # Default to 0 for runs with no data
382
+ for row in cursor.fetchall():
383
+ results[row["run_name"]] = row["max_step"]
384
+
385
+ return results
386
+
387
+ def finish(self):
388
+ """Cleanup when run is finished."""
389
+ pass
typehints.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, TypedDict
2
+
3
+ from gradio import FileData
4
+
5
+
6
+ class LogEntry(TypedDict):
7
+ project: str
8
+ run: str
9
+ metrics: dict[str, Any]
10
+ step: int | None
11
+
12
+
13
+ class UploadEntry(TypedDict):
14
+ project: str
15
+ run: str
16
+ step: int | None
17
+ uploaded_file: FileData
ui.py ADDED
@@ -0,0 +1,731 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+ import re
4
+ import shutil
5
+ from typing import Any, Literal
6
+
7
+ import gradio as gr
8
+ import huggingface_hub as hf
9
+ import numpy as np
10
+ import pandas as pd
11
+
12
+
13
+ HfApi = hf.HfApi()
14
+
15
+ try:
16
+ import trackio.utils as utils
17
+ from trackio.file_storage import FileStorage
18
+ from trackio.media import TrackioImage, TrackioVideo
19
+ from trackio.sqlite_storage import SQLiteStorage
20
+ from trackio.typehints import LogEntry, UploadEntry
21
+ except: # noqa: E722
22
+ import utils
23
+ from file_storage import FileStorage
24
+ from media import TrackioImage, TrackioVideo
25
+ from sqlite_storage import SQLiteStorage
26
+ from typehints import LogEntry, UploadEntry
27
+
28
+
29
+ def get_project_info() -> str | None:
30
+ dataset_id = os.environ.get("TRACKIO_DATASET_ID")
31
+ space_id = os.environ.get("SPACE_ID")
32
+ persistent_storage_enabled = os.environ.get(
33
+ "PERSISTANT_STORAGE_ENABLED"
34
+ ) # Space env name has a typo
35
+ if persistent_storage_enabled:
36
+ return "&#10024; Persistent Storage is enabled, logs are stored directly in this Space."
37
+ if dataset_id:
38
+ sync_status = utils.get_sync_status(SQLiteStorage.get_scheduler())
39
+ upgrade_message = f"New changes are synced every 5 min <span class='info-container'><input type='checkbox' class='info-checkbox' id='upgrade-info'><label for='upgrade-info' class='info-icon'>&#9432;</label><span class='info-expandable'> To avoid losing data between syncs, <a href='https://huggingface.co/spaces/{space_id}/settings' class='accent-link'>click here</a> to open this Space's settings and add Persistent Storage.</span></span>"
40
+ if sync_status is not None:
41
+ info = f"&#x21bb; Backed up {sync_status} min ago to <a href='https://huggingface.co/datasets/{dataset_id}' target='_blank' class='accent-link'>{dataset_id}</a> | {upgrade_message}"
42
+ else:
43
+ info = f"&#x21bb; Not backed up yet to <a href='https://huggingface.co/datasets/{dataset_id}' target='_blank' class='accent-link'>{dataset_id}</a> | {upgrade_message}"
44
+ return info
45
+ return None
46
+
47
+
48
+ def get_projects(request: gr.Request):
49
+ projects = SQLiteStorage.get_projects()
50
+ if project := request.query_params.get("project"):
51
+ interactive = False
52
+ else:
53
+ interactive = True
54
+ project = projects[0] if projects else None
55
+
56
+ return gr.Dropdown(
57
+ label="Project",
58
+ choices=projects,
59
+ value=project,
60
+ allow_custom_value=True,
61
+ interactive=interactive,
62
+ info=get_project_info(),
63
+ )
64
+
65
+
66
+ def get_runs(project) -> list[str]:
67
+ if not project:
68
+ return []
69
+ return SQLiteStorage.get_runs(project)
70
+
71
+
72
+ def get_available_metrics(project: str, runs: list[str]) -> list[str]:
73
+ """Get all available metrics across all runs for x-axis selection."""
74
+ if not project or not runs:
75
+ return ["step", "time"]
76
+
77
+ all_metrics = set()
78
+ for run in runs:
79
+ metrics = SQLiteStorage.get_logs(project, run)
80
+ if metrics:
81
+ df = pd.DataFrame(metrics)
82
+ numeric_cols = df.select_dtypes(include="number").columns
83
+ numeric_cols = [c for c in numeric_cols if c not in utils.RESERVED_KEYS]
84
+ all_metrics.update(numeric_cols)
85
+
86
+ all_metrics.add("step")
87
+ all_metrics.add("time")
88
+
89
+ sorted_metrics = utils.sort_metrics_by_prefix(list(all_metrics))
90
+
91
+ result = ["step", "time"]
92
+ for metric in sorted_metrics:
93
+ if metric not in result:
94
+ result.append(metric)
95
+
96
+ return result
97
+
98
+ from dataclasses import dataclass
99
+ @dataclass
100
+ class MediaData:
101
+ caption: str | None
102
+ file_path: str
103
+
104
+ def get_path_for_media(path: str) -> str:
105
+ if utils.get_space():
106
+ # When running in a space, media is stored in the gradio app directory
107
+ # so we need to return the path as is.
108
+ return path
109
+ return utils.TRACKIO_DIR / path
110
+
111
+ def extract_images(logs: list[dict]) -> dict[str, list[MediaData]]:
112
+ media_by_key: dict[str, list[MediaData]] = {}
113
+ logs = sorted(logs, key=lambda x: x.get("step", 0))
114
+ for log in logs:
115
+ for key, value in log.items():
116
+ if isinstance(value, dict):
117
+ type = value.get("_type")
118
+ if type == TrackioImage.TYPE or type == TrackioVideo.TYPE:
119
+ if key not in media_by_key:
120
+ media_by_key[key] = []
121
+ try:
122
+ media_data = MediaData(
123
+ file_path=get_path_for_media(value.get("file_path")),
124
+ caption=value.get("caption"),
125
+ )
126
+ media_by_key[key].append(media_data)
127
+ except Exception as e:
128
+ print(f"Media currently unavailable: {key}: {e}")
129
+ return media_by_key
130
+
131
+
132
+ def load_run_data(
133
+ project: str | None,
134
+ run: str | None,
135
+ smoothing: bool,
136
+ x_axis: str,
137
+ log_scale: bool = False,
138
+ ) -> tuple[pd.DataFrame, dict]:
139
+ if not project or not run:
140
+ return None, None
141
+
142
+ logs = SQLiteStorage.get_logs(project, run)
143
+ if not logs:
144
+ return None, None
145
+
146
+ images = extract_images(logs)
147
+ df = pd.DataFrame(logs)
148
+
149
+ if "step" not in df.columns:
150
+ df["step"] = range(len(df))
151
+
152
+ if x_axis == "time" and "timestamp" in df.columns:
153
+ df["timestamp"] = pd.to_datetime(df["timestamp"])
154
+ first_timestamp = df["timestamp"].min()
155
+ df["time"] = (df["timestamp"] - first_timestamp).dt.total_seconds()
156
+ x_column = "time"
157
+ elif x_axis == "step":
158
+ x_column = "step"
159
+ else:
160
+ x_column = x_axis
161
+
162
+ if log_scale and x_column in df.columns:
163
+ x_vals = df[x_column]
164
+ if (x_vals <= 0).any():
165
+ df[x_column] = np.log10(np.maximum(x_vals, 0) + 1)
166
+ else:
167
+ df[x_column] = np.log10(x_vals)
168
+
169
+ if smoothing:
170
+ numeric_cols = df.select_dtypes(include="number").columns
171
+ numeric_cols = [c for c in numeric_cols if c not in utils.RESERVED_KEYS]
172
+
173
+ df_original = df.copy()
174
+ df_original["run"] = f"{run}_original"
175
+ df_original["data_type"] = "original"
176
+
177
+ df_smoothed = df.copy()
178
+ window_size = max(3, min(10, len(df) // 10)) # Adaptive window size
179
+ df_smoothed[numeric_cols] = (
180
+ df_smoothed[numeric_cols]
181
+ .rolling(window=window_size, center=True, min_periods=1)
182
+ .mean()
183
+ )
184
+ df_smoothed["run"] = f"{run}_smoothed"
185
+ df_smoothed["data_type"] = "smoothed"
186
+
187
+ combined_df = pd.concat([df_original, df_smoothed], ignore_index=True)
188
+ combined_df["x_axis"] = x_column
189
+ return combined_df, images
190
+ else:
191
+ df["run"] = run
192
+ df["data_type"] = "original"
193
+ df["x_axis"] = x_column
194
+ return df, images
195
+
196
+
197
+ def update_runs(project, filter_text, user_interacted_with_runs=False):
198
+ if project is None:
199
+ runs = []
200
+ num_runs = 0
201
+ else:
202
+ runs = get_runs(project)
203
+ num_runs = len(runs)
204
+ if filter_text:
205
+ runs = [r for r in runs if filter_text in r]
206
+ if not user_interacted_with_runs:
207
+ return gr.CheckboxGroup(choices=runs, value=runs), gr.Textbox(
208
+ label=f"Runs ({num_runs})"
209
+ )
210
+ else:
211
+ return gr.CheckboxGroup(choices=runs), gr.Textbox(label=f"Runs ({num_runs})")
212
+
213
+
214
+ def filter_runs(project, filter_text):
215
+ runs = get_runs(project)
216
+ runs = [r for r in runs if filter_text in r]
217
+ return gr.CheckboxGroup(choices=runs, value=runs)
218
+
219
+
220
+ def update_x_axis_choices(project, runs):
221
+ """Update x-axis dropdown choices based on available metrics."""
222
+ available_metrics = get_available_metrics(project, runs)
223
+ return gr.Dropdown(
224
+ label="X-axis",
225
+ choices=available_metrics,
226
+ value="step",
227
+ )
228
+
229
+
230
+ def toggle_timer(cb_value):
231
+ if cb_value:
232
+ return gr.Timer(active=True)
233
+ else:
234
+ return gr.Timer(active=False)
235
+
236
+
237
+ def check_auth(hf_token: str | None) -> None:
238
+ if os.getenv("SYSTEM") == "spaces": # if we are running in Spaces
239
+ # check auth token passed in
240
+ if hf_token is None:
241
+ raise PermissionError(
242
+ "Expected a HF_TOKEN to be provided when logging to a Space"
243
+ )
244
+ who = HfApi.whoami(hf_token)
245
+ access_token = who["auth"]["accessToken"]
246
+ owner_name = os.getenv("SPACE_AUTHOR_NAME")
247
+ repo_name = os.getenv("SPACE_REPO_NAME")
248
+ # make sure the token user is either the author of the space,
249
+ # or is a member of an org that is the author.
250
+ orgs = [o["name"] for o in who["orgs"]]
251
+ if owner_name != who["name"] and owner_name not in orgs:
252
+ raise PermissionError(
253
+ "Expected the provided hf_token to be the user owner of the space, or be a member of the org owner of the space"
254
+ )
255
+ # reject fine-grained tokens without specific repo access
256
+ if access_token["role"] == "fineGrained":
257
+ matched = False
258
+ for item in access_token["fineGrained"]["scoped"]:
259
+ if (
260
+ item["entity"]["type"] == "space"
261
+ and item["entity"]["name"] == f"{owner_name}/{repo_name}"
262
+ and "repo.write" in item["permissions"]
263
+ ):
264
+ matched = True
265
+ break
266
+ if (
267
+ (
268
+ item["entity"]["type"] == "user"
269
+ or item["entity"]["type"] == "org"
270
+ )
271
+ and item["entity"]["name"] == owner_name
272
+ and "repo.write" in item["permissions"]
273
+ ):
274
+ matched = True
275
+ break
276
+ if not matched:
277
+ raise PermissionError(
278
+ "Expected the provided hf_token with fine grained permissions to provide write access to the space"
279
+ )
280
+ # reject read-only tokens
281
+ elif access_token["role"] != "write":
282
+ raise PermissionError(
283
+ "Expected the provided hf_token to provide write permissions"
284
+ )
285
+
286
+
287
+ def upload_db_to_space(
288
+ project: str, uploaded_db: gr.FileData, hf_token: str | None
289
+ ) -> None:
290
+ check_auth(hf_token)
291
+ db_project_path = SQLiteStorage.get_project_db_path(project)
292
+ if os.path.exists(db_project_path):
293
+ raise gr.Error(
294
+ f"Trackio database file already exists for project {project}, cannot overwrite."
295
+ )
296
+ os.makedirs(os.path.dirname(db_project_path), exist_ok=True)
297
+ shutil.copy(uploaded_db["path"], db_project_path)
298
+
299
+
300
+ def bulk_upload_media(uploads: list[UploadEntry], hf_token: str | None) -> None:
301
+ check_auth(hf_token)
302
+ for upload in uploads:
303
+ media_path = FileStorage.init_project_media_path(
304
+ upload["project"], upload["run"], upload["step"]
305
+ )
306
+ shutil.copy(upload["uploaded_file"]["path"], media_path)
307
+
308
+
309
+ def log(
310
+ project: str,
311
+ run: str,
312
+ metrics: dict[str, Any],
313
+ step: int | None,
314
+ hf_token: str | None,
315
+ ) -> None:
316
+ check_auth(hf_token)
317
+ SQLiteStorage.log(project=project, run=run, metrics=metrics, step=step)
318
+
319
+
320
+ def bulk_log(
321
+ logs: list[LogEntry],
322
+ hf_token: str | None,
323
+ ) -> None:
324
+ check_auth(hf_token)
325
+
326
+ logs_by_run = {}
327
+ for log_entry in logs:
328
+ key = (log_entry["project"], log_entry["run"])
329
+ if key not in logs_by_run:
330
+ logs_by_run[key] = {"metrics": [], "steps": []}
331
+ logs_by_run[key]["metrics"].append(log_entry["metrics"])
332
+ logs_by_run[key]["steps"].append(log_entry.get("step"))
333
+
334
+ for (project, run), data in logs_by_run.items():
335
+ SQLiteStorage.bulk_log(
336
+ project=project,
337
+ run=run,
338
+ metrics_list=data["metrics"],
339
+ steps=data["steps"],
340
+ )
341
+
342
+
343
+ def filter_metrics_by_regex(metrics: list[str], filter_pattern: str) -> list[str]:
344
+ """
345
+ Filter metrics using regex pattern.
346
+
347
+ Args:
348
+ metrics: List of metric names to filter
349
+ filter_pattern: Regex pattern to match against metric names
350
+
351
+ Returns:
352
+ List of metric names that match the pattern
353
+ """
354
+ if not filter_pattern.strip():
355
+ return metrics
356
+
357
+ try:
358
+ pattern = re.compile(filter_pattern, re.IGNORECASE)
359
+ return [metric for metric in metrics if pattern.search(metric)]
360
+ except re.error:
361
+ return [
362
+ metric for metric in metrics if filter_pattern.lower() in metric.lower()
363
+ ]
364
+
365
+
366
+ def configure(request: gr.Request):
367
+ sidebar_param = request.query_params.get("sidebar")
368
+ match sidebar_param:
369
+ case "collapsed":
370
+ sidebar = gr.Sidebar(open=False, visible=True)
371
+ case "hidden":
372
+ sidebar = gr.Sidebar(open=False, visible=False)
373
+ case _:
374
+ sidebar = gr.Sidebar(open=True, visible=True)
375
+
376
+ if metrics := request.query_params.get("metrics"):
377
+ return metrics.split(","), sidebar
378
+ else:
379
+ return [], sidebar
380
+
381
+
382
+ def create_media_section(media_by_run: dict[str, dict[str, list[MediaData]]]):
383
+ with gr.Accordion(label="media"):
384
+ with gr.Group(elem_classes=("media-group")):
385
+ for run, media_by_key in media_by_run.items():
386
+ with gr.Tab(label=run, elem_classes=("media-tab")):
387
+ for key, media_item in media_by_key.items():
388
+ gr.Gallery(
389
+ [(item.file_path, item.caption) for item in media_item],
390
+ label=key,
391
+ columns=6,
392
+ elem_classes=("media-gallery"),
393
+ )
394
+
395
+
396
+ css = """
397
+ #run-cb .wrap { gap: 2px; }
398
+ #run-cb .wrap label {
399
+ line-height: 1;
400
+ padding: 6px;
401
+ }
402
+ .logo-light { display: block; }
403
+ .logo-dark { display: none; }
404
+ .dark .logo-light { display: none; }
405
+ .dark .logo-dark { display: block; }
406
+ .dark .caption-label { color: white; }
407
+
408
+ .info-container {
409
+ position: relative;
410
+ display: inline;
411
+ }
412
+ .info-checkbox {
413
+ position: absolute;
414
+ opacity: 0;
415
+ pointer-events: none;
416
+ }
417
+ .info-icon {
418
+ border-bottom: 1px dotted;
419
+ cursor: pointer;
420
+ user-select: none;
421
+ color: var(--color-accent);
422
+ }
423
+ .info-expandable {
424
+ display: none;
425
+ opacity: 0;
426
+ transition: opacity 0.2s ease-in-out;
427
+ }
428
+ .info-checkbox:checked ~ .info-expandable {
429
+ display: inline;
430
+ opacity: 1;
431
+ }
432
+ .info-icon:hover { opacity: 0.8; }
433
+ .accent-link { font-weight: bold; }
434
+
435
+ .media-gallery { max-height: 325px; }
436
+ .media-group, .media-group > div { background: none; }
437
+ .media-group .tabs { padding: 0.5em; }
438
+ """
439
+
440
+ with gr.Blocks(theme="citrus", title="Trackio Dashboard", css=css) as demo:
441
+ with gr.Sidebar(open=False) as sidebar:
442
+ logo = gr.Markdown(
443
+ f"""
444
+ <img src='/gradio_api/file={utils.TRACKIO_LOGO_DIR}/trackio_logo_type_light_transparent.png' width='80%' class='logo-light'>
445
+ <img src='/gradio_api/file={utils.TRACKIO_LOGO_DIR}/trackio_logo_type_dark_transparent.png' width='80%' class='logo-dark'>
446
+ """
447
+ )
448
+ project_dd = gr.Dropdown(label="Project", allow_custom_value=True)
449
+ run_tb = gr.Textbox(label="Runs", placeholder="Type to filter...")
450
+ run_cb = gr.CheckboxGroup(
451
+ label="Runs", choices=[], interactive=True, elem_id="run-cb"
452
+ )
453
+ gr.HTML("<hr>")
454
+ realtime_cb = gr.Checkbox(label="Refresh metrics realtime", value=True)
455
+ smoothing_cb = gr.Checkbox(label="Smooth metrics", value=True)
456
+ x_axis_dd = gr.Dropdown(
457
+ label="X-axis",
458
+ choices=["step", "time"],
459
+ value="step",
460
+ )
461
+ log_scale_cb = gr.Checkbox(label="Log scale X-axis", value=False)
462
+ metric_filter_tb = gr.Textbox(
463
+ label="Metric Filter (regex)",
464
+ placeholder="e.g., loss|ndcg@10|gpu",
465
+ value="",
466
+ info="Filter metrics using regex patterns. Leave empty to show all metrics.",
467
+ )
468
+
469
+ timer = gr.Timer(value=1)
470
+ metrics_subset = gr.State([])
471
+ user_interacted_with_run_cb = gr.State(False)
472
+
473
+ gr.on([demo.load], fn=configure, outputs=[metrics_subset, sidebar])
474
+ gr.on(
475
+ [demo.load],
476
+ fn=get_projects,
477
+ outputs=project_dd,
478
+ show_progress="hidden",
479
+ )
480
+ gr.on(
481
+ [timer.tick],
482
+ fn=update_runs,
483
+ inputs=[project_dd, run_tb, user_interacted_with_run_cb],
484
+ outputs=[run_cb, run_tb],
485
+ show_progress="hidden",
486
+ )
487
+ gr.on(
488
+ [timer.tick],
489
+ fn=lambda: gr.Dropdown(info=get_project_info()),
490
+ outputs=[project_dd],
491
+ show_progress="hidden",
492
+ )
493
+ gr.on(
494
+ [demo.load, project_dd.change],
495
+ fn=update_runs,
496
+ inputs=[project_dd, run_tb],
497
+ outputs=[run_cb, run_tb],
498
+ show_progress="hidden",
499
+ )
500
+ gr.on(
501
+ [demo.load, project_dd.change, run_cb.change],
502
+ fn=update_x_axis_choices,
503
+ inputs=[project_dd, run_cb],
504
+ outputs=x_axis_dd,
505
+ show_progress="hidden",
506
+ )
507
+
508
+ realtime_cb.change(
509
+ fn=toggle_timer,
510
+ inputs=realtime_cb,
511
+ outputs=timer,
512
+ api_name="toggle_timer",
513
+ )
514
+ run_cb.input(
515
+ fn=lambda: True,
516
+ outputs=user_interacted_with_run_cb,
517
+ )
518
+ run_tb.input(
519
+ fn=filter_runs,
520
+ inputs=[project_dd, run_tb],
521
+ outputs=run_cb,
522
+ )
523
+
524
+ gr.api(
525
+ fn=upload_db_to_space,
526
+ api_name="upload_db_to_space",
527
+ )
528
+ gr.api(
529
+ fn=bulk_upload_media,
530
+ api_name="bulk_upload_media",
531
+ )
532
+ gr.api(
533
+ fn=log,
534
+ api_name="log",
535
+ )
536
+ gr.api(
537
+ fn=bulk_log,
538
+ api_name="bulk_log",
539
+ )
540
+
541
+ x_lim = gr.State(None)
542
+ last_steps = gr.State({})
543
+
544
+ def update_x_lim(select_data: gr.SelectData):
545
+ return select_data.index
546
+
547
+ def update_last_steps(project, runs):
548
+ """Update the last step from all runs to detect when new data is available."""
549
+ if not project or not runs:
550
+ return {}
551
+
552
+ return SQLiteStorage.get_max_steps_for_runs(project, runs)
553
+
554
+ timer.tick(
555
+ fn=update_last_steps,
556
+ inputs=[project_dd, run_cb],
557
+ outputs=last_steps,
558
+ show_progress="hidden",
559
+ )
560
+
561
+ @gr.render(
562
+ triggers=[
563
+ demo.load,
564
+ run_cb.change,
565
+ last_steps.change,
566
+ smoothing_cb.change,
567
+ x_lim.change,
568
+ x_axis_dd.change,
569
+ log_scale_cb.change,
570
+ metric_filter_tb.change,
571
+ ],
572
+ inputs=[
573
+ project_dd,
574
+ run_cb,
575
+ smoothing_cb,
576
+ metrics_subset,
577
+ x_lim,
578
+ x_axis_dd,
579
+ log_scale_cb,
580
+ metric_filter_tb,
581
+ ],
582
+ show_progress="hidden",
583
+ )
584
+ def update_dashboard(
585
+ project,
586
+ runs,
587
+ smoothing,
588
+ metrics_subset,
589
+ x_lim_value,
590
+ x_axis,
591
+ log_scale,
592
+ metric_filter,
593
+ ):
594
+ dfs = []
595
+ images_by_run = {}
596
+ original_runs = runs.copy()
597
+
598
+ for run in runs:
599
+ df, images_by_key = load_run_data(
600
+ project, run, smoothing, x_axis, log_scale
601
+ )
602
+ if df is not None:
603
+ dfs.append(df)
604
+ images_by_run[run] = images_by_key
605
+ if dfs:
606
+ master_df = pd.concat(dfs, ignore_index=True)
607
+ else:
608
+ master_df = pd.DataFrame()
609
+
610
+ if master_df.empty:
611
+ return
612
+
613
+ x_column = "step"
614
+ if dfs and not dfs[0].empty and "x_axis" in dfs[0].columns:
615
+ x_column = dfs[0]["x_axis"].iloc[0]
616
+
617
+ numeric_cols = master_df.select_dtypes(include="number").columns
618
+ numeric_cols = [c for c in numeric_cols if c not in utils.RESERVED_KEYS]
619
+ if metrics_subset:
620
+ numeric_cols = [c for c in numeric_cols if c in metrics_subset]
621
+
622
+ if metric_filter and metric_filter.strip():
623
+ numeric_cols = filter_metrics_by_regex(list(numeric_cols), metric_filter)
624
+
625
+ nested_metric_groups = utils.group_metrics_with_subprefixes(list(numeric_cols))
626
+ color_map = utils.get_color_mapping(original_runs, smoothing)
627
+
628
+ metric_idx = 0
629
+ for group_name in sorted(nested_metric_groups.keys()):
630
+ group_data = nested_metric_groups[group_name]
631
+
632
+ with gr.Accordion(
633
+ label=group_name,
634
+ open=True,
635
+ key=f"accordion-{group_name}",
636
+ preserved_by_key=["value", "open"],
637
+ ):
638
+ # Render direct metrics at this level
639
+ if group_data["direct_metrics"]:
640
+ with gr.Row(key=f"row-{group_name}-direct"):
641
+ for metric_name in group_data["direct_metrics"]:
642
+ metric_df = master_df.dropna(subset=[metric_name])
643
+ color = "run" if "run" in metric_df.columns else None
644
+ if not metric_df.empty:
645
+ plot = gr.LinePlot(
646
+ utils.downsample(
647
+ metric_df,
648
+ x_column,
649
+ metric_name,
650
+ color,
651
+ x_lim_value,
652
+ ),
653
+ x=x_column,
654
+ y=metric_name,
655
+ y_title=metric_name.split("/")[-1],
656
+ color=color,
657
+ color_map=color_map,
658
+ title=metric_name,
659
+ key=f"plot-{metric_idx}",
660
+ preserved_by_key=None,
661
+ x_lim=x_lim_value,
662
+ show_fullscreen_button=True,
663
+ min_width=400,
664
+ )
665
+ plot.select(
666
+ update_x_lim,
667
+ outputs=x_lim,
668
+ key=f"select-{metric_idx}",
669
+ )
670
+ plot.double_click(
671
+ lambda: None,
672
+ outputs=x_lim,
673
+ key=f"double-{metric_idx}",
674
+ )
675
+ metric_idx += 1
676
+
677
+ # If there are subgroups, create nested accordions
678
+ if group_data["subgroups"]:
679
+ for subgroup_name in sorted(group_data["subgroups"].keys()):
680
+ subgroup_metrics = group_data["subgroups"][subgroup_name]
681
+
682
+ with gr.Accordion(
683
+ label=subgroup_name,
684
+ open=True,
685
+ key=f"accordion-{group_name}-{subgroup_name}",
686
+ preserved_by_key=["value", "open"],
687
+ ):
688
+ with gr.Row(key=f"row-{group_name}-{subgroup_name}"):
689
+ for metric_name in subgroup_metrics:
690
+ metric_df = master_df.dropna(subset=[metric_name])
691
+ color = (
692
+ "run" if "run" in metric_df.columns else None
693
+ )
694
+ if not metric_df.empty:
695
+ plot = gr.LinePlot(
696
+ utils.downsample(
697
+ metric_df,
698
+ x_column,
699
+ metric_name,
700
+ color,
701
+ x_lim_value,
702
+ ),
703
+ x=x_column,
704
+ y=metric_name,
705
+ y_title=metric_name.split("/")[-1],
706
+ color=color,
707
+ color_map=color_map,
708
+ title=metric_name,
709
+ key=f"plot-{metric_idx}",
710
+ preserved_by_key=None,
711
+ x_lim=x_lim_value,
712
+ show_fullscreen_button=True,
713
+ min_width=400,
714
+ )
715
+ plot.select(
716
+ update_x_lim,
717
+ outputs=x_lim,
718
+ key=f"select-{metric_idx}",
719
+ )
720
+ plot.double_click(
721
+ lambda: None,
722
+ outputs=x_lim,
723
+ key=f"double-{metric_idx}",
724
+ )
725
+ metric_idx += 1
726
+ if images_by_run and any(any(images) for images in images_by_run.values()):
727
+ create_media_section(images_by_run)
728
+
729
+
730
+ if __name__ == "__main__":
731
+ demo.launch(allowed_paths=[utils.TRACKIO_LOGO_DIR], show_api=False, show_error=True)
utils.py ADDED
@@ -0,0 +1,574 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import sys
4
+ import time
5
+ from pathlib import Path
6
+ from typing import TYPE_CHECKING
7
+
8
+ import huggingface_hub
9
+ import numpy as np
10
+ import pandas as pd
11
+ from huggingface_hub.constants import HF_HOME
12
+
13
+ if TYPE_CHECKING:
14
+ from trackio.commit_scheduler import CommitScheduler
15
+ from trackio.dummy_commit_scheduler import DummyCommitScheduler
16
+
17
+ RESERVED_KEYS = ["project", "run", "timestamp", "step", "time", "metrics"]
18
+ TRACKIO_DIR = Path(HF_HOME) / "trackio"
19
+
20
+ TRACKIO_LOGO_DIR = Path(__file__).parent / "assets"
21
+
22
+
23
+ def generate_readable_name(used_names: list[str], space_id: str | None = None) -> str:
24
+ """
25
+ Generates a random, readable name like "dainty-sunset-0".
26
+ If space_id is provided, generates username-timestamp format instead.
27
+ """
28
+ if space_id is not None:
29
+ username = huggingface_hub.whoami()["name"]
30
+ timestamp = int(time.time())
31
+ return f"{username}-{timestamp}"
32
+ adjectives = [
33
+ "dainty",
34
+ "brave",
35
+ "calm",
36
+ "eager",
37
+ "fancy",
38
+ "gentle",
39
+ "happy",
40
+ "jolly",
41
+ "kind",
42
+ "lively",
43
+ "merry",
44
+ "nice",
45
+ "proud",
46
+ "quick",
47
+ "hugging",
48
+ "silly",
49
+ "tidy",
50
+ "witty",
51
+ "zealous",
52
+ "bright",
53
+ "shy",
54
+ "bold",
55
+ "clever",
56
+ "daring",
57
+ "elegant",
58
+ "faithful",
59
+ "graceful",
60
+ "honest",
61
+ "inventive",
62
+ "jovial",
63
+ "keen",
64
+ "lucky",
65
+ "modest",
66
+ "noble",
67
+ "optimistic",
68
+ "patient",
69
+ "quirky",
70
+ "resourceful",
71
+ "sincere",
72
+ "thoughtful",
73
+ "upbeat",
74
+ "valiant",
75
+ "warm",
76
+ "youthful",
77
+ "zesty",
78
+ "adventurous",
79
+ "breezy",
80
+ "cheerful",
81
+ "delightful",
82
+ "energetic",
83
+ "fearless",
84
+ "glad",
85
+ "hopeful",
86
+ "imaginative",
87
+ "joyful",
88
+ "kindly",
89
+ "luminous",
90
+ "mysterious",
91
+ "neat",
92
+ "outgoing",
93
+ "playful",
94
+ "radiant",
95
+ "spirited",
96
+ "tranquil",
97
+ "unique",
98
+ "vivid",
99
+ "wise",
100
+ "zany",
101
+ "artful",
102
+ "bubbly",
103
+ "charming",
104
+ "dazzling",
105
+ "earnest",
106
+ "festive",
107
+ "gentlemanly",
108
+ "hearty",
109
+ "intrepid",
110
+ "jubilant",
111
+ "knightly",
112
+ "lively",
113
+ "magnetic",
114
+ "nimble",
115
+ "orderly",
116
+ "peaceful",
117
+ "quick-witted",
118
+ "robust",
119
+ "sturdy",
120
+ "trusty",
121
+ "upstanding",
122
+ "vibrant",
123
+ "whimsical",
124
+ ]
125
+ nouns = [
126
+ "sunset",
127
+ "forest",
128
+ "river",
129
+ "mountain",
130
+ "breeze",
131
+ "meadow",
132
+ "ocean",
133
+ "valley",
134
+ "sky",
135
+ "field",
136
+ "cloud",
137
+ "star",
138
+ "rain",
139
+ "leaf",
140
+ "stone",
141
+ "flower",
142
+ "bird",
143
+ "tree",
144
+ "wave",
145
+ "trail",
146
+ "island",
147
+ "desert",
148
+ "hill",
149
+ "lake",
150
+ "pond",
151
+ "grove",
152
+ "canyon",
153
+ "reef",
154
+ "bay",
155
+ "peak",
156
+ "glade",
157
+ "marsh",
158
+ "cliff",
159
+ "dune",
160
+ "spring",
161
+ "brook",
162
+ "cave",
163
+ "plain",
164
+ "ridge",
165
+ "wood",
166
+ "blossom",
167
+ "petal",
168
+ "root",
169
+ "branch",
170
+ "seed",
171
+ "acorn",
172
+ "pine",
173
+ "willow",
174
+ "cedar",
175
+ "elm",
176
+ "falcon",
177
+ "eagle",
178
+ "sparrow",
179
+ "robin",
180
+ "owl",
181
+ "finch",
182
+ "heron",
183
+ "crane",
184
+ "duck",
185
+ "swan",
186
+ "fox",
187
+ "wolf",
188
+ "bear",
189
+ "deer",
190
+ "moose",
191
+ "otter",
192
+ "beaver",
193
+ "lynx",
194
+ "hare",
195
+ "badger",
196
+ "butterfly",
197
+ "bee",
198
+ "ant",
199
+ "beetle",
200
+ "dragonfly",
201
+ "firefly",
202
+ "ladybug",
203
+ "moth",
204
+ "spider",
205
+ "worm",
206
+ "coral",
207
+ "kelp",
208
+ "shell",
209
+ "pebble",
210
+ "face",
211
+ "boulder",
212
+ "cobble",
213
+ "sand",
214
+ "wavelet",
215
+ "tide",
216
+ "current",
217
+ "mist",
218
+ ]
219
+ number = 0
220
+ name = f"{adjectives[0]}-{nouns[0]}-{number}"
221
+ while name in used_names:
222
+ number += 1
223
+ adjective = adjectives[number % len(adjectives)]
224
+ noun = nouns[number % len(nouns)]
225
+ name = f"{adjective}-{noun}-{number}"
226
+ return name
227
+
228
+
229
+ def block_except_in_notebook():
230
+ in_notebook = bool(getattr(sys, "ps1", sys.flags.interactive))
231
+ if in_notebook:
232
+ return
233
+ try:
234
+ while True:
235
+ time.sleep(0.1)
236
+ except (KeyboardInterrupt, OSError):
237
+ print("Keyboard interruption in main thread... closing dashboard.")
238
+
239
+
240
+ def simplify_column_names(columns: list[str]) -> dict[str, str]:
241
+ """
242
+ Simplifies column names to first 10 alphanumeric or "/" characters with unique suffixes.
243
+
244
+ Args:
245
+ columns: List of original column names
246
+
247
+ Returns:
248
+ Dictionary mapping original column names to simplified names
249
+ """
250
+ simplified_names = {}
251
+ used_names = set()
252
+
253
+ for col in columns:
254
+ alphanumeric = re.sub(r"[^a-zA-Z0-9/]", "", col)
255
+ base_name = alphanumeric[:10] if alphanumeric else f"col_{len(used_names)}"
256
+
257
+ final_name = base_name
258
+ suffix = 1
259
+ while final_name in used_names:
260
+ final_name = f"{base_name}_{suffix}"
261
+ suffix += 1
262
+
263
+ simplified_names[col] = final_name
264
+ used_names.add(final_name)
265
+
266
+ return simplified_names
267
+
268
+
269
+ def print_dashboard_instructions(project: str) -> None:
270
+ """
271
+ Prints instructions for viewing the Trackio dashboard.
272
+
273
+ Args:
274
+ project: The name of the project to show dashboard for.
275
+ """
276
+ YELLOW = "\033[93m"
277
+ BOLD = "\033[1m"
278
+ RESET = "\033[0m"
279
+
280
+ print("* View dashboard by running in your terminal:")
281
+ print(f'{BOLD}{YELLOW}trackio show --project "{project}"{RESET}')
282
+ print(f'* or by running in Python: trackio.show(project="{project}")')
283
+
284
+
285
+ def preprocess_space_and_dataset_ids(
286
+ space_id: str | None, dataset_id: str | None
287
+ ) -> tuple[str | None, str | None]:
288
+ if space_id is not None and "/" not in space_id:
289
+ username = huggingface_hub.whoami()["name"]
290
+ space_id = f"{username}/{space_id}"
291
+ if dataset_id is not None and "/" not in dataset_id:
292
+ username = huggingface_hub.whoami()["name"]
293
+ dataset_id = f"{username}/{dataset_id}"
294
+ if space_id is not None and dataset_id is None:
295
+ dataset_id = f"{space_id}-dataset"
296
+ return space_id, dataset_id
297
+
298
+
299
+ def fibo():
300
+ """Generator for Fibonacci backoff: 1, 1, 2, 3, 5, 8, ..."""
301
+ a, b = 1, 1
302
+ while True:
303
+ yield a
304
+ a, b = b, a + b
305
+
306
+
307
+ COLOR_PALETTE = [
308
+ "#3B82F6",
309
+ "#EF4444",
310
+ "#10B981",
311
+ "#F59E0B",
312
+ "#8B5CF6",
313
+ "#EC4899",
314
+ "#06B6D4",
315
+ "#84CC16",
316
+ "#F97316",
317
+ "#6366F1",
318
+ ]
319
+
320
+
321
+ def get_color_mapping(runs: list[str], smoothing: bool) -> dict[str, str]:
322
+ """Generate color mapping for runs, with transparency for original data when smoothing is enabled."""
323
+ color_map = {}
324
+
325
+ for i, run in enumerate(runs):
326
+ base_color = COLOR_PALETTE[i % len(COLOR_PALETTE)]
327
+
328
+ if smoothing:
329
+ color_map[f"{run}_smoothed"] = base_color
330
+ color_map[f"{run}_original"] = base_color + "4D"
331
+ else:
332
+ color_map[run] = base_color
333
+
334
+ return color_map
335
+
336
+ def get_space() -> str | None:
337
+ # Copy of gradio's utils.get_space()
338
+ if os.getenv("SYSTEM") == "spaces":
339
+ return os.getenv("SPACE_ID")
340
+ return None
341
+
342
+ def downsample(
343
+ df: pd.DataFrame,
344
+ x: str,
345
+ y: str,
346
+ color: str | None,
347
+ x_lim: tuple[float, float] | None = None,
348
+ ) -> pd.DataFrame:
349
+ if df.empty:
350
+ return df
351
+
352
+ columns_to_keep = [x, y]
353
+ if color is not None and color in df.columns:
354
+ columns_to_keep.append(color)
355
+ df = df[columns_to_keep].copy()
356
+
357
+ n_bins = 100
358
+
359
+ if color is not None and color in df.columns:
360
+ groups = df.groupby(color)
361
+ else:
362
+ groups = [(None, df)]
363
+
364
+ downsampled_indices = []
365
+
366
+ for _, group_df in groups:
367
+ if group_df.empty:
368
+ continue
369
+
370
+ group_df = group_df.sort_values(x)
371
+
372
+ if x_lim is not None:
373
+ x_min, x_max = x_lim
374
+ before_point = group_df[group_df[x] < x_min].tail(1)
375
+ after_point = group_df[group_df[x] > x_max].head(1)
376
+ group_df = group_df[(group_df[x] >= x_min) & (group_df[x] <= x_max)]
377
+ else:
378
+ before_point = after_point = None
379
+ x_min = group_df[x].min()
380
+ x_max = group_df[x].max()
381
+
382
+ if before_point is not None and not before_point.empty:
383
+ downsampled_indices.extend(before_point.index.tolist())
384
+ if after_point is not None and not after_point.empty:
385
+ downsampled_indices.extend(after_point.index.tolist())
386
+
387
+ if group_df.empty:
388
+ continue
389
+
390
+ if x_min == x_max:
391
+ min_y_idx = group_df[y].idxmin()
392
+ max_y_idx = group_df[y].idxmax()
393
+ if min_y_idx != max_y_idx:
394
+ downsampled_indices.extend([min_y_idx, max_y_idx])
395
+ else:
396
+ downsampled_indices.append(min_y_idx)
397
+ continue
398
+
399
+ if len(group_df) < 500:
400
+ downsampled_indices.extend(group_df.index.tolist())
401
+ continue
402
+
403
+ bins = np.linspace(x_min, x_max, n_bins + 1)
404
+ group_df["bin"] = pd.cut(
405
+ group_df[x], bins=bins, labels=False, include_lowest=True
406
+ )
407
+
408
+ for bin_idx in group_df["bin"].dropna().unique():
409
+ bin_data = group_df[group_df["bin"] == bin_idx]
410
+ if bin_data.empty:
411
+ continue
412
+
413
+ min_y_idx = bin_data[y].idxmin()
414
+ max_y_idx = bin_data[y].idxmax()
415
+
416
+ downsampled_indices.append(min_y_idx)
417
+ if min_y_idx != max_y_idx:
418
+ downsampled_indices.append(max_y_idx)
419
+
420
+ unique_indices = list(set(downsampled_indices))
421
+
422
+ downsampled_df = df.loc[unique_indices].copy()
423
+ downsampled_df = downsampled_df.sort_values(x).reset_index(drop=True)
424
+ downsampled_df = downsampled_df.drop(columns=["bin"], errors="ignore")
425
+
426
+ return downsampled_df
427
+
428
+
429
+ def sort_metrics_by_prefix(metrics: list[str]) -> list[str]:
430
+ """
431
+ Sort metrics by grouping prefixes together for dropdown/list display.
432
+ Metrics without prefixes come first, then grouped by prefix.
433
+
434
+ Args:
435
+ metrics: List of metric names
436
+
437
+ Returns:
438
+ List of metric names sorted by prefix
439
+
440
+ Example:
441
+ Input: ["train/loss", "loss", "train/acc", "val/loss"]
442
+ Output: ["loss", "train/acc", "train/loss", "val/loss"]
443
+ """
444
+ groups = group_metrics_by_prefix(metrics)
445
+ result = []
446
+
447
+ if "charts" in groups:
448
+ result.extend(groups["charts"])
449
+
450
+ for group_name in sorted(groups.keys()):
451
+ if group_name != "charts":
452
+ result.extend(groups[group_name])
453
+
454
+ return result
455
+
456
+
457
+ def group_metrics_by_prefix(metrics: list[str]) -> dict[str, list[str]]:
458
+ """
459
+ Group metrics by their prefix. Metrics without prefix go to 'charts' group.
460
+
461
+ Args:
462
+ metrics: List of metric names
463
+
464
+ Returns:
465
+ Dictionary with prefix names as keys and lists of metrics as values
466
+
467
+ Example:
468
+ Input: ["loss", "accuracy", "train/loss", "train/acc", "val/loss"]
469
+ Output: {
470
+ "charts": ["loss", "accuracy"],
471
+ "train": ["train/loss", "train/acc"],
472
+ "val": ["val/loss"]
473
+ }
474
+ """
475
+ no_prefix = []
476
+ with_prefix = []
477
+
478
+ for metric in metrics:
479
+ if "/" in metric:
480
+ with_prefix.append(metric)
481
+ else:
482
+ no_prefix.append(metric)
483
+
484
+ no_prefix.sort()
485
+
486
+ prefix_groups = {}
487
+ for metric in with_prefix:
488
+ prefix = metric.split("/")[0]
489
+ if prefix not in prefix_groups:
490
+ prefix_groups[prefix] = []
491
+ prefix_groups[prefix].append(metric)
492
+
493
+ for prefix in prefix_groups:
494
+ prefix_groups[prefix].sort()
495
+
496
+ groups = {}
497
+ if no_prefix:
498
+ groups["charts"] = no_prefix
499
+
500
+ for prefix in sorted(prefix_groups.keys()):
501
+ groups[prefix] = prefix_groups[prefix]
502
+
503
+ return groups
504
+
505
+
506
+ def group_metrics_with_subprefixes(metrics: list[str]) -> dict:
507
+ """
508
+ Group metrics with simple 2-level nested structure detection.
509
+
510
+ Returns a dictionary where each prefix group can have:
511
+ - direct_metrics: list of metrics at this level (e.g., "train/acc")
512
+ - subgroups: dict of subgroup name -> list of metrics (e.g., "loss" -> ["train/loss/norm", "train/loss/unnorm"])
513
+
514
+ Example:
515
+ Input: ["loss", "train/acc", "train/loss/normalized", "train/loss/unnormalized", "val/loss"]
516
+ Output: {
517
+ "charts": {
518
+ "direct_metrics": ["loss"],
519
+ "subgroups": {}
520
+ },
521
+ "train": {
522
+ "direct_metrics": ["train/acc"],
523
+ "subgroups": {
524
+ "loss": ["train/loss/normalized", "train/loss/unnormalized"]
525
+ }
526
+ },
527
+ "val": {
528
+ "direct_metrics": ["val/loss"],
529
+ "subgroups": {}
530
+ }
531
+ }
532
+ """
533
+ result = {}
534
+
535
+ for metric in metrics:
536
+ if "/" not in metric:
537
+ if "charts" not in result:
538
+ result["charts"] = {"direct_metrics": [], "subgroups": {}}
539
+ result["charts"]["direct_metrics"].append(metric)
540
+ else:
541
+ parts = metric.split("/")
542
+ main_prefix = parts[0]
543
+
544
+ if main_prefix not in result:
545
+ result[main_prefix] = {"direct_metrics": [], "subgroups": {}}
546
+
547
+ if len(parts) == 2:
548
+ result[main_prefix]["direct_metrics"].append(metric)
549
+ else:
550
+ subprefix = parts[1]
551
+ if subprefix not in result[main_prefix]["subgroups"]:
552
+ result[main_prefix]["subgroups"][subprefix] = []
553
+ result[main_prefix]["subgroups"][subprefix].append(metric)
554
+
555
+ for group_data in result.values():
556
+ group_data["direct_metrics"].sort()
557
+ for subgroup_metrics in group_data["subgroups"].values():
558
+ subgroup_metrics.sort()
559
+
560
+ if "charts" in result and not result["charts"]["direct_metrics"]:
561
+ del result["charts"]
562
+
563
+ return result
564
+
565
+
566
+ def get_sync_status(scheduler: "CommitScheduler | DummyCommitScheduler") -> int | None:
567
+ """Get the sync status from the CommitScheduler in an integer number of minutes, or None if not synced yet."""
568
+ if getattr(
569
+ scheduler, "last_push_time", None
570
+ ): # DummyCommitScheduler doesn't have last_push_time
571
+ time_diff = time.time() - scheduler.last_push_time
572
+ return int(time_diff / 60)
573
+ else:
574
+ return None
version.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 0.3.0.dev0