pardeep-singh commited on
Commit
7854d23
·
verified ·
1 Parent(s): e1de37b

Upload folder using huggingface_hub

Browse files
.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,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from huggingface_hub import SpaceStorage
13
+
14
+ from trackio import context_vars, deploy, utils
15
+ from trackio.imports import import_csv, import_tf_events
16
+ from trackio.media import TrackioImage, TrackioVideo
17
+ from trackio.run import Run
18
+ from trackio.sqlite_storage import SQLiteStorage
19
+ from trackio.table import Table
20
+ from trackio.ui import demo
21
+ from trackio.utils import TRACKIO_DIR, TRACKIO_LOGO_DIR
22
+
23
+ __version__ = Path(__file__).parent.joinpath("version.txt").read_text().strip()
24
+
25
+ __all__ = [
26
+ "init",
27
+ "log",
28
+ "finish",
29
+ "show",
30
+ "import_csv",
31
+ "import_tf_events",
32
+ "Image",
33
+ "Video",
34
+ "Table",
35
+ ]
36
+
37
+ Image = TrackioImage
38
+ Video = TrackioVideo
39
+
40
+
41
+ config = {}
42
+
43
+ DEFAULT_THEME = "citrus"
44
+
45
+
46
+ def init(
47
+ project: str,
48
+ name: str | None = None,
49
+ space_id: str | None = None,
50
+ space_storage: SpaceStorage | None = None,
51
+ dataset_id: str | None = None,
52
+ config: dict | None = None,
53
+ resume: str = "never",
54
+ settings: Any = None,
55
+ ) -> Run:
56
+ """
57
+ Creates a new Trackio project and returns a [`Run`] object.
58
+
59
+ Args:
60
+ project (`str`):
61
+ The name of the project (can be an existing project to continue tracking or
62
+ a new project to start tracking from scratch).
63
+ name (`str` or `None`, *optional*, defaults to `None`):
64
+ The name of the run (if not provided, a default name will be generated).
65
+ space_id (`str` or `None`, *optional*, defaults to `None`):
66
+ If provided, the project will be logged to a Hugging Face Space instead of
67
+ a local directory. Should be a complete Space name like
68
+ `"username/reponame"` or `"orgname/reponame"`, or just `"reponame"` in which
69
+ case the Space will be created in the currently-logged-in Hugging Face
70
+ user's namespace. If the Space does not exist, it will be created. If the
71
+ Space already exists, the project will be logged to it.
72
+ space_storage ([`~huggingface_hub.SpaceStorage`] or `None`, *optional*, defaults to `None`):
73
+ Choice of persistent storage tier.
74
+ dataset_id (`str` or `None`, *optional*, defaults to `None`):
75
+ If a `space_id` is provided, a persistent Hugging Face Dataset will be
76
+ created and the metrics will be synced to it every 5 minutes. Specify a
77
+ Dataset with name like `"username/datasetname"` or `"orgname/datasetname"`,
78
+ or `"datasetname"` (uses currently-logged-in Hugging Face user's namespace),
79
+ or `None` (uses the same name as the Space but with the `"_dataset"`
80
+ suffix). If the Dataset does not exist, it will be created. If the Dataset
81
+ already exists, the project will be appended to it.
82
+ config (`dict` or `None`, *optional*, defaults to `None`):
83
+ A dictionary of configuration options. Provided for compatibility with
84
+ `wandb.init()`.
85
+ resume (`str`, *optional*, defaults to `"never"`):
86
+ Controls how to handle resuming a run. Can be one of:
87
+
88
+ - `"must"`: Must resume the run with the given name, raises error if run
89
+ doesn't exist
90
+ - `"allow"`: Resume the run if it exists, otherwise create a new run
91
+ - `"never"`: Never resume a run, always create a new one
92
+ settings (`Any`, *optional*, defaults to `None`):
93
+ Not used. Provided for compatibility with `wandb.init()`.
94
+
95
+ Returns:
96
+ `Run`: A [`Run`] object that can be used to log metrics and finish the run.
97
+ """
98
+ if settings is not None:
99
+ warnings.warn(
100
+ "* 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."
101
+ )
102
+
103
+ if space_id is None and dataset_id is not None:
104
+ raise ValueError("Must provide a `space_id` when `dataset_id` is provided.")
105
+ space_id, dataset_id = utils.preprocess_space_and_dataset_ids(space_id, dataset_id)
106
+ url = context_vars.current_server.get()
107
+
108
+ if url is None:
109
+ if space_id is None:
110
+ _, url, _ = demo.launch(
111
+ show_api=False,
112
+ inline=False,
113
+ quiet=True,
114
+ prevent_thread_lock=True,
115
+ show_error=True,
116
+ )
117
+ else:
118
+ url = space_id
119
+ context_vars.current_server.set(url)
120
+
121
+ if (
122
+ context_vars.current_project.get() is None
123
+ or context_vars.current_project.get() != project
124
+ ):
125
+ print(f"* Trackio project initialized: {project}")
126
+
127
+ if dataset_id is not None:
128
+ os.environ["TRACKIO_DATASET_ID"] = dataset_id
129
+ print(
130
+ f"* Trackio metrics will be synced to Hugging Face Dataset: {dataset_id}"
131
+ )
132
+ if space_id is None:
133
+ print(f"* Trackio metrics logged to: {TRACKIO_DIR}")
134
+ utils.print_dashboard_instructions(project)
135
+ else:
136
+ deploy.create_space_if_not_exists(space_id, space_storage, dataset_id)
137
+ print(
138
+ f"* View dashboard by going to: {deploy.SPACE_URL.format(space_id=space_id)}"
139
+ )
140
+ context_vars.current_project.set(project)
141
+
142
+ client = None
143
+ if not space_id:
144
+ client = Client(url, verbose=False)
145
+
146
+ if resume == "must":
147
+ if name is None:
148
+ raise ValueError("Must provide a run name when resume='must'")
149
+ if name not in SQLiteStorage.get_runs(project):
150
+ raise ValueError(f"Run '{name}' does not exist in project '{project}'")
151
+ resumed = True
152
+ elif resume == "allow":
153
+ resumed = name is not None and name in SQLiteStorage.get_runs(project)
154
+ elif resume == "never":
155
+ if name is not None and name in SQLiteStorage.get_runs(project):
156
+ warnings.warn(
157
+ f"* Warning: resume='never' but a run '{name}' already exists in "
158
+ f"project '{project}'. Generating a new name and instead. If you want "
159
+ "to resume this run, call init() with resume='must' or resume='allow'."
160
+ )
161
+ name = None
162
+ resumed = False
163
+ else:
164
+ raise ValueError("resume must be one of: 'must', 'allow', or 'never'")
165
+
166
+ run = Run(
167
+ url=url,
168
+ project=project,
169
+ client=client,
170
+ name=name,
171
+ config=config,
172
+ space_id=space_id,
173
+ )
174
+
175
+ if resumed:
176
+ print(f"* Resumed existing run: {run.name}")
177
+ else:
178
+ print(f"* Created new run: {run.name}")
179
+
180
+ context_vars.current_run.set(run)
181
+ globals()["config"] = run.config
182
+ return run
183
+
184
+
185
+ def log(metrics: dict, step: int | None = None) -> None:
186
+ """
187
+ Logs metrics to the current run.
188
+
189
+ Args:
190
+ metrics (`dict`):
191
+ A dictionary of metrics to log.
192
+ step (`int` or `None`, *optional*, defaults to `None`):
193
+ The step number. If not provided, the step will be incremented
194
+ automatically.
195
+ """
196
+ run = context_vars.current_run.get()
197
+ if run is None:
198
+ raise RuntimeError("Call trackio.init() before trackio.log().")
199
+ run.log(
200
+ metrics=metrics,
201
+ step=step,
202
+ )
203
+
204
+
205
+ def finish():
206
+ """
207
+ Finishes the current run.
208
+ """
209
+ run = context_vars.current_run.get()
210
+ if run is None:
211
+ raise RuntimeError("Call trackio.init() before trackio.finish().")
212
+ run.finish()
213
+
214
+
215
+ def show(project: str | None = None, theme: str | ThemeClass = DEFAULT_THEME):
216
+ """
217
+ Launches the Trackio dashboard.
218
+
219
+ Args:
220
+ project (`str` or `None`, *optional*, defaults to `None`):
221
+ The name of the project whose runs to show. If not provided, all projects
222
+ will be shown and the user can select one.
223
+ theme (`str` or `ThemeClass`, *optional*, defaults to `"citrus"`):
224
+ A Gradio Theme to use for the dashboard instead of the default `"citrus"`,
225
+ can be a built-in theme (e.g. `'soft'`, `'default'`), a theme from the Hub
226
+ (e.g. `"gstaff/xkcd"`), or a custom Theme class.
227
+ """
228
+ if theme != DEFAULT_THEME:
229
+ # TODO: It's a little hacky to reproduce this theme-setting logic from Gradio Blocks,
230
+ # but in Gradio 6.0, the theme will be set in `launch()` instead, which means that we
231
+ # will be able to remove this code.
232
+ if isinstance(theme, str):
233
+ if theme.lower() in BUILT_IN_THEMES:
234
+ theme = BUILT_IN_THEMES[theme.lower()]
235
+ else:
236
+ try:
237
+ theme = ThemeClass.from_hub(theme)
238
+ except Exception as e:
239
+ warnings.warn(f"Cannot load {theme}. Caught Exception: {str(e)}")
240
+ theme = DefaultTheme()
241
+ if not isinstance(theme, ThemeClass):
242
+ warnings.warn("Theme should be a class loaded from gradio.themes")
243
+ theme = DefaultTheme()
244
+ demo.theme: ThemeClass = theme
245
+ demo.theme_css = theme._get_theme_css()
246
+ demo.stylesheets = theme._stylesheets
247
+ theme_hasher = hashlib.sha256()
248
+ theme_hasher.update(demo.theme_css.encode("utf-8"))
249
+ demo.theme_hash = theme_hasher.hexdigest()
250
+
251
+ _, url, share_url = demo.launch(
252
+ show_api=False,
253
+ quiet=True,
254
+ inline=False,
255
+ prevent_thread_lock=True,
256
+ favicon_path=TRACKIO_LOGO_DIR / "trackio_logo_light.png",
257
+ allowed_paths=[TRACKIO_LOGO_DIR],
258
+ )
259
+
260
+ base_url = share_url + "/" if share_url else url
261
+ dashboard_url = base_url + f"?project={project}" if project else base_url
262
+ print(f"* Trackio UI launched at: {dashboard_url}")
263
+ webbrowser.open(dashboard_url)
264
+ utils.block_except_in_notebook()
__pycache__/__init__.cpython-311.pyc ADDED
Binary file (12.6 kB). View file
 
__pycache__/cli.cpython-311.pyc ADDED
Binary file (1.59 kB). View file
 
__pycache__/commit_scheduler.cpython-311.pyc ADDED
Binary file (20.4 kB). View file
 
__pycache__/context_vars.cpython-311.pyc ADDED
Binary file (852 Bytes). View file
 
__pycache__/deploy.cpython-311.pyc ADDED
Binary file (9.34 kB). View file
 
__pycache__/dummy_commit_scheduler.cpython-311.pyc ADDED
Binary file (1.2 kB). View file
 
__pycache__/file_storage.cpython-311.pyc ADDED
Binary file (1.9 kB). View file
 
__pycache__/imports.cpython-311.pyc ADDED
Binary file (13.8 kB). View file
 
__pycache__/media.cpython-311.pyc ADDED
Binary file (15.2 kB). View file
 
__pycache__/run.cpython-311.pyc ADDED
Binary file (8.35 kB). View file
 
__pycache__/sqlite_storage.cpython-311.pyc ADDED
Binary file (25.3 kB). View file
 
__pycache__/table.cpython-311.pyc ADDED
Binary file (2.72 kB). View file
 
__pycache__/typehints.cpython-311.pyc ADDED
Binary file (1.07 kB). View file
 
__pycache__/ui.cpython-311.pyc ADDED
Binary file (38.1 kB). View file
 
__pycache__/utils.cpython-311.pyc ADDED
Binary file (21.6 kB). View file
 
__pycache__/video_writer.cpython-311.pyc ADDED
Binary file (5.73 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,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.metadata
2
+ import io
3
+ import os
4
+ import time
5
+ from importlib.resources import files
6
+ from pathlib import Path
7
+
8
+ import gradio
9
+ import huggingface_hub
10
+ from gradio_client import Client, handle_file
11
+ from httpx import ReadTimeout
12
+ from huggingface_hub.errors import RepositoryNotFoundError
13
+ from requests import HTTPError
14
+
15
+ import trackio
16
+ from trackio.sqlite_storage import SQLiteStorage
17
+
18
+ SPACE_URL = "https://huggingface.co/spaces/{space_id}"
19
+
20
+
21
+ def _is_trackio_installed_from_source() -> bool:
22
+ """Check if trackio is installed from source/editable install vs PyPI."""
23
+ try:
24
+ trackio_file = trackio.__file__
25
+ if "site-packages" not in trackio_file:
26
+ return True
27
+
28
+ dist = importlib.metadata.distribution("trackio")
29
+ if dist.files:
30
+ files = list(dist.files)
31
+ has_pth = any(".pth" in str(f) for f in files)
32
+ if has_pth:
33
+ return True
34
+
35
+ return False
36
+ except (
37
+ AttributeError,
38
+ importlib.metadata.PackageNotFoundError,
39
+ importlib.metadata.MetadataError,
40
+ ValueError,
41
+ TypeError,
42
+ ):
43
+ return True
44
+
45
+
46
+ def deploy_as_space(
47
+ space_id: str,
48
+ space_storage: huggingface_hub.SpaceStorage | None = None,
49
+ dataset_id: str | None = None,
50
+ ):
51
+ if (
52
+ os.getenv("SYSTEM") == "spaces"
53
+ ): # in case a repo with this function is uploaded to spaces
54
+ return
55
+
56
+ trackio_path = files("trackio")
57
+
58
+ hf_api = huggingface_hub.HfApi()
59
+
60
+ try:
61
+ huggingface_hub.create_repo(
62
+ space_id,
63
+ space_sdk="gradio",
64
+ space_storage=space_storage,
65
+ repo_type="space",
66
+ exist_ok=True,
67
+ )
68
+ except HTTPError as e:
69
+ if e.response.status_code in [401, 403]: # unauthorized or forbidden
70
+ print("Need 'write' access token to create a Spaces repo.")
71
+ huggingface_hub.login(add_to_git_credential=False)
72
+ huggingface_hub.create_repo(
73
+ space_id,
74
+ space_sdk="gradio",
75
+ space_storage=space_storage,
76
+ repo_type="space",
77
+ exist_ok=True,
78
+ )
79
+ else:
80
+ raise ValueError(f"Failed to create Space: {e}")
81
+
82
+ with open(Path(trackio_path, "README.md"), "r") as f:
83
+ readme_content = f.read()
84
+ readme_content = readme_content.replace("{GRADIO_VERSION}", gradio.__version__)
85
+ readme_buffer = io.BytesIO(readme_content.encode("utf-8"))
86
+ hf_api.upload_file(
87
+ path_or_fileobj=readme_buffer,
88
+ path_in_repo="README.md",
89
+ repo_id=space_id,
90
+ repo_type="space",
91
+ )
92
+
93
+ # We can assume pandas, gradio, and huggingface-hub are already installed in a Gradio Space.
94
+ # Make sure necessary dependencies are installed by creating a requirements.txt.
95
+ is_source_install = _is_trackio_installed_from_source()
96
+
97
+ if is_source_install:
98
+ requirements_content = """pyarrow>=21.0"""
99
+ else:
100
+ requirements_content = f"""pyarrow>=21.0
101
+ trackio=={trackio.__version__}"""
102
+
103
+ requirements_buffer = io.BytesIO(requirements_content.encode("utf-8"))
104
+ hf_api.upload_file(
105
+ path_or_fileobj=requirements_buffer,
106
+ path_in_repo="requirements.txt",
107
+ repo_id=space_id,
108
+ repo_type="space",
109
+ )
110
+
111
+ huggingface_hub.utils.disable_progress_bars()
112
+
113
+ if is_source_install:
114
+ hf_api.upload_folder(
115
+ repo_id=space_id,
116
+ repo_type="space",
117
+ folder_path=trackio_path,
118
+ ignore_patterns=["README.md"],
119
+ )
120
+ else:
121
+ app_file_content = """import trackio
122
+ trackio.show()"""
123
+ app_file_buffer = io.BytesIO(app_file_content.encode("utf-8"))
124
+ hf_api.upload_file(
125
+ path_or_fileobj=app_file_buffer,
126
+ path_in_repo="ui.py",
127
+ repo_id=space_id,
128
+ repo_type="space",
129
+ )
130
+
131
+ if hf_token := huggingface_hub.utils.get_token():
132
+ huggingface_hub.add_space_secret(space_id, "HF_TOKEN", hf_token)
133
+ if dataset_id is not None:
134
+ huggingface_hub.add_space_variable(space_id, "TRACKIO_DATASET_ID", dataset_id)
135
+
136
+
137
+ def create_space_if_not_exists(
138
+ space_id: str,
139
+ space_storage: huggingface_hub.SpaceStorage | None = None,
140
+ dataset_id: str | None = None,
141
+ ) -> None:
142
+ """
143
+ 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.
144
+
145
+ Args:
146
+ space_id: The ID of the Space to create.
147
+ dataset_id: The ID of the Dataset to add to the Space.
148
+ """
149
+ if "/" not in space_id:
150
+ raise ValueError(
151
+ f"Invalid space ID: {space_id}. Must be in the format: username/reponame or orgname/reponame."
152
+ )
153
+ if dataset_id is not None and "/" not in dataset_id:
154
+ raise ValueError(
155
+ f"Invalid dataset ID: {dataset_id}. Must be in the format: username/datasetname or orgname/datasetname."
156
+ )
157
+ try:
158
+ huggingface_hub.repo_info(space_id, repo_type="space")
159
+ print(f"* Found existing space: {SPACE_URL.format(space_id=space_id)}")
160
+ if dataset_id is not None:
161
+ huggingface_hub.add_space_variable(
162
+ space_id, "TRACKIO_DATASET_ID", dataset_id
163
+ )
164
+ return
165
+ except RepositoryNotFoundError:
166
+ pass
167
+ except HTTPError as e:
168
+ if e.response.status_code in [401, 403]: # unauthorized or forbidden
169
+ print("Need 'write' access token to create a Spaces repo.")
170
+ huggingface_hub.login(add_to_git_credential=False)
171
+ huggingface_hub.add_space_variable(
172
+ space_id, "TRACKIO_DATASET_ID", dataset_id
173
+ )
174
+ else:
175
+ raise ValueError(f"Failed to create Space: {e}")
176
+
177
+ print(f"* Creating new space: {SPACE_URL.format(space_id=space_id)}")
178
+ deploy_as_space(space_id, space_storage, dataset_id)
179
+
180
+
181
+ def wait_until_space_exists(
182
+ space_id: str,
183
+ ) -> None:
184
+ """
185
+ Blocks the current thread until the space exists.
186
+ May raise a TimeoutError if this takes quite a while.
187
+
188
+ Args:
189
+ space_id: The ID of the Space to wait for.
190
+ """
191
+ delay = 1
192
+ for _ in range(10):
193
+ try:
194
+ Client(space_id, verbose=False)
195
+ return
196
+ except (ReadTimeout, ValueError):
197
+ time.sleep(delay)
198
+ delay = min(delay * 2, 30)
199
+ raise TimeoutError("Waiting for space to exist took longer than expected")
200
+
201
+
202
+ def upload_db_to_space(project: str, space_id: str) -> None:
203
+ """
204
+ Uploads the database of a local Trackio project to a Hugging Face Space.
205
+
206
+ Args:
207
+ project: The name of the project to upload.
208
+ space_id: The ID of the Space to upload to.
209
+ """
210
+ db_path = SQLiteStorage.get_project_db_path(project)
211
+ client = Client(space_id, verbose=False)
212
+ client.predict(
213
+ api_name="/upload_db_to_space",
214
+ project=project,
215
+ uploaded_db=handle_file(db_path),
216
+ hf_token=huggingface_hub.utils.get_token(),
217
+ )
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,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+
3
+ try: # absolute imports when installed
4
+ from trackio.utils import MEDIA_DIR
5
+ except ImportError: # relative imports for local execution on Spaces
6
+ from utils import MEDIA_DIR
7
+
8
+
9
+ class FileStorage:
10
+ @staticmethod
11
+ def get_project_media_path(
12
+ project: str,
13
+ run: str | None = None,
14
+ step: int | None = None,
15
+ filename: str | None = None,
16
+ ) -> Path:
17
+ if filename is not None and step is None:
18
+ raise ValueError("filename requires step")
19
+ if step is not None and run is None:
20
+ raise ValueError("step requires run")
21
+
22
+ path = MEDIA_DIR / project
23
+ if run:
24
+ path /= run
25
+ if step is not None:
26
+ path /= str(step)
27
+ if filename:
28
+ path /= filename
29
+ return path
30
+
31
+ @staticmethod
32
+ def init_project_media_path(
33
+ project: str, run: str | None = None, step: int | None = None
34
+ ) -> Path:
35
+ path = FileStorage.get_project_media_path(project, run, step)
36
+ path.mkdir(parents=True, exist_ok=True)
37
+ return path
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,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import uuid
4
+ from abc import ABC, abstractmethod
5
+ from pathlib import Path
6
+ from typing import Literal
7
+
8
+ import numpy as np
9
+ from PIL import Image as PILImage
10
+
11
+ try: # absolute imports when installed
12
+ from trackio.file_storage import FileStorage
13
+ from trackio.utils import MEDIA_DIR
14
+ from trackio.video_writer import write_video
15
+ except ImportError: # relative imports for local execution on Spaces
16
+ from file_storage import FileStorage
17
+ from utils import MEDIA_DIR
18
+ from video_writer import write_video
19
+
20
+
21
+ class TrackioMedia(ABC):
22
+ """
23
+ Abstract base class for Trackio media objects
24
+ Provides shared functionality for file handling and serialization.
25
+ """
26
+
27
+ TYPE: str
28
+
29
+ def __init_subclass__(cls, **kwargs):
30
+ """Ensure subclasses define the TYPE attribute."""
31
+ super().__init_subclass__(**kwargs)
32
+ if not hasattr(cls, "TYPE") or cls.TYPE is None:
33
+ raise TypeError(f"Class {cls.__name__} must define TYPE attribute")
34
+
35
+ def __init__(self, value, caption: str | None = None):
36
+ self.caption = caption
37
+ self._value = value
38
+ self._file_path: Path | None = None
39
+
40
+ # Validate file existence for string/Path inputs
41
+ if isinstance(self._value, str | Path):
42
+ if not os.path.isfile(self._value):
43
+ raise ValueError(f"File not found: {self._value}")
44
+
45
+ def _file_extension(self) -> str:
46
+ if self._file_path:
47
+ return self._file_path.suffix[1:].lower()
48
+ if isinstance(self._value, str | Path):
49
+ path = Path(self._value)
50
+ return path.suffix[1:].lower()
51
+ if hasattr(self, "_format") and self._format:
52
+ return self._format
53
+ return "unknown"
54
+
55
+ def _get_relative_file_path(self) -> Path | None:
56
+ return self._file_path
57
+
58
+ def _get_absolute_file_path(self) -> Path | None:
59
+ if self._file_path:
60
+ return MEDIA_DIR / self._file_path
61
+ return None
62
+
63
+ def _save(self, project: str, run: str, step: int = 0):
64
+ if self._file_path:
65
+ return
66
+
67
+ media_dir = FileStorage.init_project_media_path(project, run, step)
68
+ filename = f"{uuid.uuid4()}.{self._file_extension()}"
69
+ file_path = media_dir / filename
70
+
71
+ # Delegate to subclass-specific save logic
72
+ self._save_media(file_path)
73
+
74
+ self._file_path = file_path.relative_to(MEDIA_DIR)
75
+
76
+ @abstractmethod
77
+ def _save_media(self, file_path: Path):
78
+ """
79
+ Performs the actual media saving logic.
80
+ """
81
+ pass
82
+
83
+ def _to_dict(self) -> dict:
84
+ if not self._file_path:
85
+ raise ValueError("Media must be saved to file before serialization")
86
+ return {
87
+ "_type": self.TYPE,
88
+ "file_path": str(self._get_relative_file_path()),
89
+ "caption": self.caption,
90
+ }
91
+
92
+
93
+ TrackioImageSourceType = str | Path | np.ndarray | PILImage.Image
94
+
95
+
96
+ class TrackioImage(TrackioMedia):
97
+ """
98
+ Initializes an Image object.
99
+
100
+ Example:
101
+ ```python
102
+ import trackio
103
+ import numpy as np
104
+ from PIL import Image
105
+
106
+ # Create an image from numpy array
107
+ image_data = np.random.randint(0, 255, (64, 64, 3), dtype=np.uint8)
108
+ image = trackio.Image(image_data, caption="Random image")
109
+ trackio.log({"my_image": image})
110
+
111
+ # Create an image from PIL Image
112
+ pil_image = Image.new('RGB', (100, 100), color='red')
113
+ image = trackio.Image(pil_image, caption="Red square")
114
+ trackio.log({"red_image": image})
115
+
116
+ # Create an image from file path
117
+ image = trackio.Image("path/to/image.jpg", caption="Photo from file")
118
+ trackio.log({"file_image": image})
119
+ ```
120
+
121
+ Args:
122
+ value (`str`, `Path`, `numpy.ndarray`, or `PIL.Image`, *optional*, defaults to `None`):
123
+ A path to an image, a PIL Image, or a numpy array of shape (height, width, channels).
124
+ caption (`str`, *optional*, defaults to `None`):
125
+ A string caption for the image.
126
+ """
127
+
128
+ TYPE = "trackio.image"
129
+
130
+ def __init__(self, value: TrackioImageSourceType, caption: str | None = None):
131
+ super().__init__(value, caption)
132
+ self._format: str | None = None
133
+
134
+ if (
135
+ isinstance(self._value, np.ndarray | PILImage.Image)
136
+ and self._format is None
137
+ ):
138
+ self._format = "png"
139
+
140
+ def _as_pil(self) -> PILImage.Image | None:
141
+ try:
142
+ if isinstance(self._value, np.ndarray):
143
+ arr = np.asarray(self._value).astype("uint8")
144
+ return PILImage.fromarray(arr).convert("RGBA")
145
+ if isinstance(self._value, PILImage.Image):
146
+ return self._value.convert("RGBA")
147
+ except Exception as e:
148
+ raise ValueError(f"Failed to process image data: {self._value}") from e
149
+ return None
150
+
151
+ def _save_media(self, file_path: Path):
152
+ if pil := self._as_pil():
153
+ pil.save(file_path, format=self._format)
154
+ elif isinstance(self._value, str | Path):
155
+ if os.path.isfile(self._value):
156
+ shutil.copy(self._value, file_path)
157
+ else:
158
+ raise ValueError(f"File not found: {self._value}")
159
+
160
+
161
+ TrackioVideoSourceType = str | Path | np.ndarray
162
+ TrackioVideoFormatType = Literal["gif", "mp4", "webm"]
163
+
164
+
165
+ class TrackioVideo(TrackioMedia):
166
+ """
167
+ Initializes a Video object.
168
+
169
+ Example:
170
+ ```python
171
+ import trackio
172
+ import numpy as np
173
+
174
+ # Create a simple video from numpy array
175
+ frames = np.random.randint(0, 255, (10, 3, 64, 64), dtype=np.uint8)
176
+ video = trackio.Video(frames, caption="Random video", fps=30)
177
+
178
+ # Create a batch of videos
179
+ batch_frames = np.random.randint(0, 255, (3, 10, 3, 64, 64), dtype=np.uint8)
180
+ batch_video = trackio.Video(batch_frames, caption="Batch of videos", fps=15)
181
+
182
+ # Create video from file path
183
+ video = trackio.Video("path/to/video.mp4", caption="Video from file")
184
+ ```
185
+
186
+ Args:
187
+ value (`str`, `Path`, or `numpy.ndarray`, *optional*, defaults to `None`):
188
+ A path to a video file, or a numpy array.
189
+ The array should be of type `np.uint8` with RGB values in the range `[0, 255]`.
190
+ It is expected to have shape of either (frames, channels, height, width) or (batch, frames, channels, height, width).
191
+ For the latter, the videos will be tiled into a grid.
192
+ caption (`str`, *optional*, defaults to `None`):
193
+ A string caption for the video.
194
+ fps (`int`, *optional*, defaults to `None`):
195
+ Frames per second for the video. Only used when value is an ndarray. Default is `24`.
196
+ format (`Literal["gif", "mp4", "webm"]`, *optional*, defaults to `None`):
197
+ Video format ("gif", "mp4", or "webm"). Only used when value is an ndarray. Default is "gif".
198
+ """
199
+
200
+ TYPE = "trackio.video"
201
+
202
+ def __init__(
203
+ self,
204
+ value: TrackioVideoSourceType,
205
+ caption: str | None = None,
206
+ fps: int | None = None,
207
+ format: TrackioVideoFormatType | None = None,
208
+ ):
209
+ super().__init__(value, caption)
210
+ if isinstance(value, np.ndarray):
211
+ if format is None:
212
+ format = "gif"
213
+ if fps is None:
214
+ fps = 24
215
+ self._fps = fps
216
+ self._format = format
217
+
218
+ @property
219
+ def _codec(self) -> str:
220
+ match self._format:
221
+ case "gif":
222
+ return "gif"
223
+ case "mp4":
224
+ return "h264"
225
+ case "webm":
226
+ return "vp9"
227
+ case _:
228
+ raise ValueError(f"Unsupported format: {self._format}")
229
+
230
+ def _save_media(self, file_path: Path):
231
+ if isinstance(self._value, np.ndarray):
232
+ video = TrackioVideo._process_ndarray(self._value)
233
+ write_video(file_path, video, fps=self._fps, codec=self._codec)
234
+ elif isinstance(self._value, str | Path):
235
+ if os.path.isfile(self._value):
236
+ shutil.copy(self._value, file_path)
237
+ else:
238
+ raise ValueError(f"File not found: {self._value}")
239
+
240
+ @staticmethod
241
+ def _process_ndarray(value: np.ndarray) -> np.ndarray:
242
+ # Verify value is either 4D (single video) or 5D array (batched videos).
243
+ # Expected format: (frames, channels, height, width) or (batch, frames, channels, height, width)
244
+ if value.ndim < 4:
245
+ raise ValueError(
246
+ "Video requires at least 4 dimensions (frames, channels, height, width)"
247
+ )
248
+ if value.ndim > 5:
249
+ raise ValueError(
250
+ "Videos can have at most 5 dimensions (batch, frames, channels, height, width)"
251
+ )
252
+ if value.ndim == 4:
253
+ # Reshape to 5D with single batch: (1, frames, channels, height, width)
254
+ value = value[np.newaxis, ...]
255
+
256
+ value = TrackioVideo._tile_batched_videos(value)
257
+ return value
258
+
259
+ @staticmethod
260
+ def _tile_batched_videos(video: np.ndarray) -> np.ndarray:
261
+ """
262
+ Tiles a batch of videos into a grid of videos.
263
+
264
+ Input format: (batch, frames, channels, height, width) - original FCHW format
265
+ Output format: (frames, total_height, total_width, channels)
266
+ """
267
+ batch_size, frames, channels, height, width = video.shape
268
+
269
+ next_pow2 = 1 << (batch_size - 1).bit_length()
270
+ if batch_size != next_pow2:
271
+ pad_len = next_pow2 - batch_size
272
+ pad_shape = (pad_len, frames, channels, height, width)
273
+ padding = np.zeros(pad_shape, dtype=video.dtype)
274
+ video = np.concatenate((video, padding), axis=0)
275
+ batch_size = next_pow2
276
+
277
+ n_rows = 1 << ((batch_size.bit_length() - 1) // 2)
278
+ n_cols = batch_size // n_rows
279
+
280
+ # Reshape to grid layout: (n_rows, n_cols, frames, channels, height, width)
281
+ video = video.reshape(n_rows, n_cols, frames, channels, height, width)
282
+
283
+ # Rearrange dimensions to (frames, total_height, total_width, channels)
284
+ video = video.transpose(2, 0, 4, 1, 5, 3)
285
+ video = video.reshape(frames, n_rows * height, n_cols * width, channels)
286
+ return video
py.typed ADDED
File without changes
run.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 TrackioMedia
8
+ from trackio.sqlite_storage import SQLiteStorage
9
+ from trackio.table import Table
10
+ from trackio.typehints import LogEntry, UploadEntry
11
+ from trackio.utils import (
12
+ RESERVED_KEYS,
13
+ fibo,
14
+ generate_readable_name,
15
+ serialize_values,
16
+ )
17
+
18
+ BATCH_SEND_INTERVAL = 0.5
19
+
20
+
21
+ class Run:
22
+ def __init__(
23
+ self,
24
+ url: str,
25
+ project: str,
26
+ client: Client | None,
27
+ name: str | None = None,
28
+ config: dict | None = None,
29
+ space_id: str | None = None,
30
+ ):
31
+ self.url = url
32
+ self.project = project
33
+ self._client_lock = threading.Lock()
34
+ self._client_thread = None
35
+ self._client = client
36
+ self._space_id = space_id
37
+ self.name = name or generate_readable_name(
38
+ SQLiteStorage.get_runs(project), space_id
39
+ )
40
+ self.config = config or {}
41
+ self._queued_logs: list[LogEntry] = []
42
+ self._queued_uploads: list[UploadEntry] = []
43
+ self._stop_flag = threading.Event()
44
+
45
+ self._client_thread = threading.Thread(target=self._init_client_background)
46
+ self._client_thread.daemon = True
47
+ self._client_thread.start()
48
+
49
+ def _batch_sender(self):
50
+ """Send batched logs every BATCH_SEND_INTERVAL."""
51
+ while not self._stop_flag.is_set() or len(self._queued_logs) > 0:
52
+ # If the stop flag has been set, then just quickly send all
53
+ # the logs and exit.
54
+ if not self._stop_flag.is_set():
55
+ time.sleep(BATCH_SEND_INTERVAL)
56
+
57
+ with self._client_lock:
58
+ if self._client is None:
59
+ return
60
+ if self._queued_logs:
61
+ logs_to_send = self._queued_logs.copy()
62
+ self._queued_logs.clear()
63
+ self._client.predict(
64
+ api_name="/bulk_log",
65
+ logs=logs_to_send,
66
+ hf_token=huggingface_hub.utils.get_token(),
67
+ )
68
+ if self._queued_uploads:
69
+ uploads_to_send = self._queued_uploads.copy()
70
+ self._queued_uploads.clear()
71
+ self._client.predict(
72
+ api_name="/bulk_upload_media",
73
+ uploads=uploads_to_send,
74
+ hf_token=huggingface_hub.utils.get_token(),
75
+ )
76
+
77
+ def _init_client_background(self):
78
+ if self._client is None:
79
+ fib = fibo()
80
+ for sleep_coefficient in fib:
81
+ try:
82
+ client = Client(self.url, verbose=False)
83
+
84
+ with self._client_lock:
85
+ self._client = client
86
+ break
87
+ except Exception:
88
+ pass
89
+ if sleep_coefficient is not None:
90
+ time.sleep(0.1 * sleep_coefficient)
91
+
92
+ self._batch_sender()
93
+
94
+ def _process_media(self, metrics, step: int | None) -> dict:
95
+ """
96
+ Serialize media in metrics and upload to space if needed.
97
+ """
98
+ serializable_metrics = {}
99
+ if not step:
100
+ step = 0
101
+ for key, value in metrics.items():
102
+ if isinstance(value, TrackioMedia):
103
+ value._save(self.project, self.name, step)
104
+ serializable_metrics[key] = value._to_dict()
105
+ if self._space_id:
106
+ # Upload local media when deploying to space
107
+ upload_entry: UploadEntry = {
108
+ "project": self.project,
109
+ "run": self.name,
110
+ "step": step,
111
+ "uploaded_file": handle_file(value._get_absolute_file_path()),
112
+ }
113
+ with self._client_lock:
114
+ self._queued_uploads.append(upload_entry)
115
+ else:
116
+ serializable_metrics[key] = value
117
+ return serializable_metrics
118
+
119
+ @staticmethod
120
+ def _replace_tables(metrics):
121
+ for k, v in metrics.items():
122
+ if isinstance(v, Table):
123
+ metrics[k] = v._to_dict()
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
+ Run._replace_tables(metrics)
132
+
133
+ metrics = self._process_media(metrics, step)
134
+ metrics = serialize_values(metrics)
135
+ log_entry: LogEntry = {
136
+ "project": self.project,
137
+ "run": self.name,
138
+ "metrics": metrics,
139
+ "step": step,
140
+ }
141
+
142
+ with self._client_lock:
143
+ self._queued_logs.append(log_entry)
144
+
145
+ def finish(self):
146
+ """Cleanup when run is finished."""
147
+ self._stop_flag.set()
148
+
149
+ # Wait for the batch sender to finish before joining the client thread.
150
+ time.sleep(2 * BATCH_SEND_INTERVAL)
151
+
152
+ if self._client_thread is not None:
153
+ print(
154
+ f"* Run finished. Uploading logs to Trackio Space: {self.url} (please wait...)"
155
+ )
156
+ self._client_thread.join()
sqlite_storage.py ADDED
@@ -0,0 +1,440 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fcntl
2
+ import json
3
+ import os
4
+ import sqlite3
5
+ import time
6
+ from datetime import datetime
7
+ from pathlib import Path
8
+ from threading import Lock
9
+
10
+ import huggingface_hub as hf
11
+ import pandas as pd
12
+
13
+ try: # absolute imports when installed
14
+ from trackio.commit_scheduler import CommitScheduler
15
+ from trackio.dummy_commit_scheduler import DummyCommitScheduler
16
+ from trackio.utils import (
17
+ TRACKIO_DIR,
18
+ deserialize_values,
19
+ serialize_values,
20
+ )
21
+ except Exception: # relative imports for local execution on Spaces
22
+ from commit_scheduler import CommitScheduler
23
+ from dummy_commit_scheduler import DummyCommitScheduler
24
+ from utils import TRACKIO_DIR, deserialize_values, serialize_values
25
+
26
+
27
+ class ProcessLock:
28
+ """A simple file-based lock that works across processes."""
29
+
30
+ def __init__(self, lockfile_path: Path):
31
+ self.lockfile_path = lockfile_path
32
+ self.lockfile = None
33
+
34
+ def __enter__(self):
35
+ """Acquire the lock with retry logic."""
36
+ self.lockfile_path.parent.mkdir(parents=True, exist_ok=True)
37
+ self.lockfile = open(self.lockfile_path, "w")
38
+
39
+ max_retries = 100
40
+ for attempt in range(max_retries):
41
+ try:
42
+ fcntl.flock(self.lockfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
43
+ return self
44
+ except IOError:
45
+ if attempt < max_retries - 1:
46
+ time.sleep(0.1)
47
+ else:
48
+ raise IOError("Could not acquire database lock after 10 seconds")
49
+
50
+ def __exit__(self, exc_type, exc_val, exc_tb):
51
+ """Release the lock."""
52
+ if self.lockfile:
53
+ fcntl.flock(self.lockfile.fileno(), fcntl.LOCK_UN)
54
+ self.lockfile.close()
55
+
56
+
57
+ class SQLiteStorage:
58
+ _dataset_import_attempted = False
59
+ _current_scheduler: CommitScheduler | DummyCommitScheduler | None = None
60
+ _scheduler_lock = Lock()
61
+
62
+ @staticmethod
63
+ def _get_connection(db_path: Path) -> sqlite3.Connection:
64
+ conn = sqlite3.connect(str(db_path), timeout=30.0)
65
+ conn.execute("PRAGMA journal_mode = WAL")
66
+ conn.row_factory = sqlite3.Row
67
+ return conn
68
+
69
+ @staticmethod
70
+ def _get_process_lock(project: str) -> ProcessLock:
71
+ lockfile_path = TRACKIO_DIR / f"{project}.lock"
72
+ return ProcessLock(lockfile_path)
73
+
74
+ @staticmethod
75
+ def get_project_db_filename(project: str) -> Path:
76
+ """Get the database filename for a specific project."""
77
+ safe_project_name = "".join(
78
+ c for c in project if c.isalnum() or c in ("-", "_")
79
+ ).rstrip()
80
+ if not safe_project_name:
81
+ safe_project_name = "default"
82
+ return f"{safe_project_name}.db"
83
+
84
+ @staticmethod
85
+ def get_project_db_path(project: str) -> Path:
86
+ """Get the database path for a specific project."""
87
+ filename = SQLiteStorage.get_project_db_filename(project)
88
+ return TRACKIO_DIR / filename
89
+
90
+ @staticmethod
91
+ def init_db(project: str) -> Path:
92
+ """
93
+ Initialize the SQLite database with required tables.
94
+ If there is a dataset ID provided, copies from that dataset instead.
95
+ Returns the database path.
96
+ """
97
+ db_path = SQLiteStorage.get_project_db_path(project)
98
+ db_path.parent.mkdir(parents=True, exist_ok=True)
99
+ with SQLiteStorage._get_process_lock(project):
100
+ with sqlite3.connect(db_path, timeout=30.0) as conn:
101
+ conn.execute("PRAGMA journal_mode = WAL")
102
+ cursor = conn.cursor()
103
+ cursor.execute("""
104
+ CREATE TABLE IF NOT EXISTS metrics (
105
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
106
+ timestamp TEXT NOT NULL,
107
+ run_name TEXT NOT NULL,
108
+ step INTEGER NOT NULL,
109
+ metrics TEXT NOT NULL
110
+ )
111
+ """)
112
+ cursor.execute(
113
+ """
114
+ CREATE INDEX IF NOT EXISTS idx_metrics_run_step
115
+ ON metrics(run_name, step)
116
+ """
117
+ )
118
+ conn.commit()
119
+ return db_path
120
+
121
+ @staticmethod
122
+ def export_to_parquet():
123
+ """
124
+ Exports all projects' DB files as Parquet under the same path but with extension ".parquet".
125
+ """
126
+ # don't attempt to export (potentially wrong/blank) data before importing for the first time
127
+ if not SQLiteStorage._dataset_import_attempted:
128
+ return
129
+ all_paths = os.listdir(TRACKIO_DIR)
130
+ db_paths = [f for f in all_paths if f.endswith(".db")]
131
+ for db_path in db_paths:
132
+ db_path = TRACKIO_DIR / db_path
133
+ parquet_path = db_path.with_suffix(".parquet")
134
+ if (not parquet_path.exists()) or (
135
+ db_path.stat().st_mtime > parquet_path.stat().st_mtime
136
+ ):
137
+ with sqlite3.connect(db_path) as conn:
138
+ df = pd.read_sql("SELECT * from metrics", conn)
139
+ # break out the single JSON metrics column into individual columns
140
+ metrics = df["metrics"].copy()
141
+ metrics = pd.DataFrame(
142
+ metrics.apply(
143
+ lambda x: deserialize_values(json.loads(x))
144
+ ).values.tolist(),
145
+ index=df.index,
146
+ )
147
+ del df["metrics"]
148
+ for col in metrics.columns:
149
+ df[col] = metrics[col]
150
+ df.to_parquet(parquet_path)
151
+
152
+ @staticmethod
153
+ def import_from_parquet():
154
+ """
155
+ Imports to all DB files that have matching files under the same path but with extension ".parquet".
156
+ """
157
+ all_paths = os.listdir(TRACKIO_DIR)
158
+ parquet_paths = [f for f in all_paths if f.endswith(".parquet")]
159
+ for parquet_path in parquet_paths:
160
+ parquet_path = TRACKIO_DIR / parquet_path
161
+ db_path = parquet_path.with_suffix(".db")
162
+ df = pd.read_parquet(parquet_path)
163
+ with sqlite3.connect(db_path) as conn:
164
+ # fix up df to have a single JSON metrics column
165
+ if "metrics" not in df.columns:
166
+ # separate other columns from metrics
167
+ metrics = df.copy()
168
+ other_cols = ["id", "timestamp", "run_name", "step"]
169
+ df = df[other_cols]
170
+ for col in other_cols:
171
+ del metrics[col]
172
+ # combine them all into a single metrics col
173
+ metrics = json.loads(metrics.to_json(orient="records"))
174
+ df["metrics"] = [
175
+ json.dumps(serialize_values(row)) for row in metrics
176
+ ]
177
+ df.to_sql("metrics", conn, if_exists="replace", index=False)
178
+
179
+ @staticmethod
180
+ def get_scheduler():
181
+ """
182
+ Get the scheduler for the database based on the environment variables.
183
+ This applies to both local and Spaces.
184
+ """
185
+ with SQLiteStorage._scheduler_lock:
186
+ if SQLiteStorage._current_scheduler is not None:
187
+ return SQLiteStorage._current_scheduler
188
+ hf_token = os.environ.get("HF_TOKEN")
189
+ dataset_id = os.environ.get("TRACKIO_DATASET_ID")
190
+ space_repo_name = os.environ.get("SPACE_REPO_NAME")
191
+ if dataset_id is None or space_repo_name is None:
192
+ scheduler = DummyCommitScheduler()
193
+ else:
194
+ scheduler = CommitScheduler(
195
+ repo_id=dataset_id,
196
+ repo_type="dataset",
197
+ folder_path=TRACKIO_DIR,
198
+ private=True,
199
+ allow_patterns=["*.parquet", "media/**/*"],
200
+ squash_history=True,
201
+ token=hf_token,
202
+ on_before_commit=SQLiteStorage.export_to_parquet,
203
+ )
204
+ SQLiteStorage._current_scheduler = scheduler
205
+ return scheduler
206
+
207
+ @staticmethod
208
+ def log(project: str, run: str, metrics: dict, step: int | None = None):
209
+ """
210
+ Safely log metrics to the database. Before logging, this method will ensure the database exists
211
+ and is set up with the correct tables. It also uses a cross-process lock to prevent
212
+ database locking errors when multiple processes access the same database.
213
+
214
+ This method is not used in the latest versions of Trackio (replaced by bulk_log) but
215
+ is kept for backwards compatibility for users who are connecting to a newer version of
216
+ a Trackio Spaces dashboard with an older version of Trackio installed locally.
217
+ """
218
+ db_path = SQLiteStorage.init_db(project)
219
+
220
+ with SQLiteStorage._get_process_lock(project):
221
+ with SQLiteStorage._get_connection(db_path) as conn:
222
+ cursor = conn.cursor()
223
+
224
+ cursor.execute(
225
+ """
226
+ SELECT MAX(step)
227
+ FROM metrics
228
+ WHERE run_name = ?
229
+ """,
230
+ (run,),
231
+ )
232
+ last_step = cursor.fetchone()[0]
233
+ if step is None:
234
+ current_step = 0 if last_step is None else last_step + 1
235
+ else:
236
+ current_step = step
237
+
238
+ current_timestamp = datetime.now().isoformat()
239
+
240
+ cursor.execute(
241
+ """
242
+ INSERT INTO metrics
243
+ (timestamp, run_name, step, metrics)
244
+ VALUES (?, ?, ?, ?)
245
+ """,
246
+ (
247
+ current_timestamp,
248
+ run,
249
+ current_step,
250
+ json.dumps(serialize_values(metrics)),
251
+ ),
252
+ )
253
+ conn.commit()
254
+
255
+ @staticmethod
256
+ def bulk_log(
257
+ project: str,
258
+ run: str,
259
+ metrics_list: list[dict],
260
+ steps: list[int] | None = None,
261
+ timestamps: list[str] | None = None,
262
+ ):
263
+ """
264
+ Safely log bulk metrics to the database. Before logging, this method will ensure the database exists
265
+ and is set up with the correct tables. It also uses a cross-process lock to prevent
266
+ database locking errors when multiple processes access the same database.
267
+ """
268
+ if not metrics_list:
269
+ return
270
+
271
+ if timestamps is None:
272
+ timestamps = [datetime.now().isoformat()] * len(metrics_list)
273
+
274
+ db_path = SQLiteStorage.init_db(project)
275
+ with SQLiteStorage._get_process_lock(project):
276
+ with SQLiteStorage._get_connection(db_path) as conn:
277
+ cursor = conn.cursor()
278
+
279
+ if steps is None:
280
+ steps = list(range(len(metrics_list)))
281
+ elif any(s is None for s in steps):
282
+ cursor.execute(
283
+ "SELECT MAX(step) FROM metrics WHERE run_name = ?", (run,)
284
+ )
285
+ last_step = cursor.fetchone()[0]
286
+ current_step = 0 if last_step is None else last_step + 1
287
+
288
+ processed_steps = []
289
+ for step in steps:
290
+ if step is None:
291
+ processed_steps.append(current_step)
292
+ current_step += 1
293
+ else:
294
+ processed_steps.append(step)
295
+ steps = processed_steps
296
+
297
+ if len(metrics_list) != len(steps) or len(metrics_list) != len(
298
+ timestamps
299
+ ):
300
+ raise ValueError(
301
+ "metrics_list, steps, and timestamps must have the same length"
302
+ )
303
+
304
+ data = []
305
+ for i, metrics in enumerate(metrics_list):
306
+ data.append(
307
+ (
308
+ timestamps[i],
309
+ run,
310
+ steps[i],
311
+ json.dumps(serialize_values(metrics)),
312
+ )
313
+ )
314
+
315
+ cursor.executemany(
316
+ """
317
+ INSERT INTO metrics
318
+ (timestamp, run_name, step, metrics)
319
+ VALUES (?, ?, ?, ?)
320
+ """,
321
+ data,
322
+ )
323
+ conn.commit()
324
+
325
+ @staticmethod
326
+ def get_logs(project: str, run: str) -> list[dict]:
327
+ """Retrieve logs for a specific run. Logs include the step count (int) and the timestamp (datetime object)."""
328
+ db_path = SQLiteStorage.get_project_db_path(project)
329
+ if not db_path.exists():
330
+ return []
331
+
332
+ with SQLiteStorage._get_connection(db_path) as conn:
333
+ cursor = conn.cursor()
334
+ cursor.execute(
335
+ """
336
+ SELECT timestamp, step, metrics
337
+ FROM metrics
338
+ WHERE run_name = ?
339
+ ORDER BY timestamp
340
+ """,
341
+ (run,),
342
+ )
343
+
344
+ rows = cursor.fetchall()
345
+ results = []
346
+ for row in rows:
347
+ metrics = json.loads(row["metrics"])
348
+ metrics = deserialize_values(metrics)
349
+ metrics["timestamp"] = row["timestamp"]
350
+ metrics["step"] = row["step"]
351
+ results.append(metrics)
352
+ return results
353
+
354
+ @staticmethod
355
+ def load_from_dataset():
356
+ dataset_id = os.environ.get("TRACKIO_DATASET_ID")
357
+ space_repo_name = os.environ.get("SPACE_REPO_NAME")
358
+ if dataset_id is not None and space_repo_name is not None:
359
+ hfapi = hf.HfApi()
360
+ updated = False
361
+ if not TRACKIO_DIR.exists():
362
+ TRACKIO_DIR.mkdir(parents=True, exist_ok=True)
363
+ with SQLiteStorage.get_scheduler().lock:
364
+ try:
365
+ files = hfapi.list_repo_files(dataset_id, repo_type="dataset")
366
+ for file in files:
367
+ # Download parquet and media assets
368
+ if not (file.endswith(".parquet") or file.startswith("media/")):
369
+ continue
370
+ if (TRACKIO_DIR / file).exists():
371
+ continue
372
+ hf.hf_hub_download(
373
+ dataset_id, file, repo_type="dataset", local_dir=TRACKIO_DIR
374
+ )
375
+ updated = True
376
+ except hf.errors.EntryNotFoundError:
377
+ pass
378
+ except hf.errors.RepositoryNotFoundError:
379
+ pass
380
+ if updated:
381
+ SQLiteStorage.import_from_parquet()
382
+ SQLiteStorage._dataset_import_attempted = True
383
+
384
+ @staticmethod
385
+ def get_projects() -> list[str]:
386
+ """
387
+ Get list of all projects by scanning the database files in the trackio directory.
388
+ """
389
+ if not SQLiteStorage._dataset_import_attempted:
390
+ SQLiteStorage.load_from_dataset()
391
+
392
+ projects: set[str] = set()
393
+ if not TRACKIO_DIR.exists():
394
+ return []
395
+
396
+ for db_file in TRACKIO_DIR.glob("*.db"):
397
+ project_name = db_file.stem
398
+ projects.add(project_name)
399
+ return sorted(projects)
400
+
401
+ @staticmethod
402
+ def get_runs(project: str) -> list[str]:
403
+ """Get list of all runs for a project."""
404
+ db_path = SQLiteStorage.get_project_db_path(project)
405
+ if not db_path.exists():
406
+ return []
407
+
408
+ with SQLiteStorage._get_connection(db_path) as conn:
409
+ cursor = conn.cursor()
410
+ cursor.execute(
411
+ "SELECT DISTINCT run_name FROM metrics",
412
+ )
413
+ return [row[0] for row in cursor.fetchall()]
414
+
415
+ @staticmethod
416
+ def get_max_steps_for_runs(project: str) -> dict[str, int]:
417
+ """Get the maximum step for each run in a project."""
418
+ db_path = SQLiteStorage.get_project_db_path(project)
419
+ if not db_path.exists():
420
+ return {}
421
+
422
+ with SQLiteStorage._get_connection(db_path) as conn:
423
+ cursor = conn.cursor()
424
+ cursor.execute(
425
+ """
426
+ SELECT run_name, MAX(step) as max_step
427
+ FROM metrics
428
+ GROUP BY run_name
429
+ """
430
+ )
431
+
432
+ results = {}
433
+ for row in cursor.fetchall():
434
+ results[row["run_name"]] = row["max_step"]
435
+
436
+ return results
437
+
438
+ def finish(self):
439
+ """Cleanup when run is finished."""
440
+ pass
table.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Literal, Optional, Union
2
+
3
+ from pandas import DataFrame
4
+
5
+
6
+ class Table:
7
+ """
8
+ Initializes a Table object.
9
+
10
+ Args:
11
+ columns (`list[str]`, *optional*, defaults to `None`):
12
+ Names of the columns in the table. Optional if `data` is provided. Not
13
+ expected if `dataframe` is provided. Currently ignored.
14
+ data (`list[list[Any]]`, *optional*, defaults to `None`):
15
+ 2D row-oriented array of values.
16
+ dataframe (`pandas.`DataFrame``, *optional*, defaults to `None`):
17
+ DataFrame object used to create the table. When set, `data` and `columns`
18
+ arguments are ignored.
19
+ rows (`list[list[any]]`, *optional*, defaults to `None`):
20
+ Currently ignored.
21
+ optional (`bool` or `list[bool]`, *optional*, defaults to `True`):
22
+ Currently ignored.
23
+ allow_mixed_types (`bool`, *optional*, defaults to `False`):
24
+ Currently ignored.
25
+ log_mode: (`Literal["IMMUTABLE", "MUTABLE", "INCREMENTAL"]` or `None`, *optional*, defaults to `"IMMUTABLE"`):
26
+ Currently ignored.
27
+ """
28
+
29
+ TYPE = "trackio.table"
30
+
31
+ def __init__(
32
+ self,
33
+ columns: Optional[list[str]] = None,
34
+ data: Optional[list[list[Any]]] = None,
35
+ dataframe: Optional[DataFrame] = None,
36
+ rows: Optional[list[list[Any]]] = None,
37
+ optional: Union[bool, list[bool]] = True,
38
+ allow_mixed_types: bool = False,
39
+ log_mode: Optional[
40
+ Literal["IMMUTABLE", "MUTABLE", "INCREMENTAL"]
41
+ ] = "IMMUTABLE",
42
+ ):
43
+ # TODO: implement support for columns, dtype, optional, allow_mixed_types, and log_mode.
44
+ # for now (like `rows`) they are included for API compat but don't do anything.
45
+
46
+ if dataframe is None:
47
+ self.data = data
48
+ else:
49
+ self.data = dataframe.to_dict(orient="records")
50
+
51
+ def _to_dict(self):
52
+ return {
53
+ "_type": self.TYPE,
54
+ "_value": self.data,
55
+ }
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,857 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import shutil
4
+ from dataclasses import dataclass
5
+ from typing import Any
6
+
7
+ import gradio as gr
8
+ import huggingface_hub as hf
9
+ import numpy as np
10
+ import pandas as pd
11
+
12
+ HfApi = hf.HfApi()
13
+
14
+ try:
15
+ import trackio.utils as utils
16
+ from trackio.file_storage import FileStorage
17
+ from trackio.media import TrackioImage, TrackioVideo
18
+ from trackio.sqlite_storage import SQLiteStorage
19
+ from trackio.table import Table
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 table import Table
27
+ from typehints import LogEntry, UploadEntry
28
+
29
+
30
+ def get_project_info() -> str | None:
31
+ dataset_id = os.environ.get("TRACKIO_DATASET_ID")
32
+ space_id = os.environ.get("SPACE_ID")
33
+ if utils.persistent_storage_enabled():
34
+ return "&#10024; Persistent Storage is enabled, logs are stored directly in this Space."
35
+ if dataset_id:
36
+ sync_status = utils.get_sync_status(SQLiteStorage.get_scheduler())
37
+ 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. Make sure data is synced prior to enabling.</span></span>"
38
+ if sync_status is not None:
39
+ 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}"
40
+ else:
41
+ 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}"
42
+ return info
43
+ return None
44
+
45
+
46
+ def get_projects(request: gr.Request):
47
+ projects = SQLiteStorage.get_projects()
48
+ if project := request.query_params.get("project"):
49
+ interactive = False
50
+ else:
51
+ interactive = True
52
+ project = projects[0] if projects else None
53
+
54
+ return gr.Dropdown(
55
+ label="Project",
56
+ choices=projects,
57
+ value=project,
58
+ allow_custom_value=True,
59
+ interactive=interactive,
60
+ info=get_project_info(),
61
+ )
62
+
63
+
64
+ def get_runs(project) -> list[str]:
65
+ if not project:
66
+ return []
67
+ return SQLiteStorage.get_runs(project)
68
+
69
+
70
+ def get_available_metrics(project: str, runs: list[str]) -> list[str]:
71
+ """Get all available metrics across all runs for x-axis selection."""
72
+ if not project or not runs:
73
+ return ["step", "time"]
74
+
75
+ all_metrics = set()
76
+ for run in runs:
77
+ metrics = SQLiteStorage.get_logs(project, run)
78
+ if metrics:
79
+ df = pd.DataFrame(metrics)
80
+ numeric_cols = df.select_dtypes(include="number").columns
81
+ numeric_cols = [c for c in numeric_cols if c not in utils.RESERVED_KEYS]
82
+ all_metrics.update(numeric_cols)
83
+
84
+ all_metrics.add("step")
85
+ all_metrics.add("time")
86
+
87
+ sorted_metrics = utils.sort_metrics_by_prefix(list(all_metrics))
88
+
89
+ result = ["step", "time"]
90
+ for metric in sorted_metrics:
91
+ if metric not in result:
92
+ result.append(metric)
93
+
94
+ return result
95
+
96
+
97
+ @dataclass
98
+ class MediaData:
99
+ caption: str | None
100
+ file_path: str
101
+
102
+
103
+ def extract_media(logs: list[dict]) -> dict[str, list[MediaData]]:
104
+ media_by_key: dict[str, list[MediaData]] = {}
105
+ logs = sorted(logs, key=lambda x: x.get("step", 0))
106
+ for log in logs:
107
+ for key, value in log.items():
108
+ if isinstance(value, dict):
109
+ type = value.get("_type")
110
+ if type == TrackioImage.TYPE or type == TrackioVideo.TYPE:
111
+ if key not in media_by_key:
112
+ media_by_key[key] = []
113
+ try:
114
+ media_data = MediaData(
115
+ file_path=utils.MEDIA_DIR / value.get("file_path"),
116
+ caption=value.get("caption"),
117
+ )
118
+ media_by_key[key].append(media_data)
119
+ except Exception as e:
120
+ print(f"Media currently unavailable: {key}: {e}")
121
+ return media_by_key
122
+
123
+
124
+ def load_run_data(
125
+ project: str | None,
126
+ run: str | None,
127
+ smoothing_granularity: int,
128
+ x_axis: str,
129
+ log_scale: bool = False,
130
+ ) -> tuple[pd.DataFrame, dict]:
131
+ if not project or not run:
132
+ return None, None
133
+
134
+ logs = SQLiteStorage.get_logs(project, run)
135
+ if not logs:
136
+ return None, None
137
+
138
+ media = extract_media(logs)
139
+ df = pd.DataFrame(logs)
140
+
141
+ if "step" not in df.columns:
142
+ df["step"] = range(len(df))
143
+
144
+ if x_axis == "time" and "timestamp" in df.columns:
145
+ df["timestamp"] = pd.to_datetime(df["timestamp"])
146
+ first_timestamp = df["timestamp"].min()
147
+ df["time"] = (df["timestamp"] - first_timestamp).dt.total_seconds()
148
+ x_column = "time"
149
+ elif x_axis == "step":
150
+ x_column = "step"
151
+ else:
152
+ x_column = x_axis
153
+
154
+ if log_scale and x_column in df.columns:
155
+ x_vals = df[x_column]
156
+ if (x_vals <= 0).any():
157
+ df[x_column] = np.log10(np.maximum(x_vals, 0) + 1)
158
+ else:
159
+ df[x_column] = np.log10(x_vals)
160
+
161
+ if smoothing_granularity > 0:
162
+ numeric_cols = df.select_dtypes(include="number").columns
163
+ numeric_cols = [c for c in numeric_cols if c not in utils.RESERVED_KEYS]
164
+
165
+ df_original = df.copy()
166
+ df_original["run"] = run
167
+ df_original["data_type"] = "original"
168
+
169
+ df_smoothed = df.copy()
170
+ window_size = max(3, min(smoothing_granularity, len(df)))
171
+ df_smoothed[numeric_cols] = (
172
+ df_smoothed[numeric_cols]
173
+ .rolling(window=window_size, center=True, min_periods=1)
174
+ .mean()
175
+ )
176
+ df_smoothed["run"] = f"{run}_smoothed"
177
+ df_smoothed["data_type"] = "smoothed"
178
+
179
+ combined_df = pd.concat([df_original, df_smoothed], ignore_index=True)
180
+ combined_df["x_axis"] = x_column
181
+ return combined_df, media
182
+ else:
183
+ df["run"] = run
184
+ df["data_type"] = "original"
185
+ df["x_axis"] = x_column
186
+ return df, media
187
+
188
+
189
+ def update_runs(
190
+ project, filter_text, user_interacted_with_runs=False, selected_runs_from_url=None
191
+ ):
192
+ if project is None:
193
+ runs = []
194
+ num_runs = 0
195
+ else:
196
+ runs = get_runs(project)
197
+ num_runs = len(runs)
198
+ if filter_text:
199
+ runs = [r for r in runs if filter_text in r]
200
+
201
+ if not user_interacted_with_runs:
202
+ if selected_runs_from_url:
203
+ value = [r for r in runs if r in selected_runs_from_url]
204
+ else:
205
+ value = runs
206
+ return gr.CheckboxGroup(choices=runs, value=value), gr.Textbox(
207
+ label=f"Runs ({num_runs})"
208
+ )
209
+ else:
210
+ return gr.CheckboxGroup(choices=runs), gr.Textbox(label=f"Runs ({num_runs})")
211
+
212
+
213
+ def filter_runs(project, filter_text):
214
+ runs = get_runs(project)
215
+ runs = [r for r in runs if filter_text in r]
216
+ return gr.CheckboxGroup(choices=runs, value=runs)
217
+
218
+
219
+ def update_x_axis_choices(project, runs):
220
+ """Update x-axis dropdown choices based on available metrics."""
221
+ available_metrics = get_available_metrics(project, runs)
222
+ return gr.Dropdown(
223
+ label="X-axis",
224
+ choices=available_metrics,
225
+ value="step",
226
+ )
227
+
228
+
229
+ def toggle_timer(cb_value):
230
+ if cb_value:
231
+ return gr.Timer(active=True)
232
+ else:
233
+ return gr.Timer(active=False)
234
+
235
+
236
+ def check_auth(hf_token: str | None) -> None:
237
+ if os.getenv("SYSTEM") == "spaces": # if we are running in Spaces
238
+ # check auth token passed in
239
+ if hf_token is None:
240
+ raise PermissionError(
241
+ "Expected a HF_TOKEN to be provided when logging to a Space"
242
+ )
243
+ who = HfApi.whoami(hf_token)
244
+ access_token = who["auth"]["accessToken"]
245
+ owner_name = os.getenv("SPACE_AUTHOR_NAME")
246
+ repo_name = os.getenv("SPACE_REPO_NAME")
247
+ # make sure the token user is either the author of the space,
248
+ # or is a member of an org that is the author.
249
+ orgs = [o["name"] for o in who["orgs"]]
250
+ if owner_name != who["name"] and owner_name not in orgs:
251
+ raise PermissionError(
252
+ "Expected the provided hf_token to be the user owner of the space, or be a member of the org owner of the space"
253
+ )
254
+ # reject fine-grained tokens without specific repo access
255
+ if access_token["role"] == "fineGrained":
256
+ matched = False
257
+ for item in access_token["fineGrained"]["scoped"]:
258
+ if (
259
+ item["entity"]["type"] == "space"
260
+ and item["entity"]["name"] == f"{owner_name}/{repo_name}"
261
+ and "repo.write" in item["permissions"]
262
+ ):
263
+ matched = True
264
+ break
265
+ if (
266
+ (
267
+ item["entity"]["type"] == "user"
268
+ or item["entity"]["type"] == "org"
269
+ )
270
+ and item["entity"]["name"] == owner_name
271
+ and "repo.write" in item["permissions"]
272
+ ):
273
+ matched = True
274
+ break
275
+ if not matched:
276
+ raise PermissionError(
277
+ "Expected the provided hf_token with fine grained permissions to provide write access to the space"
278
+ )
279
+ # reject read-only tokens
280
+ elif access_token["role"] != "write":
281
+ raise PermissionError(
282
+ "Expected the provided hf_token to provide write permissions"
283
+ )
284
+
285
+
286
+ def upload_db_to_space(
287
+ project: str, uploaded_db: gr.FileData, hf_token: str | None
288
+ ) -> None:
289
+ check_auth(hf_token)
290
+ db_project_path = SQLiteStorage.get_project_db_path(project)
291
+ if os.path.exists(db_project_path):
292
+ raise gr.Error(
293
+ f"Trackio database file already exists for project {project}, cannot overwrite."
294
+ )
295
+ os.makedirs(os.path.dirname(db_project_path), exist_ok=True)
296
+ shutil.copy(uploaded_db["path"], db_project_path)
297
+
298
+
299
+ def bulk_upload_media(uploads: list[UploadEntry], hf_token: str | None) -> None:
300
+ check_auth(hf_token)
301
+ for upload in uploads:
302
+ media_path = FileStorage.init_project_media_path(
303
+ upload["project"], upload["run"], upload["step"]
304
+ )
305
+ shutil.copy(upload["uploaded_file"]["path"], media_path)
306
+
307
+
308
+ def log(
309
+ project: str,
310
+ run: str,
311
+ metrics: dict[str, Any],
312
+ step: int | None,
313
+ hf_token: str | None,
314
+ ) -> None:
315
+ """
316
+ Note: this method is not used in the latest versions of Trackio (replaced by bulk_log) but
317
+ is kept for backwards compatibility for users who are connecting to a newer version of
318
+ a Trackio Spaces dashboard with an older version of Trackio installed locally.
319
+ """
320
+ check_auth(hf_token)
321
+ SQLiteStorage.log(project=project, run=run, metrics=metrics, step=step)
322
+
323
+
324
+ def bulk_log(
325
+ logs: list[LogEntry],
326
+ hf_token: str | None,
327
+ ) -> None:
328
+ check_auth(hf_token)
329
+
330
+ logs_by_run = {}
331
+ for log_entry in logs:
332
+ key = (log_entry["project"], log_entry["run"])
333
+ if key not in logs_by_run:
334
+ logs_by_run[key] = {"metrics": [], "steps": []}
335
+ logs_by_run[key]["metrics"].append(log_entry["metrics"])
336
+ logs_by_run[key]["steps"].append(log_entry.get("step"))
337
+
338
+ for (project, run), data in logs_by_run.items():
339
+ SQLiteStorage.bulk_log(
340
+ project=project,
341
+ run=run,
342
+ metrics_list=data["metrics"],
343
+ steps=data["steps"],
344
+ )
345
+
346
+
347
+ def filter_metrics_by_regex(metrics: list[str], filter_pattern: str) -> list[str]:
348
+ """
349
+ Filter metrics using regex pattern.
350
+
351
+ Args:
352
+ metrics: List of metric names to filter
353
+ filter_pattern: Regex pattern to match against metric names
354
+
355
+ Returns:
356
+ List of metric names that match the pattern
357
+ """
358
+ if not filter_pattern.strip():
359
+ return metrics
360
+
361
+ try:
362
+ pattern = re.compile(filter_pattern, re.IGNORECASE)
363
+ return [metric for metric in metrics if pattern.search(metric)]
364
+ except re.error:
365
+ return [
366
+ metric for metric in metrics if filter_pattern.lower() in metric.lower()
367
+ ]
368
+
369
+
370
+ def configure(request: gr.Request):
371
+ sidebar_param = request.query_params.get("sidebar")
372
+ match sidebar_param:
373
+ case "collapsed":
374
+ sidebar = gr.Sidebar(open=False, visible=True)
375
+ case "hidden":
376
+ sidebar = gr.Sidebar(open=False, visible=False)
377
+ case _:
378
+ sidebar = gr.Sidebar(open=True, visible=True)
379
+
380
+ metrics_param = request.query_params.get("metrics", "")
381
+ runs_param = request.query_params.get("runs", "")
382
+ selected_runs = runs_param.split(",") if runs_param else []
383
+
384
+ return [], sidebar, metrics_param, selected_runs
385
+
386
+
387
+ def create_media_section(media_by_run: dict[str, dict[str, list[MediaData]]]):
388
+ with gr.Accordion(label="media"):
389
+ with gr.Group(elem_classes=("media-group")):
390
+ for run, media_by_key in media_by_run.items():
391
+ with gr.Tab(label=run, elem_classes=("media-tab")):
392
+ for key, media_item in media_by_key.items():
393
+ gr.Gallery(
394
+ [(item.file_path, item.caption) for item in media_item],
395
+ label=key,
396
+ columns=6,
397
+ elem_classes=("media-gallery"),
398
+ )
399
+
400
+
401
+ css = """
402
+ #run-cb .wrap { gap: 2px; }
403
+ #run-cb .wrap label {
404
+ line-height: 1;
405
+ padding: 6px;
406
+ }
407
+ .logo-light { display: block; }
408
+ .logo-dark { display: none; }
409
+ .dark .logo-light { display: none; }
410
+ .dark .logo-dark { display: block; }
411
+ .dark .caption-label { color: white; }
412
+
413
+ .info-container {
414
+ position: relative;
415
+ display: inline;
416
+ }
417
+ .info-checkbox {
418
+ position: absolute;
419
+ opacity: 0;
420
+ pointer-events: none;
421
+ }
422
+ .info-icon {
423
+ border-bottom: 1px dotted;
424
+ cursor: pointer;
425
+ user-select: none;
426
+ color: var(--color-accent);
427
+ }
428
+ .info-expandable {
429
+ display: none;
430
+ opacity: 0;
431
+ transition: opacity 0.2s ease-in-out;
432
+ }
433
+ .info-checkbox:checked ~ .info-expandable {
434
+ display: inline;
435
+ opacity: 1;
436
+ }
437
+ .info-icon:hover { opacity: 0.8; }
438
+ .accent-link { font-weight: bold; }
439
+
440
+ .media-gallery .fixed-height { min-height: 275px; }
441
+ .media-group, .media-group > div { background: none; }
442
+ .media-group .tabs { padding: 0.5em; }
443
+ .media-tab { max-height: 500px; overflow-y: scroll; }
444
+ """
445
+
446
+ gr.set_static_paths(paths=[utils.MEDIA_DIR])
447
+ with gr.Blocks(theme="citrus", title="Trackio Dashboard", css=css) as demo:
448
+ with gr.Sidebar(open=False) as sidebar:
449
+ logo = gr.Markdown(
450
+ f"""
451
+ <img src='/gradio_api/file={utils.TRACKIO_LOGO_DIR}/trackio_logo_type_light_transparent.png' width='80%' class='logo-light'>
452
+ <img src='/gradio_api/file={utils.TRACKIO_LOGO_DIR}/trackio_logo_type_dark_transparent.png' width='80%' class='logo-dark'>
453
+ """
454
+ )
455
+ project_dd = gr.Dropdown(label="Project", allow_custom_value=True)
456
+
457
+ embed_code = gr.Code(
458
+ label="Embed this view",
459
+ max_lines=2,
460
+ lines=2,
461
+ language="html",
462
+ visible=bool(os.environ.get("SPACE_HOST")),
463
+ )
464
+ run_tb = gr.Textbox(label="Runs", placeholder="Type to filter...")
465
+ run_cb = gr.CheckboxGroup(
466
+ label="Runs", choices=[], interactive=True, elem_id="run-cb"
467
+ )
468
+ gr.HTML("<hr>")
469
+ realtime_cb = gr.Checkbox(label="Refresh metrics realtime", value=True)
470
+ smoothing_slider = gr.Slider(
471
+ label="Smoothing Factor",
472
+ minimum=0,
473
+ maximum=20,
474
+ value=10,
475
+ step=1,
476
+ info="0 = no smoothing",
477
+ )
478
+ x_axis_dd = gr.Dropdown(
479
+ label="X-axis",
480
+ choices=["step", "time"],
481
+ value="step",
482
+ )
483
+ log_scale_cb = gr.Checkbox(label="Log scale X-axis", value=False)
484
+ metric_filter_tb = gr.Textbox(
485
+ label="Metric Filter (regex)",
486
+ placeholder="e.g., loss|ndcg@10|gpu",
487
+ value="",
488
+ info="Filter metrics using regex patterns. Leave empty to show all metrics.",
489
+ )
490
+
491
+ timer = gr.Timer(value=1)
492
+ metrics_subset = gr.State([])
493
+ user_interacted_with_run_cb = gr.State(False)
494
+ selected_runs_from_url = gr.State([])
495
+
496
+ gr.on(
497
+ [demo.load],
498
+ fn=configure,
499
+ outputs=[metrics_subset, sidebar, metric_filter_tb, selected_runs_from_url],
500
+ queue=False,
501
+ api_name=False,
502
+ )
503
+ gr.on(
504
+ [demo.load],
505
+ fn=get_projects,
506
+ outputs=project_dd,
507
+ show_progress="hidden",
508
+ queue=False,
509
+ api_name=False,
510
+ )
511
+ gr.on(
512
+ [timer.tick],
513
+ fn=update_runs,
514
+ inputs=[
515
+ project_dd,
516
+ run_tb,
517
+ user_interacted_with_run_cb,
518
+ selected_runs_from_url,
519
+ ],
520
+ outputs=[run_cb, run_tb],
521
+ show_progress="hidden",
522
+ api_name=False,
523
+ )
524
+ gr.on(
525
+ [timer.tick],
526
+ fn=lambda: gr.Dropdown(info=get_project_info()),
527
+ outputs=[project_dd],
528
+ show_progress="hidden",
529
+ api_name=False,
530
+ )
531
+ gr.on(
532
+ [demo.load, project_dd.change],
533
+ fn=update_runs,
534
+ inputs=[project_dd, run_tb, gr.State(False), selected_runs_from_url],
535
+ outputs=[run_cb, run_tb],
536
+ show_progress="hidden",
537
+ queue=False,
538
+ api_name=False,
539
+ ).then(
540
+ fn=update_x_axis_choices,
541
+ inputs=[project_dd, run_cb],
542
+ outputs=x_axis_dd,
543
+ show_progress="hidden",
544
+ queue=False,
545
+ api_name=False,
546
+ ).then(
547
+ fn=utils.generate_embed_code,
548
+ inputs=[project_dd, metric_filter_tb, run_cb],
549
+ outputs=embed_code,
550
+ show_progress="hidden",
551
+ api_name=False,
552
+ queue=False,
553
+ )
554
+
555
+ gr.on(
556
+ [run_cb.input],
557
+ fn=update_x_axis_choices,
558
+ inputs=[project_dd, run_cb],
559
+ outputs=x_axis_dd,
560
+ show_progress="hidden",
561
+ queue=False,
562
+ api_name=False,
563
+ )
564
+ gr.on(
565
+ [metric_filter_tb.change, run_cb.change],
566
+ fn=utils.generate_embed_code,
567
+ inputs=[project_dd, metric_filter_tb, run_cb],
568
+ outputs=embed_code,
569
+ show_progress="hidden",
570
+ api_name=False,
571
+ queue=False,
572
+ )
573
+
574
+ realtime_cb.change(
575
+ fn=toggle_timer,
576
+ inputs=realtime_cb,
577
+ outputs=timer,
578
+ api_name=False,
579
+ queue=False,
580
+ )
581
+ run_cb.input(
582
+ fn=lambda: True,
583
+ outputs=user_interacted_with_run_cb,
584
+ api_name=False,
585
+ queue=False,
586
+ )
587
+ run_tb.input(
588
+ fn=filter_runs,
589
+ inputs=[project_dd, run_tb],
590
+ outputs=run_cb,
591
+ api_name=False,
592
+ queue=False,
593
+ )
594
+
595
+ gr.api(
596
+ fn=upload_db_to_space,
597
+ api_name="upload_db_to_space",
598
+ )
599
+ gr.api(
600
+ fn=bulk_upload_media,
601
+ api_name="bulk_upload_media",
602
+ )
603
+ gr.api(
604
+ fn=log,
605
+ api_name="log",
606
+ )
607
+ gr.api(
608
+ fn=bulk_log,
609
+ api_name="bulk_log",
610
+ )
611
+
612
+ x_lim = gr.State(None)
613
+ last_steps = gr.State({})
614
+
615
+ def update_x_lim(select_data: gr.SelectData):
616
+ return select_data.index
617
+
618
+ def update_last_steps(project):
619
+ """Check the last step for each run to detect when new data is available."""
620
+ if not project:
621
+ return {}
622
+ return SQLiteStorage.get_max_steps_for_runs(project)
623
+
624
+ timer.tick(
625
+ fn=update_last_steps,
626
+ inputs=[project_dd],
627
+ outputs=last_steps,
628
+ show_progress="hidden",
629
+ api_name=False,
630
+ )
631
+
632
+ @gr.render(
633
+ triggers=[
634
+ demo.load,
635
+ run_cb.change,
636
+ last_steps.change,
637
+ smoothing_slider.change,
638
+ x_lim.change,
639
+ x_axis_dd.change,
640
+ log_scale_cb.change,
641
+ metric_filter_tb.change,
642
+ ],
643
+ inputs=[
644
+ project_dd,
645
+ run_cb,
646
+ smoothing_slider,
647
+ metrics_subset,
648
+ x_lim,
649
+ x_axis_dd,
650
+ log_scale_cb,
651
+ metric_filter_tb,
652
+ ],
653
+ show_progress="hidden",
654
+ queue=False,
655
+ )
656
+ def update_dashboard(
657
+ project,
658
+ runs,
659
+ smoothing_granularity,
660
+ metrics_subset,
661
+ x_lim_value,
662
+ x_axis,
663
+ log_scale,
664
+ metric_filter,
665
+ ):
666
+ dfs = []
667
+ images_by_run = {}
668
+ original_runs = runs.copy()
669
+
670
+ for run in runs:
671
+ df, images_by_key = load_run_data(
672
+ project, run, smoothing_granularity, x_axis, log_scale
673
+ )
674
+ if df is not None:
675
+ dfs.append(df)
676
+ images_by_run[run] = images_by_key
677
+
678
+ if dfs:
679
+ if smoothing_granularity > 0:
680
+ original_dfs = []
681
+ smoothed_dfs = []
682
+ for df in dfs:
683
+ original_data = df[df["data_type"] == "original"]
684
+ smoothed_data = df[df["data_type"] == "smoothed"]
685
+ if not original_data.empty:
686
+ original_dfs.append(original_data)
687
+ if not smoothed_data.empty:
688
+ smoothed_dfs.append(smoothed_data)
689
+
690
+ all_dfs = original_dfs + smoothed_dfs
691
+ master_df = (
692
+ pd.concat(all_dfs, ignore_index=True) if all_dfs else pd.DataFrame()
693
+ )
694
+
695
+ else:
696
+ master_df = pd.concat(dfs, ignore_index=True)
697
+ else:
698
+ master_df = pd.DataFrame()
699
+
700
+ if master_df.empty:
701
+ return
702
+
703
+ x_column = "step"
704
+ if dfs and not dfs[0].empty and "x_axis" in dfs[0].columns:
705
+ x_column = dfs[0]["x_axis"].iloc[0]
706
+
707
+ numeric_cols = master_df.select_dtypes(include="number").columns
708
+ numeric_cols = [c for c in numeric_cols if c not in utils.RESERVED_KEYS]
709
+ if x_column and x_column in numeric_cols:
710
+ numeric_cols.remove(x_column)
711
+
712
+ if metrics_subset:
713
+ numeric_cols = [c for c in numeric_cols if c in metrics_subset]
714
+
715
+ if metric_filter and metric_filter.strip():
716
+ numeric_cols = filter_metrics_by_regex(list(numeric_cols), metric_filter)
717
+
718
+ nested_metric_groups = utils.group_metrics_with_subprefixes(list(numeric_cols))
719
+ color_map = utils.get_color_mapping(original_runs, smoothing_granularity > 0)
720
+
721
+ metric_idx = 0
722
+ for group_name in sorted(nested_metric_groups.keys()):
723
+ group_data = nested_metric_groups[group_name]
724
+
725
+ with gr.Accordion(
726
+ label=group_name,
727
+ open=True,
728
+ key=f"accordion-{group_name}",
729
+ preserved_by_key=["value", "open"],
730
+ ):
731
+ # Render direct metrics at this level
732
+ if group_data["direct_metrics"]:
733
+ with gr.Draggable(
734
+ key=f"row-{group_name}-direct", orientation="row"
735
+ ):
736
+ for metric_name in group_data["direct_metrics"]:
737
+ metric_df = master_df.dropna(subset=[metric_name])
738
+ color = "run" if "run" in metric_df.columns else None
739
+ if not metric_df.empty:
740
+ plot = gr.LinePlot(
741
+ utils.downsample(
742
+ metric_df,
743
+ x_column,
744
+ metric_name,
745
+ color,
746
+ x_lim_value,
747
+ ),
748
+ x=x_column,
749
+ y=metric_name,
750
+ y_title=metric_name.split("/")[-1],
751
+ color=color,
752
+ color_map=color_map,
753
+ title=metric_name,
754
+ key=f"plot-{metric_idx}",
755
+ preserved_by_key=None,
756
+ x_lim=x_lim_value,
757
+ show_fullscreen_button=True,
758
+ min_width=400,
759
+ )
760
+ plot.select(
761
+ update_x_lim,
762
+ outputs=x_lim,
763
+ key=f"select-{metric_idx}",
764
+ )
765
+ plot.double_click(
766
+ lambda: None,
767
+ outputs=x_lim,
768
+ key=f"double-{metric_idx}",
769
+ )
770
+ metric_idx += 1
771
+
772
+ # If there are subgroups, create nested accordions
773
+ if group_data["subgroups"]:
774
+ for subgroup_name in sorted(group_data["subgroups"].keys()):
775
+ subgroup_metrics = group_data["subgroups"][subgroup_name]
776
+
777
+ with gr.Accordion(
778
+ label=subgroup_name,
779
+ open=True,
780
+ key=f"accordion-{group_name}-{subgroup_name}",
781
+ preserved_by_key=["value", "open"],
782
+ ):
783
+ with gr.Draggable(key=f"row-{group_name}-{subgroup_name}"):
784
+ for metric_name in subgroup_metrics:
785
+ metric_df = master_df.dropna(subset=[metric_name])
786
+ color = (
787
+ "run" if "run" in metric_df.columns else None
788
+ )
789
+ if not metric_df.empty:
790
+ plot = gr.LinePlot(
791
+ utils.downsample(
792
+ metric_df,
793
+ x_column,
794
+ metric_name,
795
+ color,
796
+ x_lim_value,
797
+ ),
798
+ x=x_column,
799
+ y=metric_name,
800
+ y_title=metric_name.split("/")[-1],
801
+ color=color,
802
+ color_map=color_map,
803
+ title=metric_name,
804
+ key=f"plot-{metric_idx}",
805
+ preserved_by_key=None,
806
+ x_lim=x_lim_value,
807
+ show_fullscreen_button=True,
808
+ min_width=400,
809
+ )
810
+ plot.select(
811
+ update_x_lim,
812
+ outputs=x_lim,
813
+ key=f"select-{metric_idx}",
814
+ )
815
+ plot.double_click(
816
+ lambda: None,
817
+ outputs=x_lim,
818
+ key=f"double-{metric_idx}",
819
+ )
820
+ metric_idx += 1
821
+ if images_by_run and any(any(images) for images in images_by_run.values()):
822
+ create_media_section(images_by_run)
823
+
824
+ table_cols = master_df.select_dtypes(include="object").columns
825
+ table_cols = [c for c in table_cols if c not in utils.RESERVED_KEYS]
826
+ if metrics_subset:
827
+ table_cols = [c for c in table_cols if c in metrics_subset]
828
+ if metric_filter and metric_filter.strip():
829
+ table_cols = filter_metrics_by_regex(list(table_cols), metric_filter)
830
+ if len(table_cols) > 0:
831
+ with gr.Accordion("tables", open=True):
832
+ with gr.Row(key="row"):
833
+ for metric_idx, metric_name in enumerate(table_cols):
834
+ metric_df = master_df.dropna(subset=[metric_name])
835
+ if not metric_df.empty:
836
+ value = metric_df[metric_name].iloc[-1]
837
+ if (
838
+ isinstance(value, dict)
839
+ and "_type" in value
840
+ and value["_type"] == Table.TYPE
841
+ ):
842
+ try:
843
+ df = pd.DataFrame(value["_value"])
844
+ gr.DataFrame(
845
+ df,
846
+ label=f"{metric_name} (latest)",
847
+ key=f"table-{metric_idx}",
848
+ wrap=True,
849
+ )
850
+ except Exception as e:
851
+ gr.Warning(
852
+ f"Column {metric_name} failed to render as a table: {e}"
853
+ )
854
+
855
+
856
+ if __name__ == "__main__":
857
+ demo.launch(allowed_paths=[utils.TRACKIO_LOGO_DIR], show_api=False, show_error=True)
utils.py ADDED
@@ -0,0 +1,687 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import re
4
+ import sys
5
+ import time
6
+ from pathlib import Path
7
+ from typing import TYPE_CHECKING
8
+
9
+ import huggingface_hub
10
+ import numpy as np
11
+ import pandas as pd
12
+ from huggingface_hub.constants import HF_HOME
13
+
14
+ if TYPE_CHECKING:
15
+ from trackio.commit_scheduler import CommitScheduler
16
+ from trackio.dummy_commit_scheduler import DummyCommitScheduler
17
+
18
+ RESERVED_KEYS = ["project", "run", "timestamp", "step", "time", "metrics"]
19
+
20
+ TRACKIO_LOGO_DIR = Path(__file__).parent / "assets"
21
+
22
+
23
+ def persistent_storage_enabled() -> bool:
24
+ return (
25
+ os.environ.get("PERSISTANT_STORAGE_ENABLED") == "true"
26
+ ) # typo in the name of the environment variable
27
+
28
+
29
+ def _get_trackio_dir() -> Path:
30
+ if persistent_storage_enabled():
31
+ return Path("/data/trackio")
32
+ return Path(HF_HOME) / "trackio"
33
+
34
+
35
+ TRACKIO_DIR = _get_trackio_dir()
36
+ MEDIA_DIR = TRACKIO_DIR / "media"
37
+
38
+
39
+ def generate_readable_name(used_names: list[str], space_id: str | None = None) -> str:
40
+ """
41
+ Generates a random, readable name like "dainty-sunset-0".
42
+ If space_id is provided, generates username-timestamp format instead.
43
+ """
44
+ if space_id is not None:
45
+ username = huggingface_hub.whoami()["name"]
46
+ timestamp = int(time.time())
47
+ return f"{username}-{timestamp}"
48
+ adjectives = [
49
+ "dainty",
50
+ "brave",
51
+ "calm",
52
+ "eager",
53
+ "fancy",
54
+ "gentle",
55
+ "happy",
56
+ "jolly",
57
+ "kind",
58
+ "lively",
59
+ "merry",
60
+ "nice",
61
+ "proud",
62
+ "quick",
63
+ "hugging",
64
+ "silly",
65
+ "tidy",
66
+ "witty",
67
+ "zealous",
68
+ "bright",
69
+ "shy",
70
+ "bold",
71
+ "clever",
72
+ "daring",
73
+ "elegant",
74
+ "faithful",
75
+ "graceful",
76
+ "honest",
77
+ "inventive",
78
+ "jovial",
79
+ "keen",
80
+ "lucky",
81
+ "modest",
82
+ "noble",
83
+ "optimistic",
84
+ "patient",
85
+ "quirky",
86
+ "resourceful",
87
+ "sincere",
88
+ "thoughtful",
89
+ "upbeat",
90
+ "valiant",
91
+ "warm",
92
+ "youthful",
93
+ "zesty",
94
+ "adventurous",
95
+ "breezy",
96
+ "cheerful",
97
+ "delightful",
98
+ "energetic",
99
+ "fearless",
100
+ "glad",
101
+ "hopeful",
102
+ "imaginative",
103
+ "joyful",
104
+ "kindly",
105
+ "luminous",
106
+ "mysterious",
107
+ "neat",
108
+ "outgoing",
109
+ "playful",
110
+ "radiant",
111
+ "spirited",
112
+ "tranquil",
113
+ "unique",
114
+ "vivid",
115
+ "wise",
116
+ "zany",
117
+ "artful",
118
+ "bubbly",
119
+ "charming",
120
+ "dazzling",
121
+ "earnest",
122
+ "festive",
123
+ "gentlemanly",
124
+ "hearty",
125
+ "intrepid",
126
+ "jubilant",
127
+ "knightly",
128
+ "lively",
129
+ "magnetic",
130
+ "nimble",
131
+ "orderly",
132
+ "peaceful",
133
+ "quick-witted",
134
+ "robust",
135
+ "sturdy",
136
+ "trusty",
137
+ "upstanding",
138
+ "vibrant",
139
+ "whimsical",
140
+ ]
141
+ nouns = [
142
+ "sunset",
143
+ "forest",
144
+ "river",
145
+ "mountain",
146
+ "breeze",
147
+ "meadow",
148
+ "ocean",
149
+ "valley",
150
+ "sky",
151
+ "field",
152
+ "cloud",
153
+ "star",
154
+ "rain",
155
+ "leaf",
156
+ "stone",
157
+ "flower",
158
+ "bird",
159
+ "tree",
160
+ "wave",
161
+ "trail",
162
+ "island",
163
+ "desert",
164
+ "hill",
165
+ "lake",
166
+ "pond",
167
+ "grove",
168
+ "canyon",
169
+ "reef",
170
+ "bay",
171
+ "peak",
172
+ "glade",
173
+ "marsh",
174
+ "cliff",
175
+ "dune",
176
+ "spring",
177
+ "brook",
178
+ "cave",
179
+ "plain",
180
+ "ridge",
181
+ "wood",
182
+ "blossom",
183
+ "petal",
184
+ "root",
185
+ "branch",
186
+ "seed",
187
+ "acorn",
188
+ "pine",
189
+ "willow",
190
+ "cedar",
191
+ "elm",
192
+ "falcon",
193
+ "eagle",
194
+ "sparrow",
195
+ "robin",
196
+ "owl",
197
+ "finch",
198
+ "heron",
199
+ "crane",
200
+ "duck",
201
+ "swan",
202
+ "fox",
203
+ "wolf",
204
+ "bear",
205
+ "deer",
206
+ "moose",
207
+ "otter",
208
+ "beaver",
209
+ "lynx",
210
+ "hare",
211
+ "badger",
212
+ "butterfly",
213
+ "bee",
214
+ "ant",
215
+ "beetle",
216
+ "dragonfly",
217
+ "firefly",
218
+ "ladybug",
219
+ "moth",
220
+ "spider",
221
+ "worm",
222
+ "coral",
223
+ "kelp",
224
+ "shell",
225
+ "pebble",
226
+ "face",
227
+ "boulder",
228
+ "cobble",
229
+ "sand",
230
+ "wavelet",
231
+ "tide",
232
+ "current",
233
+ "mist",
234
+ ]
235
+ number = 0
236
+ name = f"{adjectives[0]}-{nouns[0]}-{number}"
237
+ while name in used_names:
238
+ number += 1
239
+ adjective = adjectives[number % len(adjectives)]
240
+ noun = nouns[number % len(nouns)]
241
+ name = f"{adjective}-{noun}-{number}"
242
+ return name
243
+
244
+
245
+ def block_except_in_notebook():
246
+ in_notebook = bool(getattr(sys, "ps1", sys.flags.interactive))
247
+ if in_notebook:
248
+ return
249
+ try:
250
+ while True:
251
+ time.sleep(0.1)
252
+ except (KeyboardInterrupt, OSError):
253
+ print("Keyboard interruption in main thread... closing dashboard.")
254
+
255
+
256
+ def simplify_column_names(columns: list[str]) -> dict[str, str]:
257
+ """
258
+ Simplifies column names to first 10 alphanumeric or "/" characters with unique suffixes.
259
+
260
+ Args:
261
+ columns: List of original column names
262
+
263
+ Returns:
264
+ Dictionary mapping original column names to simplified names
265
+ """
266
+ simplified_names = {}
267
+ used_names = set()
268
+
269
+ for col in columns:
270
+ alphanumeric = re.sub(r"[^a-zA-Z0-9/]", "", col)
271
+ base_name = alphanumeric[:10] if alphanumeric else f"col_{len(used_names)}"
272
+
273
+ final_name = base_name
274
+ suffix = 1
275
+ while final_name in used_names:
276
+ final_name = f"{base_name}_{suffix}"
277
+ suffix += 1
278
+
279
+ simplified_names[col] = final_name
280
+ used_names.add(final_name)
281
+
282
+ return simplified_names
283
+
284
+
285
+ def print_dashboard_instructions(project: str) -> None:
286
+ """
287
+ Prints instructions for viewing the Trackio dashboard.
288
+
289
+ Args:
290
+ project: The name of the project to show dashboard for.
291
+ """
292
+ YELLOW = "\033[93m"
293
+ BOLD = "\033[1m"
294
+ RESET = "\033[0m"
295
+
296
+ print("* View dashboard by running in your terminal:")
297
+ print(f'{BOLD}{YELLOW}trackio show --project "{project}"{RESET}')
298
+ print(f'* or by running in Python: trackio.show(project="{project}")')
299
+
300
+
301
+ def preprocess_space_and_dataset_ids(
302
+ space_id: str | None, dataset_id: str | None
303
+ ) -> tuple[str | None, str | None]:
304
+ if space_id is not None and "/" not in space_id:
305
+ username = huggingface_hub.whoami()["name"]
306
+ space_id = f"{username}/{space_id}"
307
+ if dataset_id is not None and "/" not in dataset_id:
308
+ username = huggingface_hub.whoami()["name"]
309
+ dataset_id = f"{username}/{dataset_id}"
310
+ if space_id is not None and dataset_id is None:
311
+ dataset_id = f"{space_id}-dataset"
312
+ return space_id, dataset_id
313
+
314
+
315
+ def fibo():
316
+ """Generator for Fibonacci backoff: 1, 1, 2, 3, 5, 8, ..."""
317
+ a, b = 1, 1
318
+ while True:
319
+ yield a
320
+ a, b = b, a + b
321
+
322
+
323
+ COLOR_PALETTE = [
324
+ "#3B82F6",
325
+ "#EF4444",
326
+ "#10B981",
327
+ "#F59E0B",
328
+ "#8B5CF6",
329
+ "#EC4899",
330
+ "#06B6D4",
331
+ "#84CC16",
332
+ "#F97316",
333
+ "#6366F1",
334
+ ]
335
+
336
+
337
+ def get_color_mapping(runs: list[str], smoothing: bool) -> dict[str, str]:
338
+ """Generate color mapping for runs, with transparency for original data when smoothing is enabled."""
339
+ color_map = {}
340
+
341
+ for i, run in enumerate(runs):
342
+ base_color = COLOR_PALETTE[i % len(COLOR_PALETTE)]
343
+
344
+ if smoothing:
345
+ color_map[run] = base_color + "4D"
346
+ color_map[f"{run}_smoothed"] = base_color
347
+ else:
348
+ color_map[run] = base_color
349
+
350
+ return color_map
351
+
352
+
353
+ def downsample(
354
+ df: pd.DataFrame,
355
+ x: str,
356
+ y: str,
357
+ color: str | None,
358
+ x_lim: tuple[float, float] | None = None,
359
+ ) -> pd.DataFrame:
360
+ if df.empty:
361
+ return df
362
+
363
+ columns_to_keep = [x, y]
364
+ if color is not None and color in df.columns:
365
+ columns_to_keep.append(color)
366
+ df = df[columns_to_keep].copy()
367
+
368
+ n_bins = 100
369
+
370
+ if color is not None and color in df.columns:
371
+ groups = df.groupby(color)
372
+ else:
373
+ groups = [(None, df)]
374
+
375
+ downsampled_indices = []
376
+
377
+ for _, group_df in groups:
378
+ if group_df.empty:
379
+ continue
380
+
381
+ group_df = group_df.sort_values(x)
382
+
383
+ if x_lim is not None:
384
+ x_min, x_max = x_lim
385
+ before_point = group_df[group_df[x] < x_min].tail(1)
386
+ after_point = group_df[group_df[x] > x_max].head(1)
387
+ group_df = group_df[(group_df[x] >= x_min) & (group_df[x] <= x_max)]
388
+ else:
389
+ before_point = after_point = None
390
+ x_min = group_df[x].min()
391
+ x_max = group_df[x].max()
392
+
393
+ if before_point is not None and not before_point.empty:
394
+ downsampled_indices.extend(before_point.index.tolist())
395
+ if after_point is not None and not after_point.empty:
396
+ downsampled_indices.extend(after_point.index.tolist())
397
+
398
+ if group_df.empty:
399
+ continue
400
+
401
+ if x_min == x_max:
402
+ min_y_idx = group_df[y].idxmin()
403
+ max_y_idx = group_df[y].idxmax()
404
+ if min_y_idx != max_y_idx:
405
+ downsampled_indices.extend([min_y_idx, max_y_idx])
406
+ else:
407
+ downsampled_indices.append(min_y_idx)
408
+ continue
409
+
410
+ if len(group_df) < 500:
411
+ downsampled_indices.extend(group_df.index.tolist())
412
+ continue
413
+
414
+ bins = np.linspace(x_min, x_max, n_bins + 1)
415
+ group_df["bin"] = pd.cut(
416
+ group_df[x], bins=bins, labels=False, include_lowest=True
417
+ )
418
+
419
+ for bin_idx in group_df["bin"].dropna().unique():
420
+ bin_data = group_df[group_df["bin"] == bin_idx]
421
+ if bin_data.empty:
422
+ continue
423
+
424
+ min_y_idx = bin_data[y].idxmin()
425
+ max_y_idx = bin_data[y].idxmax()
426
+
427
+ downsampled_indices.append(min_y_idx)
428
+ if min_y_idx != max_y_idx:
429
+ downsampled_indices.append(max_y_idx)
430
+
431
+ unique_indices = list(set(downsampled_indices))
432
+
433
+ downsampled_df = df.loc[unique_indices].copy()
434
+
435
+ if color is not None:
436
+ downsampled_df = (
437
+ downsampled_df.groupby(color, sort=False)[downsampled_df.columns]
438
+ .apply(lambda group: group.sort_values(x))
439
+ .reset_index(drop=True)
440
+ )
441
+ else:
442
+ downsampled_df = downsampled_df.sort_values(x).reset_index(drop=True)
443
+
444
+ downsampled_df = downsampled_df.drop(columns=["bin"], errors="ignore")
445
+
446
+ return downsampled_df
447
+
448
+
449
+ def sort_metrics_by_prefix(metrics: list[str]) -> list[str]:
450
+ """
451
+ Sort metrics by grouping prefixes together for dropdown/list display.
452
+ Metrics without prefixes come first, then grouped by prefix.
453
+
454
+ Args:
455
+ metrics: List of metric names
456
+
457
+ Returns:
458
+ List of metric names sorted by prefix
459
+
460
+ Example:
461
+ Input: ["train/loss", "loss", "train/acc", "val/loss"]
462
+ Output: ["loss", "train/acc", "train/loss", "val/loss"]
463
+ """
464
+ groups = group_metrics_by_prefix(metrics)
465
+ result = []
466
+
467
+ if "charts" in groups:
468
+ result.extend(groups["charts"])
469
+
470
+ for group_name in sorted(groups.keys()):
471
+ if group_name != "charts":
472
+ result.extend(groups[group_name])
473
+
474
+ return result
475
+
476
+
477
+ def group_metrics_by_prefix(metrics: list[str]) -> dict[str, list[str]]:
478
+ """
479
+ Group metrics by their prefix. Metrics without prefix go to 'charts' group.
480
+
481
+ Args:
482
+ metrics: List of metric names
483
+
484
+ Returns:
485
+ Dictionary with prefix names as keys and lists of metrics as values
486
+
487
+ Example:
488
+ Input: ["loss", "accuracy", "train/loss", "train/acc", "val/loss"]
489
+ Output: {
490
+ "charts": ["loss", "accuracy"],
491
+ "train": ["train/loss", "train/acc"],
492
+ "val": ["val/loss"]
493
+ }
494
+ """
495
+ no_prefix = []
496
+ with_prefix = []
497
+
498
+ for metric in metrics:
499
+ if "/" in metric:
500
+ with_prefix.append(metric)
501
+ else:
502
+ no_prefix.append(metric)
503
+
504
+ no_prefix.sort()
505
+
506
+ prefix_groups = {}
507
+ for metric in with_prefix:
508
+ prefix = metric.split("/")[0]
509
+ if prefix not in prefix_groups:
510
+ prefix_groups[prefix] = []
511
+ prefix_groups[prefix].append(metric)
512
+
513
+ for prefix in prefix_groups:
514
+ prefix_groups[prefix].sort()
515
+
516
+ groups = {}
517
+ if no_prefix:
518
+ groups["charts"] = no_prefix
519
+
520
+ for prefix in sorted(prefix_groups.keys()):
521
+ groups[prefix] = prefix_groups[prefix]
522
+
523
+ return groups
524
+
525
+
526
+ def group_metrics_with_subprefixes(metrics: list[str]) -> dict:
527
+ """
528
+ Group metrics with simple 2-level nested structure detection.
529
+
530
+ Returns a dictionary where each prefix group can have:
531
+ - direct_metrics: list of metrics at this level (e.g., "train/acc")
532
+ - subgroups: dict of subgroup name -> list of metrics (e.g., "loss" -> ["train/loss/norm", "train/loss/unnorm"])
533
+
534
+ Example:
535
+ Input: ["loss", "train/acc", "train/loss/normalized", "train/loss/unnormalized", "val/loss"]
536
+ Output: {
537
+ "charts": {
538
+ "direct_metrics": ["loss"],
539
+ "subgroups": {}
540
+ },
541
+ "train": {
542
+ "direct_metrics": ["train/acc"],
543
+ "subgroups": {
544
+ "loss": ["train/loss/normalized", "train/loss/unnormalized"]
545
+ }
546
+ },
547
+ "val": {
548
+ "direct_metrics": ["val/loss"],
549
+ "subgroups": {}
550
+ }
551
+ }
552
+ """
553
+ result = {}
554
+
555
+ for metric in metrics:
556
+ if "/" not in metric:
557
+ if "charts" not in result:
558
+ result["charts"] = {"direct_metrics": [], "subgroups": {}}
559
+ result["charts"]["direct_metrics"].append(metric)
560
+ else:
561
+ parts = metric.split("/")
562
+ main_prefix = parts[0]
563
+
564
+ if main_prefix not in result:
565
+ result[main_prefix] = {"direct_metrics": [], "subgroups": {}}
566
+
567
+ if len(parts) == 2:
568
+ result[main_prefix]["direct_metrics"].append(metric)
569
+ else:
570
+ subprefix = parts[1]
571
+ if subprefix not in result[main_prefix]["subgroups"]:
572
+ result[main_prefix]["subgroups"][subprefix] = []
573
+ result[main_prefix]["subgroups"][subprefix].append(metric)
574
+
575
+ for group_data in result.values():
576
+ group_data["direct_metrics"].sort()
577
+ for subgroup_metrics in group_data["subgroups"].values():
578
+ subgroup_metrics.sort()
579
+
580
+ if "charts" in result and not result["charts"]["direct_metrics"]:
581
+ del result["charts"]
582
+
583
+ return result
584
+
585
+
586
+ def get_sync_status(scheduler: "CommitScheduler | DummyCommitScheduler") -> int | None:
587
+ """Get the sync status from the CommitScheduler in an integer number of minutes, or None if not synced yet."""
588
+ if getattr(
589
+ scheduler, "last_push_time", None
590
+ ): # DummyCommitScheduler doesn't have last_push_time
591
+ time_diff = time.time() - scheduler.last_push_time
592
+ return int(time_diff / 60)
593
+ else:
594
+ return None
595
+
596
+
597
+ def generate_embed_code(project: str, metrics: str, selected_runs: list = None) -> str:
598
+ """Generate the embed iframe code based on current settings."""
599
+ space_host = os.environ.get("SPACE_HOST", "")
600
+ if not space_host:
601
+ return ""
602
+
603
+ params = []
604
+
605
+ if project:
606
+ params.append(f"project={project}")
607
+
608
+ if metrics and metrics.strip():
609
+ params.append(f"metrics={metrics}")
610
+
611
+ if selected_runs:
612
+ runs_param = ",".join(selected_runs)
613
+ params.append(f"runs={runs_param}")
614
+
615
+ params.append("sidebar=hidden")
616
+
617
+ query_string = "&".join(params)
618
+ embed_url = f"https://{space_host}?{query_string}"
619
+
620
+ return f'<iframe src="{embed_url}" style="width:1600px; height:500px; border:0;"></iframe>'
621
+
622
+
623
+ def serialize_values(metrics):
624
+ """
625
+ Serialize infinity and NaN values in metrics dict to make it JSON-compliant.
626
+ Only handles top-level float values.
627
+
628
+ Converts:
629
+ - float('inf') -> "Infinity"
630
+ - float('-inf') -> "-Infinity"
631
+ - float('nan') -> "NaN"
632
+
633
+ Example:
634
+ {"loss": float('inf'), "accuracy": 0.95} -> {"loss": "Infinity", "accuracy": 0.95}
635
+ """
636
+ if not isinstance(metrics, dict):
637
+ return metrics
638
+
639
+ result = {}
640
+ for key, value in metrics.items():
641
+ if isinstance(value, float):
642
+ if math.isinf(value):
643
+ result[key] = "Infinity" if value > 0 else "-Infinity"
644
+ elif math.isnan(value):
645
+ result[key] = "NaN"
646
+ else:
647
+ result[key] = value
648
+ elif isinstance(value, np.floating):
649
+ float_val = float(value)
650
+ if math.isinf(float_val):
651
+ result[key] = "Infinity" if float_val > 0 else "-Infinity"
652
+ elif math.isnan(float_val):
653
+ result[key] = "NaN"
654
+ else:
655
+ result[key] = float_val
656
+ else:
657
+ result[key] = value
658
+ return result
659
+
660
+
661
+ def deserialize_values(metrics):
662
+ """
663
+ Deserialize infinity and NaN string values back to their numeric forms.
664
+ Only handles top-level string values.
665
+
666
+ Converts:
667
+ - "Infinity" -> float('inf')
668
+ - "-Infinity" -> float('-inf')
669
+ - "NaN" -> float('nan')
670
+
671
+ Example:
672
+ {"loss": "Infinity", "accuracy": 0.95} -> {"loss": float('inf'), "accuracy": 0.95}
673
+ """
674
+ if not isinstance(metrics, dict):
675
+ return metrics
676
+
677
+ result = {}
678
+ for key, value in metrics.items():
679
+ if value == "Infinity":
680
+ result[key] = float("inf")
681
+ elif value == "-Infinity":
682
+ result[key] = float("-inf")
683
+ elif value == "NaN":
684
+ result[key] = float("nan")
685
+ else:
686
+ result[key] = value
687
+ return result
version.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 0.3.4
video_writer.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import shutil
2
+ import subprocess
3
+ from pathlib import Path
4
+ from typing import Literal
5
+
6
+ import numpy as np
7
+
8
+ VideoCodec = Literal["h264", "vp9", "gif"]
9
+
10
+
11
+ def _check_ffmpeg_installed() -> None:
12
+ """Raise an error if ffmpeg is not available on the system PATH."""
13
+ if shutil.which("ffmpeg") is None:
14
+ raise RuntimeError(
15
+ "ffmpeg is required to write video but was not found on your system. "
16
+ "Please install ffmpeg and ensure it is available on your PATH."
17
+ )
18
+
19
+
20
+ def _check_array_format(video: np.ndarray) -> None:
21
+ """Raise an error if the array is not in the expected format."""
22
+ if not (video.ndim == 4 and video.shape[-1] == 3):
23
+ raise ValueError(
24
+ f"Expected RGB input shaped (F, H, W, 3), got {video.shape}. "
25
+ f"Input has {video.ndim} dimensions, expected 4."
26
+ )
27
+ if video.dtype != np.uint8:
28
+ raise TypeError(
29
+ f"Expected dtype=uint8, got {video.dtype}. "
30
+ "Please convert your video data to uint8 format."
31
+ )
32
+
33
+
34
+ def _check_path(file_path: str | Path) -> None:
35
+ """Raise an error if the parent directory does not exist."""
36
+ file_path = Path(file_path)
37
+ if not file_path.parent.exists():
38
+ try:
39
+ file_path.parent.mkdir(parents=True, exist_ok=True)
40
+ except OSError as e:
41
+ raise ValueError(
42
+ f"Failed to create parent directory {file_path.parent}: {e}"
43
+ )
44
+
45
+
46
+ def write_video(
47
+ file_path: str | Path, video: np.ndarray, fps: float, codec: VideoCodec
48
+ ) -> None:
49
+ """RGB uint8 only, shape (F, H, W, 3)."""
50
+ _check_ffmpeg_installed()
51
+ _check_path(file_path)
52
+
53
+ if codec not in {"h264", "vp9", "gif"}:
54
+ raise ValueError("Unsupported codec. Use h264, vp9, or gif.")
55
+
56
+ arr = np.asarray(video)
57
+ _check_array_format(arr)
58
+
59
+ frames = np.ascontiguousarray(arr)
60
+ _, height, width, _ = frames.shape
61
+ out_path = str(file_path)
62
+
63
+ cmd = [
64
+ "ffmpeg",
65
+ "-y",
66
+ "-f",
67
+ "rawvideo",
68
+ "-s",
69
+ f"{width}x{height}",
70
+ "-pix_fmt",
71
+ "rgb24",
72
+ "-r",
73
+ str(fps),
74
+ "-i",
75
+ "-",
76
+ "-an",
77
+ ]
78
+
79
+ if codec == "gif":
80
+ video_filter = "split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse"
81
+ cmd += [
82
+ "-vf",
83
+ video_filter,
84
+ "-loop",
85
+ "0",
86
+ ]
87
+ elif codec == "h264":
88
+ cmd += [
89
+ "-vcodec",
90
+ "libx264",
91
+ "-pix_fmt",
92
+ "yuv420p",
93
+ "-movflags",
94
+ "+faststart",
95
+ ]
96
+ elif codec == "vp9":
97
+ bpp = 0.08
98
+ bps = int(width * height * fps * bpp)
99
+ if bps >= 1_000_000:
100
+ bitrate = f"{round(bps / 1_000_000)}M"
101
+ elif bps >= 1_000:
102
+ bitrate = f"{round(bps / 1_000)}k"
103
+ else:
104
+ bitrate = str(max(bps, 1))
105
+ cmd += [
106
+ "-vcodec",
107
+ "libvpx-vp9",
108
+ "-b:v",
109
+ bitrate,
110
+ "-pix_fmt",
111
+ "yuv420p",
112
+ ]
113
+ cmd += [out_path]
114
+ proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
115
+ try:
116
+ for frame in frames:
117
+ proc.stdin.write(frame.tobytes())
118
+ finally:
119
+ if proc.stdin:
120
+ proc.stdin.close()
121
+ stderr = (
122
+ proc.stderr.read().decode("utf-8", errors="ignore") if proc.stderr else ""
123
+ )
124
+ ret = proc.wait()
125
+ if ret != 0:
126
+ raise RuntimeError(f"ffmpeg failed with code {ret}\n{stderr}")