ariG23498 HF Staff commited on
Commit
cee7030
·
verified ·
1 Parent(s): 5a34c6c

Upload folder using huggingface_hub

Browse files
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. __init__.py +296 -0
  3. __pycache__/__init__.cpython-312.pyc +0 -0
  4. __pycache__/cli.cpython-312.pyc +0 -0
  5. __pycache__/commit_scheduler.cpython-312.pyc +0 -0
  6. __pycache__/context_vars.cpython-312.pyc +0 -0
  7. __pycache__/deploy.cpython-312.pyc +0 -0
  8. __pycache__/dummy_commit_scheduler.cpython-312.pyc +0 -0
  9. __pycache__/file_storage.cpython-312.pyc +0 -0
  10. __pycache__/imports.cpython-312.pyc +0 -0
  11. __pycache__/media.cpython-312.pyc +0 -0
  12. __pycache__/run.cpython-312.pyc +0 -0
  13. __pycache__/sqlite_storage.cpython-312.pyc +0 -0
  14. __pycache__/table.cpython-312.pyc +0 -0
  15. __pycache__/typehints.cpython-312.pyc +0 -0
  16. __pycache__/utils.cpython-312.pyc +0 -0
  17. __pycache__/video_writer.cpython-312.pyc +0 -0
  18. assets/trackio_logo_dark.png +0 -0
  19. assets/trackio_logo_light.png +0 -0
  20. assets/trackio_logo_old.png +3 -0
  21. assets/trackio_logo_type_dark.png +0 -0
  22. assets/trackio_logo_type_dark_transparent.png +0 -0
  23. assets/trackio_logo_type_light.png +0 -0
  24. assets/trackio_logo_type_light_transparent.png +0 -0
  25. cli.py +32 -0
  26. commit_scheduler.py +391 -0
  27. context_vars.py +18 -0
  28. deploy.py +225 -0
  29. dummy_commit_scheduler.py +12 -0
  30. file_storage.py +37 -0
  31. imports.py +302 -0
  32. media.py +286 -0
  33. py.typed +0 -0
  34. run.py +176 -0
  35. sqlite_storage.py +559 -0
  36. table.py +53 -0
  37. typehints.py +18 -0
  38. ui/__init__.py +10 -0
  39. ui/__pycache__/__init__.cpython-312.pyc +0 -0
  40. ui/__pycache__/fns.cpython-312.pyc +0 -0
  41. ui/__pycache__/main.cpython-312.pyc +0 -0
  42. ui/__pycache__/run_detail.cpython-312.pyc +0 -0
  43. ui/__pycache__/runs.cpython-312.pyc +0 -0
  44. ui/fns.py +58 -0
  45. ui/main.py +943 -0
  46. ui/run_detail.py +90 -0
  47. ui/runs.py +236 -0
  48. utils.py +771 -0
  49. version.txt +1 -0
  50. video_writer.py +126 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ assets/trackio_logo_old.png filter=lfs diff=lfs merge=lfs -text
__init__.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.main 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
+ private: bool | None = None,
56
+ embed: bool = True,
57
+ ) -> Run:
58
+ """
59
+ Creates a new Trackio project and returns a [`Run`] object.
60
+
61
+ Args:
62
+ project (`str`):
63
+ The name of the project (can be an existing project to continue tracking or
64
+ a new project to start tracking from scratch).
65
+ name (`str`, *optional*):
66
+ The name of the run (if not provided, a default name will be generated).
67
+ space_id (`str`, *optional*):
68
+ If provided, the project will be logged to a Hugging Face Space instead of
69
+ a local directory. Should be a complete Space name like
70
+ `"username/reponame"` or `"orgname/reponame"`, or just `"reponame"` in which
71
+ case the Space will be created in the currently-logged-in Hugging Face
72
+ user's namespace. If the Space does not exist, it will be created. If the
73
+ Space already exists, the project will be logged to it.
74
+ space_storage ([`~huggingface_hub.SpaceStorage`], *optional*):
75
+ Choice of persistent storage tier.
76
+ dataset_id (`str`, *optional*):
77
+ If a `space_id` is provided, a persistent Hugging Face Dataset will be
78
+ created and the metrics will be synced to it every 5 minutes. Specify a
79
+ Dataset with name like `"username/datasetname"` or `"orgname/datasetname"`,
80
+ or `"datasetname"` (uses currently-logged-in Hugging Face user's namespace),
81
+ or `None` (uses the same name as the Space but with the `"_dataset"`
82
+ suffix). If the Dataset does not exist, it will be created. If the Dataset
83
+ already exists, the project will be appended to it.
84
+ config (`dict`, *optional*):
85
+ A dictionary of configuration options. Provided for compatibility with
86
+ `wandb.init()`.
87
+ resume (`str`, *optional*, defaults to `"never"`):
88
+ Controls how to handle resuming a run. Can be one of:
89
+
90
+ - `"must"`: Must resume the run with the given name, raises error if run
91
+ doesn't exist
92
+ - `"allow"`: Resume the run if it exists, otherwise create a new run
93
+ - `"never"`: Never resume a run, always create a new one
94
+ private (`bool`, *optional*):
95
+ Whether to make the Space private. If None (default), the repo will be
96
+ public unless the organization's default is private. This value is ignored
97
+ if the repo already exists.
98
+ settings (`Any`, *optional*):
99
+ Not used. Provided for compatibility with `wandb.init()`.
100
+ embed (`bool`, *optional*, defaults to `True`):
101
+ If running inside a jupyter/Colab notebook, whether the dashboard should
102
+ automatically be embedded in the cell when trackio.init() is called.
103
+
104
+ Returns:
105
+ `Run`: A [`Run`] object that can be used to log metrics and finish the run.
106
+ """
107
+ if settings is not None:
108
+ warnings.warn(
109
+ "* 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."
110
+ )
111
+
112
+ if space_id is None and dataset_id is not None:
113
+ raise ValueError("Must provide a `space_id` when `dataset_id` is provided.")
114
+ space_id, dataset_id = utils.preprocess_space_and_dataset_ids(space_id, dataset_id)
115
+ url = context_vars.current_server.get()
116
+ share_url = context_vars.current_share_server.get()
117
+
118
+ if url is None:
119
+ if space_id is None:
120
+ _, url, share_url = demo.launch(
121
+ show_api=False,
122
+ inline=False,
123
+ quiet=True,
124
+ prevent_thread_lock=True,
125
+ show_error=True,
126
+ favicon_path=TRACKIO_LOGO_DIR / "trackio_logo_light.png",
127
+ allowed_paths=[TRACKIO_LOGO_DIR],
128
+ )
129
+ else:
130
+ url = space_id
131
+ share_url = None
132
+ context_vars.current_server.set(url)
133
+ context_vars.current_share_server.set(share_url)
134
+ if (
135
+ context_vars.current_project.get() is None
136
+ or context_vars.current_project.get() != project
137
+ ):
138
+ print(f"* Trackio project initialized: {project}")
139
+
140
+ if dataset_id is not None:
141
+ os.environ["TRACKIO_DATASET_ID"] = dataset_id
142
+ print(
143
+ f"* Trackio metrics will be synced to Hugging Face Dataset: {dataset_id}"
144
+ )
145
+ if space_id is None:
146
+ print(f"* Trackio metrics logged to: {TRACKIO_DIR}")
147
+ if utils.is_in_notebook() and embed:
148
+ base_url = share_url + "/" if share_url else url
149
+ full_url = utils.get_full_url(
150
+ base_url, project=project, write_token=demo.write_token
151
+ )
152
+ utils.embed_url_in_notebook(full_url)
153
+ else:
154
+ utils.print_dashboard_instructions(project)
155
+ else:
156
+ deploy.create_space_if_not_exists(
157
+ space_id, space_storage, dataset_id, private
158
+ )
159
+ user_name, space_name = space_id.split("/")
160
+ space_url = deploy.SPACE_HOST_URL.format(
161
+ user_name=user_name, space_name=space_name
162
+ )
163
+ print(f"* View dashboard by going to: {space_url}")
164
+ if utils.is_in_notebook() and embed:
165
+ utils.embed_url_in_notebook(space_url)
166
+ context_vars.current_project.set(project)
167
+
168
+ client = None
169
+ if not space_id:
170
+ client = Client(url, verbose=False)
171
+
172
+ if resume == "must":
173
+ if name is None:
174
+ raise ValueError("Must provide a run name when resume='must'")
175
+ if name not in SQLiteStorage.get_runs(project):
176
+ raise ValueError(f"Run '{name}' does not exist in project '{project}'")
177
+ resumed = True
178
+ elif resume == "allow":
179
+ resumed = name is not None and name in SQLiteStorage.get_runs(project)
180
+ elif resume == "never":
181
+ if name is not None and name in SQLiteStorage.get_runs(project):
182
+ warnings.warn(
183
+ f"* Warning: resume='never' but a run '{name}' already exists in "
184
+ f"project '{project}'. Generating a new name and instead. If you want "
185
+ "to resume this run, call init() with resume='must' or resume='allow'."
186
+ )
187
+ name = None
188
+ resumed = False
189
+ else:
190
+ raise ValueError("resume must be one of: 'must', 'allow', or 'never'")
191
+
192
+ run = Run(
193
+ url=url,
194
+ project=project,
195
+ client=client,
196
+ name=name,
197
+ config=config,
198
+ space_id=space_id,
199
+ )
200
+
201
+ if resumed:
202
+ print(f"* Resumed existing run: {run.name}")
203
+ else:
204
+ print(f"* Created new run: {run.name}")
205
+
206
+ context_vars.current_run.set(run)
207
+ globals()["config"] = run.config
208
+ return run
209
+
210
+
211
+ def log(metrics: dict, step: int | None = None) -> None:
212
+ """
213
+ Logs metrics to the current run.
214
+
215
+ Args:
216
+ metrics (`dict`):
217
+ A dictionary of metrics to log.
218
+ step (`int`, *optional*):
219
+ The step number. If not provided, the step will be incremented
220
+ automatically.
221
+ """
222
+ run = context_vars.current_run.get()
223
+ if run is None:
224
+ raise RuntimeError("Call trackio.init() before trackio.log().")
225
+ run.log(
226
+ metrics=metrics,
227
+ step=step,
228
+ )
229
+
230
+
231
+ def finish():
232
+ """
233
+ Finishes the current run.
234
+ """
235
+ run = context_vars.current_run.get()
236
+ if run is None:
237
+ raise RuntimeError("Call trackio.init() before trackio.finish().")
238
+ run.finish()
239
+
240
+
241
+ def show(project: str | None = None, theme: str | ThemeClass = DEFAULT_THEME):
242
+ """
243
+ Launches the Trackio dashboard.
244
+
245
+ Args:
246
+ project (`str`, *optional*):
247
+ The name of the project whose runs to show. If not provided, all projects
248
+ will be shown and the user can select one.
249
+ theme (`str` or `ThemeClass`, *optional*, defaults to `"citrus"`):
250
+ A Gradio Theme to use for the dashboard instead of the default `"citrus"`,
251
+ can be a built-in theme (e.g. `'soft'`, `'default'`), a theme from the Hub
252
+ (e.g. `"gstaff/xkcd"`), or a custom Theme class.
253
+ """
254
+ if theme != DEFAULT_THEME:
255
+ # TODO: It's a little hacky to reproduce this theme-setting logic from Gradio Blocks,
256
+ # but in Gradio 6.0, the theme will be set in `launch()` instead, which means that we
257
+ # will be able to remove this code.
258
+ if isinstance(theme, str):
259
+ if theme.lower() in BUILT_IN_THEMES:
260
+ theme = BUILT_IN_THEMES[theme.lower()]
261
+ else:
262
+ try:
263
+ theme = ThemeClass.from_hub(theme)
264
+ except Exception as e:
265
+ warnings.warn(f"Cannot load {theme}. Caught Exception: {str(e)}")
266
+ theme = DefaultTheme()
267
+ if not isinstance(theme, ThemeClass):
268
+ warnings.warn("Theme should be a class loaded from gradio.themes")
269
+ theme = DefaultTheme()
270
+ demo.theme: ThemeClass = theme
271
+ demo.theme_css = theme._get_theme_css()
272
+ demo.stylesheets = theme._stylesheets
273
+ theme_hasher = hashlib.sha256()
274
+ theme_hasher.update(demo.theme_css.encode("utf-8"))
275
+ demo.theme_hash = theme_hasher.hexdigest()
276
+
277
+ _, url, share_url = demo.launch(
278
+ show_api=False,
279
+ quiet=True,
280
+ inline=False,
281
+ prevent_thread_lock=True,
282
+ favicon_path=TRACKIO_LOGO_DIR / "trackio_logo_light.png",
283
+ allowed_paths=[TRACKIO_LOGO_DIR],
284
+ )
285
+
286
+ base_url = share_url + "/" if share_url else url
287
+ full_url = utils.get_full_url(
288
+ base_url, project=project, write_token=demo.write_token
289
+ )
290
+
291
+ if not utils.is_in_notebook():
292
+ print(f"* Trackio UI launched at: {full_url}")
293
+ webbrowser.open(full_url)
294
+ utils.block_main_thread_until_keyboard_interrupt()
295
+ else:
296
+ utils.embed_url_in_notebook(full_url)
__pycache__/__init__.cpython-312.pyc ADDED
Binary file (13 kB). View file
 
__pycache__/cli.cpython-312.pyc ADDED
Binary file (1.44 kB). View file
 
__pycache__/commit_scheduler.cpython-312.pyc ADDED
Binary file (18.8 kB). View file
 
__pycache__/context_vars.cpython-312.pyc ADDED
Binary file (933 Bytes). View file
 
__pycache__/deploy.cpython-312.pyc ADDED
Binary file (8.81 kB). View file
 
__pycache__/dummy_commit_scheduler.cpython-312.pyc ADDED
Binary file (1.03 kB). View file
 
__pycache__/file_storage.cpython-312.pyc ADDED
Binary file (1.65 kB). View file
 
__pycache__/imports.cpython-312.pyc ADDED
Binary file (13.2 kB). View file
 
__pycache__/media.cpython-312.pyc ADDED
Binary file (14.1 kB). View file
 
__pycache__/run.cpython-312.pyc ADDED
Binary file (8.84 kB). View file
 
__pycache__/sqlite_storage.cpython-312.pyc ADDED
Binary file (27.3 kB). View file
 
__pycache__/table.cpython-312.pyc ADDED
Binary file (2.34 kB). View file
 
__pycache__/typehints.cpython-312.pyc ADDED
Binary file (920 Bytes). View file
 
__pycache__/utils.cpython-312.pyc ADDED
Binary file (23.6 kB). View file
 
__pycache__/video_writer.cpython-312.pyc ADDED
Binary file (5.34 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, 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: str | None = None,
115
+ repo_type: str | None = None,
116
+ revision: str | None = None,
117
+ private: bool | None = None,
118
+ token: str | None = None,
119
+ allow_patterns: list[str] | str | None = None,
120
+ ignore_patterns: list[str] | str | None = None,
121
+ squash_history: bool = False,
122
+ hf_api: HfApi | None = None,
123
+ on_before_commit: Callable[[], None] | 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) -> CommitInfo | None:
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) -> CommitInfo | None:
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: int | None = -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,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ )
16
+ current_share_server: contextvars.ContextVar[str | None] = contextvars.ContextVar(
17
+ "current_share_server", default=None
18
+ )
deploy.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_HOST_URL = "https://{user_name}-{space_name}.hf.space/"
19
+ SPACE_URL = "https://huggingface.co/spaces/{space_id}"
20
+
21
+
22
+ def _is_trackio_installed_from_source() -> bool:
23
+ """Check if trackio is installed from source/editable install vs PyPI."""
24
+ try:
25
+ trackio_file = trackio.__file__
26
+ if "site-packages" not in trackio_file:
27
+ return True
28
+
29
+ dist = importlib.metadata.distribution("trackio")
30
+ if dist.files:
31
+ files = list(dist.files)
32
+ has_pth = any(".pth" in str(f) for f in files)
33
+ if has_pth:
34
+ return True
35
+
36
+ return False
37
+ except (
38
+ AttributeError,
39
+ importlib.metadata.PackageNotFoundError,
40
+ importlib.metadata.MetadataError,
41
+ ValueError,
42
+ TypeError,
43
+ ):
44
+ return True
45
+
46
+
47
+ def deploy_as_space(
48
+ space_id: str,
49
+ space_storage: huggingface_hub.SpaceStorage | None = None,
50
+ dataset_id: str | None = None,
51
+ private: bool | None = None,
52
+ ):
53
+ if (
54
+ os.getenv("SYSTEM") == "spaces"
55
+ ): # in case a repo with this function is uploaded to spaces
56
+ return
57
+
58
+ trackio_path = files("trackio")
59
+
60
+ hf_api = huggingface_hub.HfApi()
61
+
62
+ try:
63
+ huggingface_hub.create_repo(
64
+ space_id,
65
+ private=private,
66
+ space_sdk="gradio",
67
+ space_storage=space_storage,
68
+ repo_type="space",
69
+ exist_ok=True,
70
+ )
71
+ except HTTPError as e:
72
+ if e.response.status_code in [401, 403]: # unauthorized or forbidden
73
+ print("Need 'write' access token to create a Spaces repo.")
74
+ huggingface_hub.login(add_to_git_credential=False)
75
+ huggingface_hub.create_repo(
76
+ space_id,
77
+ private=private,
78
+ space_sdk="gradio",
79
+ space_storage=space_storage,
80
+ repo_type="space",
81
+ exist_ok=True,
82
+ )
83
+ else:
84
+ raise ValueError(f"Failed to create Space: {e}")
85
+
86
+ with open(Path(trackio_path, "README.md"), "r") as f:
87
+ readme_content = f.read()
88
+ readme_content = readme_content.replace("{GRADIO_VERSION}", gradio.__version__)
89
+ readme_buffer = io.BytesIO(readme_content.encode("utf-8"))
90
+ hf_api.upload_file(
91
+ path_or_fileobj=readme_buffer,
92
+ path_in_repo="README.md",
93
+ repo_id=space_id,
94
+ repo_type="space",
95
+ )
96
+
97
+ # We can assume pandas, gradio, and huggingface-hub are already installed in a Gradio Space.
98
+ # Make sure necessary dependencies are installed by creating a requirements.txt.
99
+ is_source_install = _is_trackio_installed_from_source()
100
+
101
+ if is_source_install:
102
+ requirements_content = """pyarrow>=21.0"""
103
+ else:
104
+ requirements_content = f"""pyarrow>=21.0
105
+ trackio=={trackio.__version__}"""
106
+
107
+ requirements_buffer = io.BytesIO(requirements_content.encode("utf-8"))
108
+ hf_api.upload_file(
109
+ path_or_fileobj=requirements_buffer,
110
+ path_in_repo="requirements.txt",
111
+ repo_id=space_id,
112
+ repo_type="space",
113
+ )
114
+
115
+ huggingface_hub.utils.disable_progress_bars()
116
+
117
+ if is_source_install:
118
+ hf_api.upload_folder(
119
+ repo_id=space_id,
120
+ repo_type="space",
121
+ folder_path=trackio_path,
122
+ ignore_patterns=["README.md"],
123
+ )
124
+ else:
125
+ app_file_content = """import trackio
126
+ trackio.show()"""
127
+ app_file_buffer = io.BytesIO(app_file_content.encode("utf-8"))
128
+ hf_api.upload_file(
129
+ path_or_fileobj=app_file_buffer,
130
+ path_in_repo="ui/main.py",
131
+ repo_id=space_id,
132
+ repo_type="space",
133
+ )
134
+
135
+ if hf_token := huggingface_hub.utils.get_token():
136
+ huggingface_hub.add_space_secret(space_id, "HF_TOKEN", hf_token)
137
+ if dataset_id is not None:
138
+ huggingface_hub.add_space_variable(space_id, "TRACKIO_DATASET_ID", dataset_id)
139
+
140
+
141
+ def create_space_if_not_exists(
142
+ space_id: str,
143
+ space_storage: huggingface_hub.SpaceStorage | None = None,
144
+ dataset_id: str | None = None,
145
+ private: bool | None = None,
146
+ ) -> None:
147
+ """
148
+ 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.
149
+
150
+ Args:
151
+ space_id: The ID of the Space to create.
152
+ dataset_id: The ID of the Dataset to add to the Space.
153
+ private: Whether to make the Space private. If None (default), the repo will be
154
+ public unless the organization's default is private. This value is ignored if
155
+ the repo already exists.
156
+ """
157
+ if "/" not in space_id:
158
+ raise ValueError(
159
+ f"Invalid space ID: {space_id}. Must be in the format: username/reponame or orgname/reponame."
160
+ )
161
+ if dataset_id is not None and "/" not in dataset_id:
162
+ raise ValueError(
163
+ f"Invalid dataset ID: {dataset_id}. Must be in the format: username/datasetname or orgname/datasetname."
164
+ )
165
+ try:
166
+ huggingface_hub.repo_info(space_id, repo_type="space")
167
+ print(f"* Found existing space: {SPACE_URL.format(space_id=space_id)}")
168
+ if dataset_id is not None:
169
+ huggingface_hub.add_space_variable(
170
+ space_id, "TRACKIO_DATASET_ID", dataset_id
171
+ )
172
+ return
173
+ except RepositoryNotFoundError:
174
+ pass
175
+ except HTTPError as e:
176
+ if e.response.status_code in [401, 403]: # unauthorized or forbidden
177
+ print("Need 'write' access token to create a Spaces repo.")
178
+ huggingface_hub.login(add_to_git_credential=False)
179
+ huggingface_hub.add_space_variable(
180
+ space_id, "TRACKIO_DATASET_ID", dataset_id
181
+ )
182
+ else:
183
+ raise ValueError(f"Failed to create Space: {e}")
184
+
185
+ print(f"* Creating new space: {SPACE_URL.format(space_id=space_id)}")
186
+ deploy_as_space(space_id, space_storage, dataset_id, private)
187
+
188
+
189
+ def wait_until_space_exists(
190
+ space_id: str,
191
+ ) -> None:
192
+ """
193
+ Blocks the current thread until the space exists.
194
+ May raise a TimeoutError if this takes quite a while.
195
+
196
+ Args:
197
+ space_id: The ID of the Space to wait for.
198
+ """
199
+ delay = 1
200
+ for _ in range(10):
201
+ try:
202
+ Client(space_id, verbose=False)
203
+ return
204
+ except (ReadTimeout, ValueError):
205
+ time.sleep(delay)
206
+ delay = min(delay * 2, 30)
207
+ raise TimeoutError("Waiting for space to exist took longer than expected")
208
+
209
+
210
+ def upload_db_to_space(project: str, space_id: str) -> None:
211
+ """
212
+ Uploads the database of a local Trackio project to a Hugging Face Space.
213
+
214
+ Args:
215
+ project: The name of the project to upload.
216
+ space_id: The ID of the Space to upload to.
217
+ """
218
+ db_path = SQLiteStorage.get_project_db_path(project)
219
+ client = Client(space_id, verbose=False)
220
+ client.predict(
221
+ api_name="/upload_db_to_space",
222
+ project=project,
223
+ uploaded_db=handle_file(db_path),
224
+ hf_token=huggingface_hub.utils.get_token(),
225
+ )
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,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ private: bool | None = None,
17
+ ) -> None:
18
+ """
19
+ Imports a CSV file into a Trackio project. The CSV file must contain a `"step"`
20
+ column, may optionally contain a `"timestamp"` column, and any other columns will be
21
+ treated as metrics. It should also include a header row with the column names.
22
+
23
+ TODO: call init() and return a Run object so that the user can continue to log metrics to it.
24
+
25
+ Args:
26
+ csv_path (`str` or `Path`):
27
+ The str or Path to the CSV file to import.
28
+ project (`str`):
29
+ The name of the project to import the CSV file into. Must not be an existing
30
+ project.
31
+ name (`str`, *optional*):
32
+ The name of the Run to import the CSV file into. If not provided, a default
33
+ name will be generated.
34
+ name (`str`, *optional*):
35
+ The name of the run (if not provided, a default name will be generated).
36
+ space_id (`str`, *optional*):
37
+ If provided, the project will be logged to a Hugging Face Space instead of a
38
+ local directory. Should be a complete Space name like `"username/reponame"`
39
+ or `"orgname/reponame"`, or just `"reponame"` in which case the Space will
40
+ be created in the currently-logged-in Hugging Face user's namespace. If the
41
+ Space does not exist, it will be created. If the Space already exists, the
42
+ project will be logged to it.
43
+ dataset_id (`str`, *optional*):
44
+ If provided, a persistent Hugging Face Dataset will be created and the
45
+ metrics will be synced to it every 5 minutes. Should be a complete Dataset
46
+ name like `"username/datasetname"` or `"orgname/datasetname"`, or just
47
+ `"datasetname"` in which case the Dataset will be created in the
48
+ currently-logged-in Hugging Face user's namespace. If the Dataset does not
49
+ exist, it will be created. If the Dataset already exists, the project will
50
+ be appended to it. If not provided, the metrics will be logged to a local
51
+ SQLite database, unless a `space_id` is provided, in which case a Dataset
52
+ will be automatically created with the same name as the Space but with the
53
+ `"_dataset"` suffix.
54
+ private (`bool`, *optional*):
55
+ Whether to make the Space private. If None (default), the repo will be
56
+ public unless the organization's default is private. This value is ignored
57
+ if the repo already exists.
58
+ """
59
+ if SQLiteStorage.get_runs(project):
60
+ raise ValueError(
61
+ f"Project '{project}' already exists. Cannot import CSV into existing project."
62
+ )
63
+
64
+ csv_path = Path(csv_path)
65
+ if not csv_path.exists():
66
+ raise FileNotFoundError(f"CSV file not found: {csv_path}")
67
+
68
+ df = pd.read_csv(csv_path)
69
+ if df.empty:
70
+ raise ValueError("CSV file is empty")
71
+
72
+ column_mapping = utils.simplify_column_names(df.columns.tolist())
73
+ df = df.rename(columns=column_mapping)
74
+
75
+ step_column = None
76
+ for col in df.columns:
77
+ if col.lower() == "step":
78
+ step_column = col
79
+ break
80
+
81
+ if step_column is None:
82
+ raise ValueError("CSV file must contain a 'step' or 'Step' column")
83
+
84
+ if name is None:
85
+ name = csv_path.stem
86
+
87
+ metrics_list = []
88
+ steps = []
89
+ timestamps = []
90
+
91
+ numeric_columns = []
92
+ for column in df.columns:
93
+ if column == step_column:
94
+ continue
95
+ if column == "timestamp":
96
+ continue
97
+
98
+ try:
99
+ pd.to_numeric(df[column], errors="raise")
100
+ numeric_columns.append(column)
101
+ except (ValueError, TypeError):
102
+ continue
103
+
104
+ for _, row in df.iterrows():
105
+ metrics = {}
106
+ for column in numeric_columns:
107
+ value = row[column]
108
+ if bool(pd.notna(value)):
109
+ metrics[column] = float(value)
110
+
111
+ if metrics:
112
+ metrics_list.append(metrics)
113
+ steps.append(int(row[step_column]))
114
+
115
+ if "timestamp" in df.columns and bool(pd.notna(row["timestamp"])):
116
+ timestamps.append(str(row["timestamp"]))
117
+ else:
118
+ timestamps.append("")
119
+
120
+ if metrics_list:
121
+ SQLiteStorage.bulk_log(
122
+ project=project,
123
+ run=name,
124
+ metrics_list=metrics_list,
125
+ steps=steps,
126
+ timestamps=timestamps,
127
+ )
128
+
129
+ print(
130
+ f"* Imported {len(metrics_list)} rows from {csv_path} into project '{project}' as run '{name}'"
131
+ )
132
+ print(f"* Metrics found: {', '.join(metrics_list[0].keys())}")
133
+
134
+ space_id, dataset_id = utils.preprocess_space_and_dataset_ids(space_id, dataset_id)
135
+ if dataset_id is not None:
136
+ os.environ["TRACKIO_DATASET_ID"] = dataset_id
137
+ print(f"* Trackio metrics will be synced to Hugging Face Dataset: {dataset_id}")
138
+
139
+ if space_id is None:
140
+ utils.print_dashboard_instructions(project)
141
+ else:
142
+ deploy.create_space_if_not_exists(
143
+ space_id=space_id, dataset_id=dataset_id, private=private
144
+ )
145
+ deploy.wait_until_space_exists(space_id=space_id)
146
+ deploy.upload_db_to_space(project=project, space_id=space_id)
147
+ print(
148
+ f"* View dashboard by going to: {deploy.SPACE_URL.format(space_id=space_id)}"
149
+ )
150
+
151
+
152
+ def import_tf_events(
153
+ log_dir: str | Path,
154
+ project: str,
155
+ name: str | None = None,
156
+ space_id: str | None = None,
157
+ dataset_id: str | None = None,
158
+ private: bool | None = None,
159
+ ) -> None:
160
+ """
161
+ Imports TensorFlow Events files from a directory into a Trackio project. Each
162
+ subdirectory in the log directory will be imported as a separate run.
163
+
164
+ Args:
165
+ log_dir (`str` or `Path`):
166
+ The str or Path to the directory containing TensorFlow Events files.
167
+ project (`str`):
168
+ The name of the project to import the TensorFlow Events files into. Must not
169
+ be an existing project.
170
+ name (`str`, *optional*):
171
+ The name prefix for runs (if not provided, will use directory names). Each
172
+ subdirectory will create a separate run.
173
+ space_id (`str`, *optional*):
174
+ If provided, the project will be logged to a Hugging Face Space instead of a
175
+ local directory. Should be a complete Space name like `"username/reponame"`
176
+ or `"orgname/reponame"`, or just `"reponame"` in which case the Space will
177
+ be created in the currently-logged-in Hugging Face user's namespace. If the
178
+ Space does not exist, it will be created. If the Space already exists, the
179
+ project will be logged to it.
180
+ dataset_id (`str`, *optional*):
181
+ If provided, a persistent Hugging Face Dataset will be created and the
182
+ metrics will be synced to it every 5 minutes. Should be a complete Dataset
183
+ name like `"username/datasetname"` or `"orgname/datasetname"`, or just
184
+ `"datasetname"` in which case the Dataset will be created in the
185
+ currently-logged-in Hugging Face user's namespace. If the Dataset does not
186
+ exist, it will be created. If the Dataset already exists, the project will
187
+ be appended to it. If not provided, the metrics will be logged to a local
188
+ SQLite database, unless a `space_id` is provided, in which case a Dataset
189
+ will be automatically created with the same name as the Space but with the
190
+ `"_dataset"` suffix.
191
+ private (`bool`, *optional*):
192
+ Whether to make the Space private. If None (default), the repo will be
193
+ public unless the organization's default is private. This value is ignored
194
+ if the repo already exists.
195
+ """
196
+ try:
197
+ from tbparse import SummaryReader
198
+ except ImportError:
199
+ raise ImportError(
200
+ "The `tbparse` package is not installed but is required for `import_tf_events`. Please install trackio with the `tensorboard` extra: `pip install trackio[tensorboard]`."
201
+ )
202
+
203
+ if SQLiteStorage.get_runs(project):
204
+ raise ValueError(
205
+ f"Project '{project}' already exists. Cannot import TF events into existing project."
206
+ )
207
+
208
+ path = Path(log_dir)
209
+ if not path.exists():
210
+ raise FileNotFoundError(f"TF events directory not found: {path}")
211
+
212
+ # Use tbparse to read all tfevents files in the directory structure
213
+ reader = SummaryReader(str(path), extra_columns={"dir_name"})
214
+ df = reader.scalars
215
+
216
+ if df.empty:
217
+ raise ValueError(f"No TensorFlow events data found in {path}")
218
+
219
+ total_imported = 0
220
+ imported_runs = []
221
+
222
+ # Group by dir_name to create separate runs
223
+ for dir_name, group_df in df.groupby("dir_name"):
224
+ try:
225
+ # Determine run name based on directory name
226
+ if dir_name == "":
227
+ run_name = "main" # For files in the root directory
228
+ else:
229
+ run_name = dir_name # Use directory name
230
+
231
+ if name:
232
+ run_name = f"{name}_{run_name}"
233
+
234
+ if group_df.empty:
235
+ print(f"* Skipping directory {dir_name}: no scalar data found")
236
+ continue
237
+
238
+ metrics_list = []
239
+ steps = []
240
+ timestamps = []
241
+
242
+ for _, row in group_df.iterrows():
243
+ # Convert row values to appropriate types
244
+ tag = str(row["tag"])
245
+ value = float(row["value"])
246
+ step = int(row["step"])
247
+
248
+ metrics = {tag: value}
249
+ metrics_list.append(metrics)
250
+ steps.append(step)
251
+
252
+ # Use wall_time if present, else fallback
253
+ if "wall_time" in group_df.columns and not bool(
254
+ pd.isna(row["wall_time"])
255
+ ):
256
+ timestamps.append(str(row["wall_time"]))
257
+ else:
258
+ timestamps.append("")
259
+
260
+ if metrics_list:
261
+ SQLiteStorage.bulk_log(
262
+ project=project,
263
+ run=str(run_name),
264
+ metrics_list=metrics_list,
265
+ steps=steps,
266
+ timestamps=timestamps,
267
+ )
268
+
269
+ total_imported += len(metrics_list)
270
+ imported_runs.append(run_name)
271
+
272
+ print(
273
+ f"* Imported {len(metrics_list)} scalar events from directory '{dir_name}' as run '{run_name}'"
274
+ )
275
+ print(f"* Metrics in this run: {', '.join(set(group_df['tag']))}")
276
+
277
+ except Exception as e:
278
+ print(f"* Error processing directory {dir_name}: {e}")
279
+ continue
280
+
281
+ if not imported_runs:
282
+ raise ValueError("No valid TensorFlow events data could be imported")
283
+
284
+ print(f"* Total imported events: {total_imported}")
285
+ print(f"* Created runs: {', '.join(imported_runs)}")
286
+
287
+ space_id, dataset_id = utils.preprocess_space_and_dataset_ids(space_id, dataset_id)
288
+ if dataset_id is not None:
289
+ os.environ["TRACKIO_DATASET_ID"] = dataset_id
290
+ print(f"* Trackio metrics will be synced to Hugging Face Dataset: {dataset_id}")
291
+
292
+ if space_id is None:
293
+ utils.print_dashboard_instructions(project)
294
+ else:
295
+ deploy.create_space_if_not_exists(
296
+ space_id, dataset_id=dataset_id, private=private
297
+ )
298
+ deploy.wait_until_space_exists(space_id)
299
+ deploy.upload_db_to_space(project, space_id)
300
+ print(
301
+ f"* View dashboard by going to: {deploy.SPACE_URL.format(space_id=space_id)}"
302
+ )
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*):
123
+ A path to an image, a PIL Image, or a numpy array of shape (height, width, channels).
124
+ caption (`str`, *optional*):
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*):
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*):
193
+ A string caption for the video.
194
+ fps (`int`, *optional*):
195
+ Frames per second for the video. Only used when value is an ndarray. Default is `24`.
196
+ format (`Literal["gif", "mp4", "webm"]`, *optional*):
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,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import threading
2
+ import time
3
+ from datetime import datetime, timezone
4
+
5
+ import huggingface_hub
6
+ from gradio_client import Client, handle_file
7
+
8
+ from trackio import utils
9
+ from trackio.media import TrackioMedia
10
+ from trackio.sqlite_storage import SQLiteStorage
11
+ from trackio.table import Table
12
+ from trackio.typehints import LogEntry, UploadEntry
13
+
14
+ BATCH_SEND_INTERVAL = 0.5
15
+
16
+
17
+ class Run:
18
+ def __init__(
19
+ self,
20
+ url: str,
21
+ project: str,
22
+ client: Client | None,
23
+ name: str | None = None,
24
+ config: dict | None = None,
25
+ space_id: str | None = None,
26
+ ):
27
+ self.url = url
28
+ self.project = project
29
+ self._client_lock = threading.Lock()
30
+ self._client_thread = None
31
+ self._client = client
32
+ self._space_id = space_id
33
+ self.name = name or utils.generate_readable_name(
34
+ SQLiteStorage.get_runs(project), space_id
35
+ )
36
+ self.config = utils.to_json_safe(config or {})
37
+
38
+ if isinstance(self.config, dict):
39
+ for key in self.config:
40
+ if key.startswith("_"):
41
+ raise ValueError(
42
+ f"Config key '{key}' is reserved (keys starting with '_' are reserved for internal use)"
43
+ )
44
+
45
+ self.config["_Username"] = self._get_username()
46
+ self.config["_Created"] = datetime.now(timezone.utc).isoformat()
47
+ self._queued_logs: list[LogEntry] = []
48
+ self._queued_uploads: list[UploadEntry] = []
49
+ self._stop_flag = threading.Event()
50
+ self._config_logged = False
51
+
52
+ self._client_thread = threading.Thread(target=self._init_client_background)
53
+ self._client_thread.daemon = True
54
+ self._client_thread.start()
55
+
56
+ def _get_username(self) -> str | None:
57
+ """Get the current HuggingFace username if logged in, otherwise None."""
58
+ try:
59
+ who = huggingface_hub.whoami()
60
+ return who["name"] if who else None
61
+ except Exception:
62
+ return None
63
+
64
+ def _batch_sender(self):
65
+ """Send batched logs every BATCH_SEND_INTERVAL."""
66
+ while not self._stop_flag.is_set() or len(self._queued_logs) > 0:
67
+ # If the stop flag has been set, then just quickly send all
68
+ # the logs and exit.
69
+ if not self._stop_flag.is_set():
70
+ time.sleep(BATCH_SEND_INTERVAL)
71
+
72
+ with self._client_lock:
73
+ if self._client is None:
74
+ return
75
+ if self._queued_logs:
76
+ logs_to_send = self._queued_logs.copy()
77
+ self._queued_logs.clear()
78
+ self._client.predict(
79
+ api_name="/bulk_log",
80
+ logs=logs_to_send,
81
+ hf_token=huggingface_hub.utils.get_token(),
82
+ )
83
+ if self._queued_uploads:
84
+ uploads_to_send = self._queued_uploads.copy()
85
+ self._queued_uploads.clear()
86
+ self._client.predict(
87
+ api_name="/bulk_upload_media",
88
+ uploads=uploads_to_send,
89
+ hf_token=huggingface_hub.utils.get_token(),
90
+ )
91
+
92
+ def _init_client_background(self):
93
+ if self._client is None:
94
+ fib = utils.fibo()
95
+ for sleep_coefficient in fib:
96
+ try:
97
+ client = Client(self.url, verbose=False)
98
+
99
+ with self._client_lock:
100
+ self._client = client
101
+ break
102
+ except Exception:
103
+ pass
104
+ if sleep_coefficient is not None:
105
+ time.sleep(0.1 * sleep_coefficient)
106
+
107
+ self._batch_sender()
108
+
109
+ def _process_media(self, metrics, step: int | None) -> dict:
110
+ """
111
+ Serialize media in metrics and upload to space if needed.
112
+ """
113
+ serializable_metrics = {}
114
+ if not step:
115
+ step = 0
116
+ for key, value in metrics.items():
117
+ if isinstance(value, TrackioMedia):
118
+ value._save(self.project, self.name, step)
119
+ serializable_metrics[key] = value._to_dict()
120
+ if self._space_id:
121
+ # Upload local media when deploying to space
122
+ upload_entry: UploadEntry = {
123
+ "project": self.project,
124
+ "run": self.name,
125
+ "step": step,
126
+ "uploaded_file": handle_file(value._get_absolute_file_path()),
127
+ }
128
+ with self._client_lock:
129
+ self._queued_uploads.append(upload_entry)
130
+ else:
131
+ serializable_metrics[key] = value
132
+ return serializable_metrics
133
+
134
+ @staticmethod
135
+ def _replace_tables(metrics):
136
+ for k, v in metrics.items():
137
+ if isinstance(v, Table):
138
+ metrics[k] = v._to_dict()
139
+
140
+ def log(self, metrics: dict, step: int | None = None):
141
+ for k in metrics.keys():
142
+ if k in utils.RESERVED_KEYS or k.startswith("__"):
143
+ raise ValueError(
144
+ f"Please do not use this reserved key as a metric: {k}"
145
+ )
146
+ Run._replace_tables(metrics)
147
+
148
+ metrics = self._process_media(metrics, step)
149
+ metrics = utils.serialize_values(metrics)
150
+
151
+ config_to_log = None
152
+ if not self._config_logged and self.config:
153
+ config_to_log = utils.to_json_safe(self.config)
154
+ self._config_logged = True
155
+
156
+ log_entry: LogEntry = {
157
+ "project": self.project,
158
+ "run": self.name,
159
+ "metrics": metrics,
160
+ "step": step,
161
+ "config": config_to_log,
162
+ }
163
+
164
+ with self._client_lock:
165
+ self._queued_logs.append(log_entry)
166
+
167
+ def finish(self):
168
+ """Cleanup when run is finished."""
169
+ self._stop_flag.set()
170
+
171
+ # Wait for the batch sender to finish before joining the client thread.
172
+ time.sleep(2 * BATCH_SEND_INTERVAL)
173
+
174
+ if self._client_thread is not None:
175
+ print("* Run finished. Uploading logs to Trackio (please wait...)")
176
+ self._client_thread.join()
sqlite_storage.py ADDED
@@ -0,0 +1,559 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ CREATE TABLE IF NOT EXISTS configs (
114
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
115
+ run_name TEXT NOT NULL,
116
+ config TEXT NOT NULL,
117
+ created_at TEXT NOT NULL,
118
+ UNIQUE(run_name)
119
+ )
120
+ """)
121
+ cursor.execute(
122
+ """
123
+ CREATE INDEX IF NOT EXISTS idx_metrics_run_step
124
+ ON metrics(run_name, step)
125
+ """
126
+ )
127
+ cursor.execute(
128
+ """
129
+ CREATE INDEX IF NOT EXISTS idx_configs_run_name
130
+ ON configs(run_name)
131
+ """
132
+ )
133
+ conn.commit()
134
+ return db_path
135
+
136
+ @staticmethod
137
+ def export_to_parquet():
138
+ """
139
+ Exports all projects' DB files as Parquet under the same path but with extension ".parquet".
140
+ """
141
+ # don't attempt to export (potentially wrong/blank) data before importing for the first time
142
+ if not SQLiteStorage._dataset_import_attempted:
143
+ return
144
+ all_paths = os.listdir(TRACKIO_DIR)
145
+ db_paths = [f for f in all_paths if f.endswith(".db")]
146
+ for db_path in db_paths:
147
+ db_path = TRACKIO_DIR / db_path
148
+ parquet_path = db_path.with_suffix(".parquet")
149
+ if (not parquet_path.exists()) or (
150
+ db_path.stat().st_mtime > parquet_path.stat().st_mtime
151
+ ):
152
+ with sqlite3.connect(db_path) as conn:
153
+ df = pd.read_sql("SELECT * from metrics", conn)
154
+ # break out the single JSON metrics column into individual columns
155
+ metrics = df["metrics"].copy()
156
+ metrics = pd.DataFrame(
157
+ metrics.apply(
158
+ lambda x: deserialize_values(json.loads(x))
159
+ ).values.tolist(),
160
+ index=df.index,
161
+ )
162
+ del df["metrics"]
163
+ for col in metrics.columns:
164
+ df[col] = metrics[col]
165
+ df.to_parquet(parquet_path)
166
+
167
+ @staticmethod
168
+ def import_from_parquet():
169
+ """
170
+ Imports to all DB files that have matching files under the same path but with extension ".parquet".
171
+ """
172
+ all_paths = os.listdir(TRACKIO_DIR)
173
+ parquet_paths = [f for f in all_paths if f.endswith(".parquet")]
174
+ for parquet_path in parquet_paths:
175
+ parquet_path = TRACKIO_DIR / parquet_path
176
+ db_path = parquet_path.with_suffix(".db")
177
+ df = pd.read_parquet(parquet_path)
178
+ with sqlite3.connect(db_path) as conn:
179
+ # fix up df to have a single JSON metrics column
180
+ if "metrics" not in df.columns:
181
+ # separate other columns from metrics
182
+ metrics = df.copy()
183
+ other_cols = ["id", "timestamp", "run_name", "step"]
184
+ df = df[other_cols]
185
+ for col in other_cols:
186
+ del metrics[col]
187
+ # combine them all into a single metrics col
188
+ metrics = json.loads(metrics.to_json(orient="records"))
189
+ df["metrics"] = [
190
+ json.dumps(serialize_values(row)) for row in metrics
191
+ ]
192
+ df.to_sql("metrics", conn, if_exists="replace", index=False)
193
+
194
+ @staticmethod
195
+ def get_scheduler():
196
+ """
197
+ Get the scheduler for the database based on the environment variables.
198
+ This applies to both local and Spaces.
199
+ """
200
+ with SQLiteStorage._scheduler_lock:
201
+ if SQLiteStorage._current_scheduler is not None:
202
+ return SQLiteStorage._current_scheduler
203
+ hf_token = os.environ.get("HF_TOKEN")
204
+ dataset_id = os.environ.get("TRACKIO_DATASET_ID")
205
+ space_repo_name = os.environ.get("SPACE_REPO_NAME")
206
+ if dataset_id is None or space_repo_name is None:
207
+ scheduler = DummyCommitScheduler()
208
+ else:
209
+ scheduler = CommitScheduler(
210
+ repo_id=dataset_id,
211
+ repo_type="dataset",
212
+ folder_path=TRACKIO_DIR,
213
+ private=True,
214
+ allow_patterns=["*.parquet", "media/**/*"],
215
+ squash_history=True,
216
+ token=hf_token,
217
+ on_before_commit=SQLiteStorage.export_to_parquet,
218
+ )
219
+ SQLiteStorage._current_scheduler = scheduler
220
+ return scheduler
221
+
222
+ @staticmethod
223
+ def log(project: str, run: str, metrics: dict, step: int | None = None):
224
+ """
225
+ Safely log metrics to the database. Before logging, this method will ensure the database exists
226
+ and is set up with the correct tables. It also uses a cross-process lock to prevent
227
+ database locking errors when multiple processes access the same database.
228
+
229
+ This method is not used in the latest versions of Trackio (replaced by bulk_log) but
230
+ is kept for backwards compatibility for users who are connecting to a newer version of
231
+ a Trackio Spaces dashboard with an older version of Trackio installed locally.
232
+ """
233
+ db_path = SQLiteStorage.init_db(project)
234
+
235
+ with SQLiteStorage._get_process_lock(project):
236
+ with SQLiteStorage._get_connection(db_path) as conn:
237
+ cursor = conn.cursor()
238
+
239
+ cursor.execute(
240
+ """
241
+ SELECT MAX(step)
242
+ FROM metrics
243
+ WHERE run_name = ?
244
+ """,
245
+ (run,),
246
+ )
247
+ last_step = cursor.fetchone()[0]
248
+ if step is None:
249
+ current_step = 0 if last_step is None else last_step + 1
250
+ else:
251
+ current_step = step
252
+
253
+ current_timestamp = datetime.now().isoformat()
254
+
255
+ cursor.execute(
256
+ """
257
+ INSERT INTO metrics
258
+ (timestamp, run_name, step, metrics)
259
+ VALUES (?, ?, ?, ?)
260
+ """,
261
+ (
262
+ current_timestamp,
263
+ run,
264
+ current_step,
265
+ json.dumps(serialize_values(metrics)),
266
+ ),
267
+ )
268
+ conn.commit()
269
+
270
+ @staticmethod
271
+ def bulk_log(
272
+ project: str,
273
+ run: str,
274
+ metrics_list: list[dict],
275
+ steps: list[int] | None = None,
276
+ timestamps: list[str] | None = None,
277
+ config: dict | None = None,
278
+ ):
279
+ """
280
+ Safely log bulk metrics to the database. Before logging, this method will ensure the database exists
281
+ and is set up with the correct tables. It also uses a cross-process lock to prevent
282
+ database locking errors when multiple processes access the same database.
283
+ """
284
+ if not metrics_list:
285
+ return
286
+
287
+ if timestamps is None:
288
+ timestamps = [datetime.now().isoformat()] * len(metrics_list)
289
+
290
+ db_path = SQLiteStorage.init_db(project)
291
+ with SQLiteStorage._get_process_lock(project):
292
+ with SQLiteStorage._get_connection(db_path) as conn:
293
+ cursor = conn.cursor()
294
+
295
+ if steps is None:
296
+ steps = list(range(len(metrics_list)))
297
+ elif any(s is None for s in steps):
298
+ cursor.execute(
299
+ "SELECT MAX(step) FROM metrics WHERE run_name = ?", (run,)
300
+ )
301
+ last_step = cursor.fetchone()[0]
302
+ current_step = 0 if last_step is None else last_step + 1
303
+
304
+ processed_steps = []
305
+ for step in steps:
306
+ if step is None:
307
+ processed_steps.append(current_step)
308
+ current_step += 1
309
+ else:
310
+ processed_steps.append(step)
311
+ steps = processed_steps
312
+
313
+ if len(metrics_list) != len(steps) or len(metrics_list) != len(
314
+ timestamps
315
+ ):
316
+ raise ValueError(
317
+ "metrics_list, steps, and timestamps must have the same length"
318
+ )
319
+
320
+ data = []
321
+ for i, metrics in enumerate(metrics_list):
322
+ data.append(
323
+ (
324
+ timestamps[i],
325
+ run,
326
+ steps[i],
327
+ json.dumps(serialize_values(metrics)),
328
+ )
329
+ )
330
+
331
+ cursor.executemany(
332
+ """
333
+ INSERT INTO metrics
334
+ (timestamp, run_name, step, metrics)
335
+ VALUES (?, ?, ?, ?)
336
+ """,
337
+ data,
338
+ )
339
+
340
+ if config:
341
+ current_timestamp = datetime.now().isoformat()
342
+ cursor.execute(
343
+ """
344
+ INSERT OR REPLACE INTO configs
345
+ (run_name, config, created_at)
346
+ VALUES (?, ?, ?)
347
+ """,
348
+ (run, json.dumps(serialize_values(config)), current_timestamp),
349
+ )
350
+
351
+ conn.commit()
352
+
353
+ @staticmethod
354
+ def get_logs(project: str, run: str) -> list[dict]:
355
+ """Retrieve logs for a specific run. Logs include the step count (int) and the timestamp (datetime object)."""
356
+ db_path = SQLiteStorage.get_project_db_path(project)
357
+ if not db_path.exists():
358
+ return []
359
+
360
+ with SQLiteStorage._get_connection(db_path) as conn:
361
+ cursor = conn.cursor()
362
+ cursor.execute(
363
+ """
364
+ SELECT timestamp, step, metrics
365
+ FROM metrics
366
+ WHERE run_name = ?
367
+ ORDER BY timestamp
368
+ """,
369
+ (run,),
370
+ )
371
+
372
+ rows = cursor.fetchall()
373
+ results = []
374
+ for row in rows:
375
+ metrics = json.loads(row["metrics"])
376
+ metrics = deserialize_values(metrics)
377
+ metrics["timestamp"] = row["timestamp"]
378
+ metrics["step"] = row["step"]
379
+ results.append(metrics)
380
+ return results
381
+
382
+ @staticmethod
383
+ def load_from_dataset():
384
+ dataset_id = os.environ.get("TRACKIO_DATASET_ID")
385
+ space_repo_name = os.environ.get("SPACE_REPO_NAME")
386
+ if dataset_id is not None and space_repo_name is not None:
387
+ hfapi = hf.HfApi()
388
+ updated = False
389
+ if not TRACKIO_DIR.exists():
390
+ TRACKIO_DIR.mkdir(parents=True, exist_ok=True)
391
+ with SQLiteStorage.get_scheduler().lock:
392
+ try:
393
+ files = hfapi.list_repo_files(dataset_id, repo_type="dataset")
394
+ for file in files:
395
+ # Download parquet and media assets
396
+ if not (file.endswith(".parquet") or file.startswith("media/")):
397
+ continue
398
+ if (TRACKIO_DIR / file).exists():
399
+ continue
400
+ hf.hf_hub_download(
401
+ dataset_id, file, repo_type="dataset", local_dir=TRACKIO_DIR
402
+ )
403
+ updated = True
404
+ except hf.errors.EntryNotFoundError:
405
+ pass
406
+ except hf.errors.RepositoryNotFoundError:
407
+ pass
408
+ if updated:
409
+ SQLiteStorage.import_from_parquet()
410
+ SQLiteStorage._dataset_import_attempted = True
411
+
412
+ @staticmethod
413
+ def get_projects() -> list[str]:
414
+ """
415
+ Get list of all projects by scanning the database files in the trackio directory.
416
+ """
417
+ if not SQLiteStorage._dataset_import_attempted:
418
+ SQLiteStorage.load_from_dataset()
419
+
420
+ projects: set[str] = set()
421
+ if not TRACKIO_DIR.exists():
422
+ return []
423
+
424
+ for db_file in TRACKIO_DIR.glob("*.db"):
425
+ project_name = db_file.stem
426
+ projects.add(project_name)
427
+ return sorted(projects)
428
+
429
+ @staticmethod
430
+ def get_runs(project: str) -> list[str]:
431
+ """Get list of all runs for a project."""
432
+ db_path = SQLiteStorage.get_project_db_path(project)
433
+ if not db_path.exists():
434
+ return []
435
+
436
+ with SQLiteStorage._get_connection(db_path) as conn:
437
+ cursor = conn.cursor()
438
+ cursor.execute(
439
+ "SELECT DISTINCT run_name FROM metrics",
440
+ )
441
+ return [row[0] for row in cursor.fetchall()]
442
+
443
+ @staticmethod
444
+ def get_max_steps_for_runs(project: str) -> dict[str, int]:
445
+ """Get the maximum step for each run in a project."""
446
+ db_path = SQLiteStorage.get_project_db_path(project)
447
+ if not db_path.exists():
448
+ return {}
449
+
450
+ with SQLiteStorage._get_connection(db_path) as conn:
451
+ cursor = conn.cursor()
452
+ cursor.execute(
453
+ """
454
+ SELECT run_name, MAX(step) as max_step
455
+ FROM metrics
456
+ GROUP BY run_name
457
+ """
458
+ )
459
+
460
+ results = {}
461
+ for row in cursor.fetchall():
462
+ results[row["run_name"]] = row["max_step"]
463
+
464
+ return results
465
+
466
+ @staticmethod
467
+ def store_config(project: str, run: str, config: dict) -> None:
468
+ """Store configuration for a run."""
469
+ db_path = SQLiteStorage.init_db(project)
470
+
471
+ with SQLiteStorage._get_process_lock(project):
472
+ with SQLiteStorage._get_connection(db_path) as conn:
473
+ cursor = conn.cursor()
474
+ current_timestamp = datetime.now().isoformat()
475
+
476
+ cursor.execute(
477
+ """
478
+ INSERT OR REPLACE INTO configs
479
+ (run_name, config, created_at)
480
+ VALUES (?, ?, ?)
481
+ """,
482
+ (run, json.dumps(serialize_values(config)), current_timestamp),
483
+ )
484
+ conn.commit()
485
+
486
+ @staticmethod
487
+ def get_run_config(project: str, run: str) -> dict | None:
488
+ """Get configuration for a specific run."""
489
+ db_path = SQLiteStorage.get_project_db_path(project)
490
+ if not db_path.exists():
491
+ return None
492
+
493
+ with SQLiteStorage._get_connection(db_path) as conn:
494
+ cursor = conn.cursor()
495
+ try:
496
+ cursor.execute(
497
+ """
498
+ SELECT config FROM configs WHERE run_name = ?
499
+ """,
500
+ (run,),
501
+ )
502
+
503
+ row = cursor.fetchone()
504
+ if row:
505
+ config = json.loads(row["config"])
506
+ return deserialize_values(config)
507
+ return None
508
+ except sqlite3.OperationalError as e:
509
+ if "no such table: configs" in str(e):
510
+ return None
511
+ raise
512
+
513
+ @staticmethod
514
+ def delete_run(project: str, run: str) -> bool:
515
+ """Delete a run from the database (both metrics and config)."""
516
+ db_path = SQLiteStorage.get_project_db_path(project)
517
+ if not db_path.exists():
518
+ return False
519
+
520
+ with SQLiteStorage._get_process_lock(project):
521
+ with SQLiteStorage._get_connection(db_path) as conn:
522
+ cursor = conn.cursor()
523
+ try:
524
+ cursor.execute("DELETE FROM metrics WHERE run_name = ?", (run,))
525
+ cursor.execute("DELETE FROM configs WHERE run_name = ?", (run,))
526
+ conn.commit()
527
+ return True
528
+ except sqlite3.Error:
529
+ return False
530
+
531
+ @staticmethod
532
+ def get_all_run_configs(project: str) -> dict[str, dict]:
533
+ """Get configurations for all runs in a project."""
534
+ db_path = SQLiteStorage.get_project_db_path(project)
535
+ if not db_path.exists():
536
+ return {}
537
+
538
+ with SQLiteStorage._get_connection(db_path) as conn:
539
+ cursor = conn.cursor()
540
+ try:
541
+ cursor.execute(
542
+ """
543
+ SELECT run_name, config FROM configs
544
+ """
545
+ )
546
+
547
+ results = {}
548
+ for row in cursor.fetchall():
549
+ config = json.loads(row["config"])
550
+ results[row["run_name"]] = deserialize_values(config)
551
+ return results
552
+ except sqlite3.OperationalError as e:
553
+ if "no such table: configs" in str(e):
554
+ return {}
555
+ raise
556
+
557
+ def finish(self):
558
+ """Cleanup when run is finished."""
559
+ pass
table.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Literal
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*):
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*):
15
+ 2D row-oriented array of values.
16
+ dataframe (`pandas.`DataFrame``, *optional*):
17
+ DataFrame object used to create the table. When set, `data` and `columns`
18
+ arguments are ignored.
19
+ rows (`list[list[any]]`, *optional*):
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: list[str] | None = None,
34
+ data: list[list[Any]] | None = None,
35
+ dataframe: DataFrame | None = None,
36
+ rows: list[list[Any]] | None = None,
37
+ optional: bool | list[bool] = True,
38
+ allow_mixed_types: bool = False,
39
+ log_mode: Literal["IMMUTABLE", "MUTABLE", "INCREMENTAL"] | None = "IMMUTABLE",
40
+ ):
41
+ # TODO: implement support for columns, dtype, optional, allow_mixed_types, and log_mode.
42
+ # for now (like `rows`) they are included for API compat but don't do anything.
43
+
44
+ if dataframe is None:
45
+ self.data = data
46
+ else:
47
+ self.data = dataframe.to_dict(orient="records")
48
+
49
+ def _to_dict(self):
50
+ return {
51
+ "_type": self.TYPE,
52
+ "_value": self.data,
53
+ }
typehints.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ config: dict[str, Any] | None
12
+
13
+
14
+ class UploadEntry(TypedDict):
15
+ project: str
16
+ run: str
17
+ step: int | None
18
+ uploaded_file: FileData
ui/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ try:
2
+ from trackio.ui.main import demo
3
+ from trackio.ui.run_detail import run_detail_page
4
+ from trackio.ui.runs import run_page
5
+ except ImportError:
6
+ from ui.main import demo
7
+ from ui.run_detail import run_detail_page
8
+ from ui.runs import run_page
9
+
10
+ __all__ = ["demo", "run_page", "run_detail_page"]
ui/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (507 Bytes). View file
 
ui/__pycache__/fns.cpython-312.pyc ADDED
Binary file (3.16 kB). View file
 
ui/__pycache__/main.cpython-312.pyc ADDED
Binary file (35.7 kB). View file
 
ui/__pycache__/run_detail.cpython-312.pyc ADDED
Binary file (4.04 kB). View file
 
ui/__pycache__/runs.cpython-312.pyc ADDED
Binary file (10.6 kB). View file
 
ui/fns.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared functions for the Trackio UI."""
2
+
3
+ import os
4
+
5
+ import gradio as gr
6
+
7
+ try:
8
+ import trackio.utils as utils
9
+ from trackio.sqlite_storage import SQLiteStorage
10
+ except ImportError:
11
+ import utils
12
+ from sqlite_storage import SQLiteStorage
13
+
14
+
15
+ def get_project_info() -> str | None:
16
+ dataset_id = os.environ.get("TRACKIO_DATASET_ID")
17
+ space_id = os.environ.get("SPACE_ID")
18
+ if utils.persistent_storage_enabled():
19
+ return "&#10024; Persistent Storage is enabled, logs are stored directly in this Space."
20
+ if dataset_id:
21
+ sync_status = utils.get_sync_status(SQLiteStorage.get_scheduler())
22
+ 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>"
23
+ if sync_status is not None:
24
+ 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}"
25
+ else:
26
+ 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}"
27
+ return info
28
+ return None
29
+
30
+
31
+ def get_projects(request: gr.Request):
32
+ projects = SQLiteStorage.get_projects()
33
+ if project := request.query_params.get("project"):
34
+ interactive = False
35
+ else:
36
+ interactive = True
37
+ if selected_project := request.query_params.get("selected_project"):
38
+ project = selected_project
39
+ else:
40
+ project = projects[0] if projects else None
41
+
42
+ return gr.Dropdown(
43
+ label="Project",
44
+ choices=projects,
45
+ value=project,
46
+ allow_custom_value=True,
47
+ interactive=interactive,
48
+ info=get_project_info(),
49
+ )
50
+
51
+
52
+ def update_navbar_value(project_dd):
53
+ return gr.Navbar(
54
+ value=[
55
+ ("Metrics", f"?selected_project={project_dd}"),
56
+ ("Runs", f"runs?selected_project={project_dd}"),
57
+ ]
58
+ )
ui/main.py ADDED
@@ -0,0 +1,943 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The main page for the Trackio UI."""
2
+
3
+ import os
4
+ import re
5
+ import secrets
6
+ import shutil
7
+ from dataclasses import dataclass
8
+ from typing import Any
9
+
10
+ import gradio as gr
11
+ import huggingface_hub as hf
12
+ import numpy as np
13
+ import pandas as pd
14
+
15
+ HfApi = hf.HfApi()
16
+
17
+ try:
18
+ import trackio.utils as utils
19
+ from trackio.file_storage import FileStorage
20
+ from trackio.media import TrackioImage, TrackioVideo
21
+ from trackio.sqlite_storage import SQLiteStorage
22
+ from trackio.table import Table
23
+ from trackio.typehints import LogEntry, UploadEntry
24
+ from trackio.ui import fns
25
+ from trackio.ui.run_detail import run_detail_page
26
+ from trackio.ui.runs import run_page
27
+ except ImportError:
28
+ import utils
29
+ from file_storage import FileStorage
30
+ from media import TrackioImage, TrackioVideo
31
+ from sqlite_storage import SQLiteStorage
32
+ from table import Table
33
+ from typehints import LogEntry, UploadEntry
34
+ from ui import fns
35
+ from ui.run_detail import run_detail_page
36
+ from ui.runs import run_page
37
+
38
+
39
+ def get_runs(project) -> list[str]:
40
+ if not project:
41
+ return []
42
+ return SQLiteStorage.get_runs(project)
43
+
44
+
45
+ def get_available_metrics(project: str, runs: list[str]) -> list[str]:
46
+ """Get all available metrics across all runs for x-axis selection."""
47
+ if not project or not runs:
48
+ return ["step", "time"]
49
+
50
+ all_metrics = set()
51
+ for run in runs:
52
+ metrics = SQLiteStorage.get_logs(project, run)
53
+ if metrics:
54
+ df = pd.DataFrame(metrics)
55
+ numeric_cols = df.select_dtypes(include="number").columns
56
+ numeric_cols = [c for c in numeric_cols if c not in utils.RESERVED_KEYS]
57
+ all_metrics.update(numeric_cols)
58
+
59
+ all_metrics.add("step")
60
+ all_metrics.add("time")
61
+
62
+ sorted_metrics = utils.sort_metrics_by_prefix(list(all_metrics))
63
+
64
+ result = ["step", "time"]
65
+ for metric in sorted_metrics:
66
+ if metric not in result:
67
+ result.append(metric)
68
+
69
+ return result
70
+
71
+
72
+ @dataclass
73
+ class MediaData:
74
+ caption: str | None
75
+ file_path: str
76
+
77
+
78
+ def extract_media(logs: list[dict]) -> dict[str, list[MediaData]]:
79
+ media_by_key: dict[str, list[MediaData]] = {}
80
+ logs = sorted(logs, key=lambda x: x.get("step", 0))
81
+ for log in logs:
82
+ for key, value in log.items():
83
+ if isinstance(value, dict):
84
+ type = value.get("_type")
85
+ if type == TrackioImage.TYPE or type == TrackioVideo.TYPE:
86
+ if key not in media_by_key:
87
+ media_by_key[key] = []
88
+ try:
89
+ media_data = MediaData(
90
+ file_path=utils.MEDIA_DIR / value.get("file_path"),
91
+ caption=value.get("caption"),
92
+ )
93
+ media_by_key[key].append(media_data)
94
+ except Exception as e:
95
+ print(f"Media currently unavailable: {key}: {e}")
96
+ return media_by_key
97
+
98
+
99
+ def load_run_data(
100
+ project: str | None,
101
+ run: str | None,
102
+ smoothing_granularity: int,
103
+ x_axis: str,
104
+ log_scale: bool = False,
105
+ ) -> tuple[pd.DataFrame, dict]:
106
+ if not project or not run:
107
+ return None, None
108
+
109
+ logs = SQLiteStorage.get_logs(project, run)
110
+ if not logs:
111
+ return None, None
112
+
113
+ media = extract_media(logs)
114
+ df = pd.DataFrame(logs)
115
+
116
+ if "step" not in df.columns:
117
+ df["step"] = range(len(df))
118
+
119
+ if x_axis == "time" and "timestamp" in df.columns:
120
+ df["timestamp"] = pd.to_datetime(df["timestamp"])
121
+ first_timestamp = df["timestamp"].min()
122
+ df["time"] = (df["timestamp"] - first_timestamp).dt.total_seconds()
123
+ x_column = "time"
124
+ elif x_axis == "step":
125
+ x_column = "step"
126
+ else:
127
+ x_column = x_axis
128
+
129
+ if log_scale and x_column in df.columns:
130
+ x_vals = df[x_column]
131
+ if (x_vals <= 0).any():
132
+ df[x_column] = np.log10(np.maximum(x_vals, 0) + 1)
133
+ else:
134
+ df[x_column] = np.log10(x_vals)
135
+
136
+ if smoothing_granularity > 0:
137
+ numeric_cols = df.select_dtypes(include="number").columns
138
+ numeric_cols = [c for c in numeric_cols if c not in utils.RESERVED_KEYS]
139
+
140
+ df_original = df.copy()
141
+ df_original["run"] = run
142
+ df_original["data_type"] = "original"
143
+
144
+ df_smoothed = df.copy()
145
+ window_size = max(3, min(smoothing_granularity, len(df)))
146
+ df_smoothed[numeric_cols] = (
147
+ df_smoothed[numeric_cols]
148
+ .rolling(window=window_size, center=True, min_periods=1)
149
+ .mean()
150
+ )
151
+ df_smoothed["run"] = f"{run}_smoothed"
152
+ df_smoothed["data_type"] = "smoothed"
153
+
154
+ combined_df = pd.concat([df_original, df_smoothed], ignore_index=True)
155
+ combined_df["x_axis"] = x_column
156
+ return combined_df, media
157
+ else:
158
+ df["run"] = run
159
+ df["data_type"] = "original"
160
+ df["x_axis"] = x_column
161
+ return df, media
162
+
163
+
164
+ def update_runs(
165
+ project, filter_text, user_interacted_with_runs=False, selected_runs_from_url=None
166
+ ):
167
+ if project is None:
168
+ runs = []
169
+ num_runs = 0
170
+ else:
171
+ runs = get_runs(project)
172
+ num_runs = len(runs)
173
+ if filter_text:
174
+ runs = [r for r in runs if filter_text in r]
175
+
176
+ if not user_interacted_with_runs:
177
+ if selected_runs_from_url:
178
+ value = [r for r in runs if r in selected_runs_from_url]
179
+ else:
180
+ value = runs
181
+ return gr.CheckboxGroup(choices=runs, value=value), gr.Textbox(
182
+ label=f"Runs ({num_runs})"
183
+ )
184
+ else:
185
+ return gr.CheckboxGroup(choices=runs), gr.Textbox(label=f"Runs ({num_runs})")
186
+
187
+
188
+ def filter_runs(project, filter_text):
189
+ runs = get_runs(project)
190
+ runs = [r for r in runs if filter_text in r]
191
+ return gr.CheckboxGroup(choices=runs, value=runs)
192
+
193
+
194
+ def update_x_axis_choices(project, runs):
195
+ """Update x-axis dropdown choices based on available metrics."""
196
+ available_metrics = get_available_metrics(project, runs)
197
+ return gr.Dropdown(
198
+ label="X-axis",
199
+ choices=available_metrics,
200
+ value="step",
201
+ )
202
+
203
+
204
+ def toggle_timer(cb_value):
205
+ if cb_value:
206
+ return gr.Timer(active=True)
207
+ else:
208
+ return gr.Timer(active=False)
209
+
210
+
211
+ def check_auth(hf_token: str | None) -> None:
212
+ if os.getenv("SYSTEM") == "spaces": # if we are running in Spaces
213
+ # check auth token passed in
214
+ if hf_token is None:
215
+ raise PermissionError(
216
+ "Expected a HF_TOKEN to be provided when logging to a Space"
217
+ )
218
+ who = HfApi.whoami(hf_token)
219
+ access_token = who["auth"]["accessToken"]
220
+ owner_name = os.getenv("SPACE_AUTHOR_NAME")
221
+ repo_name = os.getenv("SPACE_REPO_NAME")
222
+ # make sure the token user is either the author of the space,
223
+ # or is a member of an org that is the author.
224
+ orgs = [o["name"] for o in who["orgs"]]
225
+ if owner_name != who["name"] and owner_name not in orgs:
226
+ raise PermissionError(
227
+ "Expected the provided hf_token to be the user owner of the space, or be a member of the org owner of the space"
228
+ )
229
+ # reject fine-grained tokens without specific repo access
230
+ if access_token["role"] == "fineGrained":
231
+ matched = False
232
+ for item in access_token["fineGrained"]["scoped"]:
233
+ if (
234
+ item["entity"]["type"] == "space"
235
+ and item["entity"]["name"] == f"{owner_name}/{repo_name}"
236
+ and "repo.write" in item["permissions"]
237
+ ):
238
+ matched = True
239
+ break
240
+ if (
241
+ (
242
+ item["entity"]["type"] == "user"
243
+ or item["entity"]["type"] == "org"
244
+ )
245
+ and item["entity"]["name"] == owner_name
246
+ and "repo.write" in item["permissions"]
247
+ ):
248
+ matched = True
249
+ break
250
+ if not matched:
251
+ raise PermissionError(
252
+ "Expected the provided hf_token with fine grained permissions to provide write access to the space"
253
+ )
254
+ # reject read-only tokens
255
+ elif access_token["role"] != "write":
256
+ raise PermissionError(
257
+ "Expected the provided hf_token to provide write permissions"
258
+ )
259
+
260
+
261
+ def upload_db_to_space(
262
+ project: str, uploaded_db: gr.FileData, hf_token: str | None
263
+ ) -> None:
264
+ check_auth(hf_token)
265
+ db_project_path = SQLiteStorage.get_project_db_path(project)
266
+ if os.path.exists(db_project_path):
267
+ raise gr.Error(
268
+ f"Trackio database file already exists for project {project}, cannot overwrite."
269
+ )
270
+ os.makedirs(os.path.dirname(db_project_path), exist_ok=True)
271
+ shutil.copy(uploaded_db["path"], db_project_path)
272
+
273
+
274
+ def bulk_upload_media(uploads: list[UploadEntry], hf_token: str | None) -> None:
275
+ check_auth(hf_token)
276
+ for upload in uploads:
277
+ media_path = FileStorage.init_project_media_path(
278
+ upload["project"], upload["run"], upload["step"]
279
+ )
280
+ shutil.copy(upload["uploaded_file"]["path"], media_path)
281
+
282
+
283
+ def log(
284
+ project: str,
285
+ run: str,
286
+ metrics: dict[str, Any],
287
+ step: int | None,
288
+ hf_token: str | None,
289
+ ) -> None:
290
+ """
291
+ Note: this method is not used in the latest versions of Trackio (replaced by bulk_log) but
292
+ is kept for backwards compatibility for users who are connecting to a newer version of
293
+ a Trackio Spaces dashboard with an older version of Trackio installed locally.
294
+ """
295
+ check_auth(hf_token)
296
+ SQLiteStorage.log(project=project, run=run, metrics=metrics, step=step)
297
+
298
+
299
+ def bulk_log(
300
+ logs: list[LogEntry],
301
+ hf_token: str | None,
302
+ ) -> None:
303
+ check_auth(hf_token)
304
+
305
+ logs_by_run = {}
306
+ for log_entry in logs:
307
+ key = (log_entry["project"], log_entry["run"])
308
+ if key not in logs_by_run:
309
+ logs_by_run[key] = {"metrics": [], "steps": [], "config": None}
310
+ logs_by_run[key]["metrics"].append(log_entry["metrics"])
311
+ logs_by_run[key]["steps"].append(log_entry.get("step"))
312
+ if log_entry.get("config") and logs_by_run[key]["config"] is None:
313
+ logs_by_run[key]["config"] = log_entry["config"]
314
+
315
+ for (project, run), data in logs_by_run.items():
316
+ SQLiteStorage.bulk_log(
317
+ project=project,
318
+ run=run,
319
+ metrics_list=data["metrics"],
320
+ steps=data["steps"],
321
+ config=data["config"],
322
+ )
323
+
324
+
325
+ def filter_metrics_by_regex(metrics: list[str], filter_pattern: str) -> list[str]:
326
+ """
327
+ Filter metrics using regex pattern.
328
+
329
+ Args:
330
+ metrics: List of metric names to filter
331
+ filter_pattern: Regex pattern to match against metric names
332
+
333
+ Returns:
334
+ List of metric names that match the pattern
335
+ """
336
+ if not filter_pattern.strip():
337
+ return metrics
338
+
339
+ try:
340
+ pattern = re.compile(filter_pattern, re.IGNORECASE)
341
+ return [metric for metric in metrics if pattern.search(metric)]
342
+ except re.error:
343
+ return [
344
+ metric for metric in metrics if filter_pattern.lower() in metric.lower()
345
+ ]
346
+
347
+
348
+ def configure(request: gr.Request):
349
+ sidebar_param = request.query_params.get("sidebar")
350
+ match sidebar_param:
351
+ case "collapsed":
352
+ sidebar = gr.Sidebar(open=False, visible=True)
353
+ case "hidden":
354
+ sidebar = gr.Sidebar(open=False, visible=False)
355
+ case _:
356
+ sidebar = gr.Sidebar(open=True, visible=True)
357
+
358
+ metrics_param = request.query_params.get("metrics", "")
359
+ runs_param = request.query_params.get("runs", "")
360
+ selected_runs = runs_param.split(",") if runs_param else []
361
+ navbar_param = request.query_params.get("navbar")
362
+ match navbar_param:
363
+ case "hidden":
364
+ navbar = gr.Navbar(visible=False)
365
+ case _:
366
+ navbar = gr.Navbar(visible=True)
367
+
368
+ return [], sidebar, metrics_param, selected_runs, navbar
369
+
370
+
371
+ def create_media_section(media_by_run: dict[str, dict[str, list[MediaData]]]):
372
+ with gr.Accordion(label="media"):
373
+ with gr.Group(elem_classes=("media-group")):
374
+ for run, media_by_key in media_by_run.items():
375
+ with gr.Tab(label=run, elem_classes=("media-tab")):
376
+ for key, media_item in media_by_key.items():
377
+ gr.Gallery(
378
+ [(item.file_path, item.caption) for item in media_item],
379
+ label=key,
380
+ columns=6,
381
+ elem_classes=("media-gallery"),
382
+ )
383
+
384
+
385
+ css = """
386
+ #run-cb .wrap { gap: 2px; }
387
+ #run-cb .wrap label {
388
+ line-height: 1;
389
+ padding: 6px;
390
+ }
391
+ .logo-light { display: block; }
392
+ .logo-dark { display: none; }
393
+ .dark .logo-light { display: none; }
394
+ .dark .logo-dark { display: block; }
395
+ .dark .caption-label { color: white; }
396
+
397
+ .info-container {
398
+ position: relative;
399
+ display: inline;
400
+ }
401
+ .info-checkbox {
402
+ position: absolute;
403
+ opacity: 0;
404
+ pointer-events: none;
405
+ }
406
+ .info-icon {
407
+ border-bottom: 1px dotted;
408
+ cursor: pointer;
409
+ user-select: none;
410
+ color: var(--color-accent);
411
+ }
412
+ .info-expandable {
413
+ display: none;
414
+ opacity: 0;
415
+ transition: opacity 0.2s ease-in-out;
416
+ }
417
+ .info-checkbox:checked ~ .info-expandable {
418
+ display: inline;
419
+ opacity: 1;
420
+ }
421
+ .info-icon:hover { opacity: 0.8; }
422
+ .accent-link { font-weight: bold; }
423
+
424
+ .media-gallery .fixed-height { min-height: 275px; }
425
+ .media-group, .media-group > div { background: none; }
426
+ .media-group .tabs { padding: 0.5em; }
427
+ .media-tab { max-height: 500px; overflow-y: scroll; }
428
+ """
429
+
430
+ javascript = """
431
+ <script>
432
+ function setCookie(name, value, days) {
433
+ var expires = "";
434
+ if (days) {
435
+ var date = new Date();
436
+ date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
437
+ expires = "; expires=" + date.toUTCString();
438
+ }
439
+ document.cookie = name + "=" + (value || "") + expires + "; path=/; SameSite=Lax";
440
+ }
441
+
442
+ function getCookie(name) {
443
+ var nameEQ = name + "=";
444
+ var ca = document.cookie.split(';');
445
+ for(var i=0;i < ca.length;i++) {
446
+ var c = ca[i];
447
+ while (c.charAt(0)==' ') c = c.substring(1,c.length);
448
+ if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
449
+ }
450
+ return null;
451
+ }
452
+
453
+ (function() {
454
+ const urlParams = new URLSearchParams(window.location.search);
455
+ const writeToken = urlParams.get('write_token');
456
+
457
+ if (writeToken) {
458
+ setCookie('trackio_write_token', writeToken, 7);
459
+
460
+ urlParams.delete('write_token');
461
+ const newUrl = window.location.pathname +
462
+ (urlParams.toString() ? '?' + urlParams.toString() : '') +
463
+ window.location.hash;
464
+ window.history.replaceState({}, document.title, newUrl);
465
+ }
466
+ })();
467
+ </script>
468
+ """
469
+
470
+
471
+ gr.set_static_paths(paths=[utils.MEDIA_DIR])
472
+
473
+ with gr.Blocks(title="Trackio Dashboard", css=css, head=javascript) as demo:
474
+ with gr.Sidebar(open=False) as sidebar:
475
+ logo = gr.Markdown(
476
+ f"""
477
+ <img src='/gradio_api/file={utils.TRACKIO_LOGO_DIR}/trackio_logo_type_light_transparent.png' width='80%' class='logo-light'>
478
+ <img src='/gradio_api/file={utils.TRACKIO_LOGO_DIR}/trackio_logo_type_dark_transparent.png' width='80%' class='logo-dark'>
479
+ """
480
+ )
481
+ project_dd = gr.Dropdown(label="Project", allow_custom_value=True)
482
+
483
+ embed_code = gr.Code(
484
+ label="Embed this view",
485
+ max_lines=2,
486
+ lines=2,
487
+ language="html",
488
+ visible=bool(os.environ.get("SPACE_HOST")),
489
+ )
490
+ run_tb = gr.Textbox(label="Runs", placeholder="Type to filter...")
491
+ run_cb = gr.CheckboxGroup(
492
+ label="Runs",
493
+ choices=[],
494
+ interactive=True,
495
+ elem_id="run-cb",
496
+ show_select_all=True,
497
+ )
498
+ gr.HTML("<hr>")
499
+ realtime_cb = gr.Checkbox(label="Refresh metrics realtime", value=True)
500
+ smoothing_slider = gr.Slider(
501
+ label="Smoothing Factor",
502
+ minimum=0,
503
+ maximum=20,
504
+ value=10,
505
+ step=1,
506
+ info="0 = no smoothing",
507
+ )
508
+ x_axis_dd = gr.Dropdown(
509
+ label="X-axis",
510
+ choices=["step", "time"],
511
+ value="step",
512
+ )
513
+ log_scale_cb = gr.Checkbox(label="Log scale X-axis", value=False)
514
+ metric_filter_tb = gr.Textbox(
515
+ label="Metric Filter (regex)",
516
+ placeholder="e.g., loss|ndcg@10|gpu",
517
+ value="",
518
+ info="Filter metrics using regex patterns. Leave empty to show all metrics.",
519
+ )
520
+
521
+ navbar = gr.Navbar(value=[("Metrics", ""), ("Runs", "/runs")], main_page_name=False)
522
+ timer = gr.Timer(value=1)
523
+ metrics_subset = gr.State([])
524
+ user_interacted_with_run_cb = gr.State(False)
525
+ selected_runs_from_url = gr.State([])
526
+
527
+ gr.on(
528
+ [demo.load],
529
+ fn=configure,
530
+ outputs=[
531
+ metrics_subset,
532
+ sidebar,
533
+ metric_filter_tb,
534
+ selected_runs_from_url,
535
+ navbar,
536
+ ],
537
+ queue=False,
538
+ api_name=False,
539
+ )
540
+ gr.on(
541
+ [demo.load],
542
+ fn=fns.get_projects,
543
+ outputs=project_dd,
544
+ show_progress="hidden",
545
+ queue=False,
546
+ api_name=False,
547
+ )
548
+ gr.on(
549
+ [timer.tick],
550
+ fn=update_runs,
551
+ inputs=[
552
+ project_dd,
553
+ run_tb,
554
+ user_interacted_with_run_cb,
555
+ selected_runs_from_url,
556
+ ],
557
+ outputs=[run_cb, run_tb],
558
+ show_progress="hidden",
559
+ api_name=False,
560
+ )
561
+ gr.on(
562
+ [timer.tick],
563
+ fn=lambda: gr.Dropdown(info=fns.get_project_info()),
564
+ outputs=[project_dd],
565
+ show_progress="hidden",
566
+ api_name=False,
567
+ )
568
+ gr.on(
569
+ [demo.load, project_dd.change],
570
+ fn=update_runs,
571
+ inputs=[project_dd, run_tb, gr.State(False), selected_runs_from_url],
572
+ outputs=[run_cb, run_tb],
573
+ show_progress="hidden",
574
+ queue=False,
575
+ api_name=False,
576
+ ).then(
577
+ fn=update_x_axis_choices,
578
+ inputs=[project_dd, run_cb],
579
+ outputs=x_axis_dd,
580
+ show_progress="hidden",
581
+ queue=False,
582
+ api_name=False,
583
+ ).then(
584
+ fn=utils.generate_embed_code,
585
+ inputs=[project_dd, metric_filter_tb, run_cb],
586
+ outputs=[embed_code],
587
+ show_progress="hidden",
588
+ api_name=False,
589
+ queue=False,
590
+ ).then(
591
+ fns.update_navbar_value,
592
+ inputs=[project_dd],
593
+ outputs=[navbar],
594
+ show_progress="hidden",
595
+ api_name=False,
596
+ queue=False,
597
+ )
598
+
599
+ gr.on(
600
+ [run_cb.input],
601
+ fn=update_x_axis_choices,
602
+ inputs=[project_dd, run_cb],
603
+ outputs=x_axis_dd,
604
+ show_progress="hidden",
605
+ queue=False,
606
+ api_name=False,
607
+ )
608
+ gr.on(
609
+ [metric_filter_tb.change, run_cb.change],
610
+ fn=utils.generate_embed_code,
611
+ inputs=[project_dd, metric_filter_tb, run_cb],
612
+ outputs=embed_code,
613
+ show_progress="hidden",
614
+ api_name=False,
615
+ queue=False,
616
+ )
617
+
618
+ realtime_cb.change(
619
+ fn=toggle_timer,
620
+ inputs=realtime_cb,
621
+ outputs=timer,
622
+ api_name=False,
623
+ queue=False,
624
+ )
625
+ run_cb.input(
626
+ fn=lambda: True,
627
+ outputs=user_interacted_with_run_cb,
628
+ api_name=False,
629
+ queue=False,
630
+ )
631
+ run_tb.input(
632
+ fn=filter_runs,
633
+ inputs=[project_dd, run_tb],
634
+ outputs=run_cb,
635
+ api_name=False,
636
+ queue=False,
637
+ )
638
+
639
+ gr.api(
640
+ fn=upload_db_to_space,
641
+ api_name="upload_db_to_space",
642
+ )
643
+ gr.api(
644
+ fn=bulk_upload_media,
645
+ api_name="bulk_upload_media",
646
+ )
647
+ gr.api(
648
+ fn=log,
649
+ api_name="log",
650
+ )
651
+ gr.api(
652
+ fn=bulk_log,
653
+ api_name="bulk_log",
654
+ )
655
+
656
+ x_lim = gr.State(None)
657
+ last_steps = gr.State({})
658
+
659
+ def update_x_lim(select_data: gr.SelectData):
660
+ return select_data.index
661
+
662
+ def update_last_steps(project):
663
+ """Check the last step for each run to detect when new data is available."""
664
+ if not project:
665
+ return {}
666
+ return SQLiteStorage.get_max_steps_for_runs(project)
667
+
668
+ timer.tick(
669
+ fn=update_last_steps,
670
+ inputs=[project_dd],
671
+ outputs=last_steps,
672
+ show_progress="hidden",
673
+ api_name=False,
674
+ )
675
+
676
+ @gr.render(
677
+ triggers=[
678
+ demo.load,
679
+ run_cb.change,
680
+ last_steps.change,
681
+ smoothing_slider.change,
682
+ x_lim.change,
683
+ x_axis_dd.change,
684
+ log_scale_cb.change,
685
+ metric_filter_tb.change,
686
+ ],
687
+ inputs=[
688
+ project_dd,
689
+ run_cb,
690
+ smoothing_slider,
691
+ metrics_subset,
692
+ x_lim,
693
+ x_axis_dd,
694
+ log_scale_cb,
695
+ metric_filter_tb,
696
+ ],
697
+ show_progress="hidden",
698
+ queue=False,
699
+ )
700
+ def update_dashboard(
701
+ project,
702
+ runs,
703
+ smoothing_granularity,
704
+ metrics_subset,
705
+ x_lim_value,
706
+ x_axis,
707
+ log_scale,
708
+ metric_filter,
709
+ ):
710
+ dfs = []
711
+ images_by_run = {}
712
+ original_runs = runs.copy()
713
+
714
+ for run in runs:
715
+ df, images_by_key = load_run_data(
716
+ project, run, smoothing_granularity, x_axis, log_scale
717
+ )
718
+ if df is not None:
719
+ dfs.append(df)
720
+ images_by_run[run] = images_by_key
721
+
722
+ if dfs:
723
+ if smoothing_granularity > 0:
724
+ original_dfs = []
725
+ smoothed_dfs = []
726
+ for df in dfs:
727
+ original_data = df[df["data_type"] == "original"]
728
+ smoothed_data = df[df["data_type"] == "smoothed"]
729
+ if not original_data.empty:
730
+ original_dfs.append(original_data)
731
+ if not smoothed_data.empty:
732
+ smoothed_dfs.append(smoothed_data)
733
+
734
+ all_dfs = original_dfs + smoothed_dfs
735
+ master_df = (
736
+ pd.concat(all_dfs, ignore_index=True) if all_dfs else pd.DataFrame()
737
+ )
738
+
739
+ else:
740
+ master_df = pd.concat(dfs, ignore_index=True)
741
+ else:
742
+ master_df = pd.DataFrame()
743
+
744
+ if master_df.empty:
745
+ return
746
+
747
+ x_column = "step"
748
+ if dfs and not dfs[0].empty and "x_axis" in dfs[0].columns:
749
+ x_column = dfs[0]["x_axis"].iloc[0]
750
+
751
+ numeric_cols = master_df.select_dtypes(include="number").columns
752
+ numeric_cols = [c for c in numeric_cols if c not in utils.RESERVED_KEYS]
753
+ if x_column and x_column in numeric_cols:
754
+ numeric_cols.remove(x_column)
755
+
756
+ if metrics_subset:
757
+ numeric_cols = [c for c in numeric_cols if c in metrics_subset]
758
+
759
+ if metric_filter and metric_filter.strip():
760
+ numeric_cols = filter_metrics_by_regex(list(numeric_cols), metric_filter)
761
+
762
+ nested_metric_groups = utils.group_metrics_with_subprefixes(list(numeric_cols))
763
+ color_map = utils.get_color_mapping(original_runs, smoothing_granularity > 0)
764
+
765
+ metric_idx = 0
766
+ for group_name in sorted(nested_metric_groups.keys()):
767
+ group_data = nested_metric_groups[group_name]
768
+
769
+ total_plot_count = sum(
770
+ 1
771
+ for m in group_data["direct_metrics"]
772
+ if not master_df.dropna(subset=[m]).empty
773
+ ) + sum(
774
+ sum(1 for m in metrics if not master_df.dropna(subset=[m]).empty)
775
+ for metrics in group_data["subgroups"].values()
776
+ )
777
+ group_label = (
778
+ f"{group_name} ({total_plot_count})"
779
+ if total_plot_count > 0
780
+ else group_name
781
+ )
782
+
783
+ with gr.Accordion(
784
+ label=group_label,
785
+ open=True,
786
+ key=f"accordion-{group_name}",
787
+ preserved_by_key=["value", "open"],
788
+ ):
789
+ if group_data["direct_metrics"]:
790
+ with gr.Draggable(
791
+ key=f"row-{group_name}-direct", orientation="row"
792
+ ):
793
+ for metric_name in group_data["direct_metrics"]:
794
+ metric_df = master_df.dropna(subset=[metric_name])
795
+ color = "run" if "run" in metric_df.columns else None
796
+ if not metric_df.empty:
797
+ plot = gr.LinePlot(
798
+ utils.downsample(
799
+ metric_df,
800
+ x_column,
801
+ metric_name,
802
+ color,
803
+ x_lim_value,
804
+ ),
805
+ x=x_column,
806
+ y=metric_name,
807
+ y_title=metric_name.split("/")[-1],
808
+ color=color,
809
+ color_map=color_map,
810
+ title=metric_name,
811
+ key=f"plot-{metric_idx}",
812
+ preserved_by_key=None,
813
+ x_lim=x_lim_value,
814
+ show_fullscreen_button=True,
815
+ min_width=400,
816
+ )
817
+ plot.select(
818
+ update_x_lim,
819
+ outputs=x_lim,
820
+ key=f"select-{metric_idx}",
821
+ )
822
+ plot.double_click(
823
+ lambda: None,
824
+ outputs=x_lim,
825
+ key=f"double-{metric_idx}",
826
+ )
827
+ metric_idx += 1
828
+
829
+ if group_data["subgroups"]:
830
+ for subgroup_name in sorted(group_data["subgroups"].keys()):
831
+ subgroup_metrics = group_data["subgroups"][subgroup_name]
832
+
833
+ subgroup_plot_count = sum(
834
+ 1
835
+ for m in subgroup_metrics
836
+ if not master_df.dropna(subset=[m]).empty
837
+ )
838
+ subgroup_label = (
839
+ f"{subgroup_name} ({subgroup_plot_count})"
840
+ if subgroup_plot_count > 0
841
+ else subgroup_name
842
+ )
843
+
844
+ with gr.Accordion(
845
+ label=subgroup_label,
846
+ open=True,
847
+ key=f"accordion-{group_name}-{subgroup_name}",
848
+ preserved_by_key=["value", "open"],
849
+ ):
850
+ with gr.Draggable(key=f"row-{group_name}-{subgroup_name}"):
851
+ for metric_name in subgroup_metrics:
852
+ metric_df = master_df.dropna(subset=[metric_name])
853
+ color = (
854
+ "run" if "run" in metric_df.columns else None
855
+ )
856
+ if not metric_df.empty:
857
+ plot = gr.LinePlot(
858
+ utils.downsample(
859
+ metric_df,
860
+ x_column,
861
+ metric_name,
862
+ color,
863
+ x_lim_value,
864
+ ),
865
+ x=x_column,
866
+ y=metric_name,
867
+ y_title=metric_name.split("/")[-1],
868
+ color=color,
869
+ color_map=color_map,
870
+ title=metric_name,
871
+ key=f"plot-{metric_idx}",
872
+ preserved_by_key=None,
873
+ x_lim=x_lim_value,
874
+ show_fullscreen_button=True,
875
+ min_width=400,
876
+ )
877
+ plot.select(
878
+ update_x_lim,
879
+ outputs=x_lim,
880
+ key=f"select-{metric_idx}",
881
+ )
882
+ plot.double_click(
883
+ lambda: None,
884
+ outputs=x_lim,
885
+ key=f"double-{metric_idx}",
886
+ )
887
+ metric_idx += 1
888
+ if images_by_run and any(any(images) for images in images_by_run.values()):
889
+ create_media_section(images_by_run)
890
+
891
+ table_cols = master_df.select_dtypes(include="object").columns
892
+ table_cols = [c for c in table_cols if c not in utils.RESERVED_KEYS]
893
+ if metrics_subset:
894
+ table_cols = [c for c in table_cols if c in metrics_subset]
895
+ if metric_filter and metric_filter.strip():
896
+ table_cols = filter_metrics_by_regex(list(table_cols), metric_filter)
897
+
898
+ actual_table_count = sum(
899
+ 1
900
+ for metric_name in table_cols
901
+ if not (metric_df := master_df.dropna(subset=[metric_name])).empty
902
+ and isinstance(value := metric_df[metric_name].iloc[-1], dict)
903
+ and value.get("_type") == Table.TYPE
904
+ )
905
+
906
+ if actual_table_count > 0:
907
+ with gr.Accordion(f"tables ({actual_table_count})", open=True):
908
+ with gr.Row(key="row"):
909
+ for metric_idx, metric_name in enumerate(table_cols):
910
+ metric_df = master_df.dropna(subset=[metric_name])
911
+ if not metric_df.empty:
912
+ value = metric_df[metric_name].iloc[-1]
913
+ if (
914
+ isinstance(value, dict)
915
+ and "_type" in value
916
+ and value["_type"] == Table.TYPE
917
+ ):
918
+ try:
919
+ df = pd.DataFrame(value["_value"])
920
+ gr.DataFrame(
921
+ df,
922
+ label=f"{metric_name} (latest)",
923
+ key=f"table-{metric_idx}",
924
+ wrap=True,
925
+ )
926
+ except Exception as e:
927
+ gr.Warning(
928
+ f"Column {metric_name} failed to render as a table: {e}"
929
+ )
930
+
931
+
932
+ with demo.route("Runs", show_in_navbar=False):
933
+ run_page.render()
934
+ with demo.route("Run", show_in_navbar=False):
935
+ run_detail_page.render()
936
+
937
+ write_token = secrets.token_urlsafe(32)
938
+ demo.write_token = write_token
939
+ run_page.write_token = write_token
940
+ run_detail_page.write_token = write_token
941
+
942
+ if __name__ == "__main__":
943
+ demo.launch(allowed_paths=[utils.TRACKIO_LOGO_DIR], show_api=False, show_error=True)
ui/run_detail.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The Runs page for the Trackio UI."""
2
+
3
+ import gradio as gr
4
+
5
+ try:
6
+ import trackio.utils as utils
7
+ from trackio.sqlite_storage import SQLiteStorage
8
+ from trackio.ui import fns
9
+ except ImportError:
10
+ import utils
11
+ from sqlite_storage import SQLiteStorage
12
+ from ui import fns
13
+
14
+ RUN_DETAILS_TEMPLATE = """
15
+ ## Run Details
16
+ * **Run Name:** `{run_name}`
17
+ * **Created:** {created} by {username}
18
+ """
19
+
20
+ with gr.Blocks() as run_detail_page:
21
+ with gr.Sidebar() as sidebar:
22
+ logo = gr.Markdown(
23
+ f"""
24
+ <img src='/gradio_api/file={utils.TRACKIO_LOGO_DIR}/trackio_logo_type_light_transparent.png' width='80%' class='logo-light'>
25
+ <img src='/gradio_api/file={utils.TRACKIO_LOGO_DIR}/trackio_logo_type_dark_transparent.png' width='80%' class='logo-dark'>
26
+ """
27
+ )
28
+ project_dd = gr.Dropdown(
29
+ label="Project", allow_custom_value=True, interactive=False
30
+ )
31
+ run_dd = gr.Dropdown(label="Run")
32
+
33
+ navbar = gr.Navbar(value=[("Metrics", ""), ("Runs", "/runs")], main_page_name=False)
34
+
35
+ run_details = gr.Markdown(RUN_DETAILS_TEMPLATE)
36
+
37
+ run_config = gr.JSON(label="Run Config")
38
+
39
+ def configure(request: gr.Request):
40
+ project = request.query_params.get("selected_project")
41
+ run = request.query_params.get("selected_run")
42
+ runs = SQLiteStorage.get_runs(project)
43
+ return project, gr.Dropdown(choices=runs, value=run)
44
+
45
+ def update_run_details(project, run):
46
+ config = SQLiteStorage.get_run_config(project, run)
47
+ if not config:
48
+ return gr.Markdown("No run details available"), {}
49
+
50
+ created = config.get("_Created", "Unknown")
51
+ if created != "Unknown":
52
+ created = utils.format_timestamp(created)
53
+
54
+ username = config.get("_Username", "Unknown")
55
+ if username and username != "None" and username != "Unknown":
56
+ username = f"[{username}](https://huggingface.co/{username})"
57
+
58
+ details_md = RUN_DETAILS_TEMPLATE.format(
59
+ run_name=run, created=created, username=username
60
+ )
61
+
62
+ config_display = {k: v for k, v in config.items() if not k.startswith("_")}
63
+
64
+ return gr.Markdown(details_md), config_display
65
+
66
+ gr.on(
67
+ [run_detail_page.load],
68
+ fn=configure,
69
+ outputs=[project_dd, run_dd],
70
+ show_progress="hidden",
71
+ queue=False,
72
+ api_name=False,
73
+ ).then(
74
+ fns.update_navbar_value,
75
+ inputs=[project_dd],
76
+ outputs=[navbar],
77
+ show_progress="hidden",
78
+ api_name=False,
79
+ queue=False,
80
+ )
81
+
82
+ gr.on(
83
+ [run_dd.change],
84
+ update_run_details,
85
+ inputs=[project_dd, run_dd],
86
+ outputs=[run_details, run_config],
87
+ show_progress="hidden",
88
+ api_name=False,
89
+ queue=False,
90
+ )
ui/runs.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The Runs page for the Trackio UI."""
2
+
3
+ import re
4
+
5
+ import gradio as gr
6
+ import pandas as pd
7
+
8
+ try:
9
+ import trackio.utils as utils
10
+ from trackio.sqlite_storage import SQLiteStorage
11
+ from trackio.ui import fns
12
+ except ImportError:
13
+ import utils
14
+ from sqlite_storage import SQLiteStorage
15
+ from ui import fns
16
+
17
+
18
+ def get_runs_data(project):
19
+ """Get the runs data as a pandas DataFrame."""
20
+ configs = SQLiteStorage.get_all_run_configs(project)
21
+ if not configs:
22
+ return pd.DataFrame()
23
+
24
+ df = pd.DataFrame.from_dict(configs, orient="index")
25
+ df = df.fillna("")
26
+ df.index.name = "Name"
27
+ df.reset_index(inplace=True)
28
+
29
+ column_mapping = {"_Username": "Username", "_Created": "Created"}
30
+ df.rename(columns=column_mapping, inplace=True)
31
+
32
+ if "Created" in df.columns:
33
+ df["Created"] = df["Created"].apply(utils.format_timestamp)
34
+
35
+ if "Username" in df.columns:
36
+ df["Username"] = df["Username"].apply(
37
+ lambda x: f"<a href='https://huggingface.co/{x}' style='text-decoration-style: dotted;'>{x}</a>"
38
+ if x and x != "None"
39
+ else x
40
+ )
41
+
42
+ if "Name" in df.columns:
43
+ df["Name"] = df["Name"].apply(
44
+ lambda x: f"<a href='/run?selected_project={project}&selected_run={x}'>{x}</a>"
45
+ if x and x != "None"
46
+ else x
47
+ )
48
+
49
+ df.insert(0, " ", False)
50
+
51
+ columns = list(df.columns)
52
+ if "Username" in columns and "Created" in columns:
53
+ columns.remove("Username")
54
+ columns.remove("Created")
55
+ columns.insert(2, "Username")
56
+ columns.insert(3, "Created")
57
+ df = df[columns]
58
+
59
+ return df
60
+
61
+
62
+ def get_runs_table(project):
63
+ df = get_runs_data(project)
64
+ if df.empty:
65
+ return gr.DataFrame(pd.DataFrame(), visible=False)
66
+
67
+ datatype = ["bool"] + ["markdown"] * (len(df.columns) - 1)
68
+
69
+ return gr.DataFrame(
70
+ df,
71
+ visible=True,
72
+ pinned_columns=2,
73
+ datatype=datatype,
74
+ wrap=True,
75
+ column_widths=["40px", "150px"],
76
+ interactive=True,
77
+ static_columns=list(range(1, len(df.columns))),
78
+ row_count=(len(df), "fixed"),
79
+ col_count=(len(df.columns), "fixed"),
80
+ )
81
+
82
+
83
+ def check_write_access_runs(request: gr.Request, write_token: str) -> bool:
84
+ """Check if the user has write access based on token validation."""
85
+ cookies = request.headers.get("cookie", "")
86
+ if cookies:
87
+ for cookie in cookies.split(";"):
88
+ parts = cookie.strip().split("=")
89
+ if len(parts) == 2 and parts[0] == "trackio_write_token":
90
+ return parts[1] == write_token
91
+ if hasattr(request, "query_params") and request.query_params:
92
+ token = request.query_params.get("write_token")
93
+ return token == write_token
94
+ return False
95
+
96
+
97
+ def update_delete_button(runs_data, request: gr.Request):
98
+ """Update the delete button value and interactivity based on the runs data and user write access."""
99
+ if not check_write_access_runs(request, run_page.write_token):
100
+ return gr.Button("⚠️ Need write access to delete runs", interactive=False)
101
+
102
+ num_selected = 0
103
+ if runs_data is not None and len(runs_data) > 0:
104
+ first_column_values = runs_data.iloc[:, 0].tolist()
105
+ num_selected = sum(1 for x in first_column_values if x)
106
+
107
+ if num_selected:
108
+ return gr.Button(f"Delete {num_selected} selected run(s)", interactive=True)
109
+ else:
110
+ return gr.Button("Select runs to delete", interactive=False)
111
+
112
+
113
+ def delete_selected_runs(runs_data, project, request: gr.Request):
114
+ """Delete the selected runs and refresh the table."""
115
+ if not check_write_access_runs(request, run_page.write_token):
116
+ return runs_data
117
+
118
+ first_column_values = runs_data.iloc[:, 0].tolist()
119
+ for i, selected in enumerate(first_column_values):
120
+ if selected:
121
+ run_name_raw = runs_data.iloc[i, 1]
122
+ match = re.search(r">([^<]+)<", run_name_raw)
123
+ run_name = match.group(1) if match else run_name_raw
124
+ SQLiteStorage.delete_run(project, run_name)
125
+
126
+ updated_data = get_runs_data(project)
127
+ return updated_data
128
+
129
+
130
+ with gr.Blocks() as run_page:
131
+ with gr.Sidebar() as sidebar:
132
+ logo = gr.Markdown(
133
+ f"""
134
+ <img src='/gradio_api/file={utils.TRACKIO_LOGO_DIR}/trackio_logo_type_light_transparent.png' width='80%' class='logo-light'>
135
+ <img src='/gradio_api/file={utils.TRACKIO_LOGO_DIR}/trackio_logo_type_dark_transparent.png' width='80%' class='logo-dark'>
136
+ """
137
+ )
138
+ project_dd = gr.Dropdown(label="Project", allow_custom_value=True)
139
+
140
+ navbar = gr.Navbar(value=[("Metrics", ""), ("Runs", "/runs")], main_page_name=False)
141
+ timer = gr.Timer(value=1)
142
+ with gr.Row():
143
+ with gr.Column():
144
+ pass
145
+ with gr.Column():
146
+ with gr.Row():
147
+ delete_run_btn = gr.Button(
148
+ "⚠️ Need write access to delete runs",
149
+ interactive=False,
150
+ variant="stop",
151
+ size="sm",
152
+ )
153
+ confirm_btn = gr.Button(
154
+ "Confirm delete", variant="stop", size="sm", visible=False
155
+ )
156
+ cancel_btn = gr.Button("Cancel", size="sm", visible=False)
157
+
158
+ runs_table = gr.DataFrame()
159
+
160
+ gr.on(
161
+ [run_page.load],
162
+ fn=fns.get_projects,
163
+ outputs=project_dd,
164
+ show_progress="hidden",
165
+ queue=False,
166
+ api_name=False,
167
+ )
168
+ gr.on(
169
+ [timer.tick],
170
+ fn=lambda: gr.Dropdown(info=fns.get_project_info()),
171
+ outputs=[project_dd],
172
+ show_progress="hidden",
173
+ api_name=False,
174
+ )
175
+ gr.on(
176
+ [project_dd.change],
177
+ fn=get_runs_table,
178
+ inputs=[project_dd],
179
+ outputs=[runs_table],
180
+ show_progress="hidden",
181
+ api_name=False,
182
+ queue=False,
183
+ ).then(
184
+ fns.update_navbar_value,
185
+ inputs=[project_dd],
186
+ outputs=[navbar],
187
+ show_progress="hidden",
188
+ api_name=False,
189
+ queue=False,
190
+ )
191
+
192
+ gr.on(
193
+ [run_page.load, runs_table.change],
194
+ fn=update_delete_button,
195
+ inputs=[runs_table],
196
+ outputs=[delete_run_btn],
197
+ show_progress="hidden",
198
+ api_name=False,
199
+ queue=False,
200
+ )
201
+
202
+ gr.on(
203
+ [delete_run_btn.click],
204
+ fn=lambda: [
205
+ gr.Button(visible=False),
206
+ gr.Button(visible=True),
207
+ gr.Button(visible=True),
208
+ ],
209
+ inputs=None,
210
+ outputs=[delete_run_btn, confirm_btn, cancel_btn],
211
+ show_progress="hidden",
212
+ api_name=False,
213
+ queue=False,
214
+ )
215
+ gr.on(
216
+ [confirm_btn.click, cancel_btn.click],
217
+ fn=lambda: [
218
+ gr.Button(visible=True),
219
+ gr.Button(visible=False),
220
+ gr.Button(visible=False),
221
+ ],
222
+ inputs=None,
223
+ outputs=[delete_run_btn, confirm_btn, cancel_btn],
224
+ show_progress="hidden",
225
+ api_name=False,
226
+ queue=False,
227
+ )
228
+ gr.on(
229
+ [confirm_btn.click],
230
+ fn=delete_selected_runs,
231
+ inputs=[runs_table, project_dd],
232
+ outputs=[runs_table],
233
+ show_progress="hidden",
234
+ api_name=False,
235
+ queue=False,
236
+ )
utils.py ADDED
@@ -0,0 +1,771 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import re
4
+ import time
5
+ from datetime import datetime, timezone
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 is_in_notebook():
246
+ """
247
+ Detect if code is running in a notebook environment (Jupyter, Colab, etc.).
248
+ """
249
+ try:
250
+ from IPython import get_ipython
251
+
252
+ if get_ipython() is not None:
253
+ return get_ipython().__class__.__name__ in [
254
+ "ZMQInteractiveShell", # Jupyter notebook/lab
255
+ "Shell", # IPython terminal
256
+ ] or "google.colab" in str(get_ipython())
257
+ except ImportError:
258
+ pass
259
+ return False
260
+
261
+
262
+ def block_main_thread_until_keyboard_interrupt():
263
+ try:
264
+ while True:
265
+ time.sleep(0.1)
266
+ except (KeyboardInterrupt, OSError):
267
+ print("Keyboard interruption in main thread... closing dashboard.")
268
+
269
+
270
+ def simplify_column_names(columns: list[str]) -> dict[str, str]:
271
+ """
272
+ Simplifies column names to first 10 alphanumeric or "/" characters with unique suffixes.
273
+
274
+ Args:
275
+ columns: List of original column names
276
+
277
+ Returns:
278
+ Dictionary mapping original column names to simplified names
279
+ """
280
+ simplified_names = {}
281
+ used_names = set()
282
+
283
+ for col in columns:
284
+ alphanumeric = re.sub(r"[^a-zA-Z0-9/]", "", col)
285
+ base_name = alphanumeric[:10] if alphanumeric else f"col_{len(used_names)}"
286
+
287
+ final_name = base_name
288
+ suffix = 1
289
+ while final_name in used_names:
290
+ final_name = f"{base_name}_{suffix}"
291
+ suffix += 1
292
+
293
+ simplified_names[col] = final_name
294
+ used_names.add(final_name)
295
+
296
+ return simplified_names
297
+
298
+
299
+ def print_dashboard_instructions(project: str) -> None:
300
+ """
301
+ Prints instructions for viewing the Trackio dashboard.
302
+
303
+ Args:
304
+ project: The name of the project to show dashboard for.
305
+ """
306
+ ORANGE = "\033[38;5;208m"
307
+ BOLD = "\033[1m"
308
+ RESET = "\033[0m"
309
+
310
+ print("* View dashboard by running in your terminal:")
311
+ print(f'{BOLD}{ORANGE}trackio show --project "{project}"{RESET}')
312
+ print(f'* or by running in Python: trackio.show(project="{project}")')
313
+
314
+
315
+ def preprocess_space_and_dataset_ids(
316
+ space_id: str | None, dataset_id: str | None
317
+ ) -> tuple[str | None, str | None]:
318
+ if space_id is not None and "/" not in space_id:
319
+ username = huggingface_hub.whoami()["name"]
320
+ space_id = f"{username}/{space_id}"
321
+ if dataset_id is not None and "/" not in dataset_id:
322
+ username = huggingface_hub.whoami()["name"]
323
+ dataset_id = f"{username}/{dataset_id}"
324
+ if space_id is not None and dataset_id is None:
325
+ dataset_id = f"{space_id}-dataset"
326
+ return space_id, dataset_id
327
+
328
+
329
+ def fibo():
330
+ """Generator for Fibonacci backoff: 1, 1, 2, 3, 5, 8, ..."""
331
+ a, b = 1, 1
332
+ while True:
333
+ yield a
334
+ a, b = b, a + b
335
+
336
+
337
+ def format_timestamp(timestamp_str):
338
+ """Convert ISO timestamp to human-readable format like '3 minutes ago'."""
339
+ if not timestamp_str or pd.isna(timestamp_str):
340
+ return "Unknown"
341
+
342
+ try:
343
+ created_time = datetime.fromisoformat(timestamp_str.replace("Z", "+00:00"))
344
+ if created_time.tzinfo is None:
345
+ created_time = created_time.replace(tzinfo=timezone.utc)
346
+
347
+ now = datetime.now(timezone.utc)
348
+ diff = now - created_time
349
+
350
+ seconds = int(diff.total_seconds())
351
+ if seconds < 60:
352
+ return "Just now"
353
+ elif seconds < 3600:
354
+ minutes = seconds // 60
355
+ return f"{minutes} minute{'s' if minutes != 1 else ''} ago"
356
+ elif seconds < 86400:
357
+ hours = seconds // 3600
358
+ return f"{hours} hour{'s' if hours != 1 else ''} ago"
359
+ else:
360
+ days = seconds // 86400
361
+ return f"{days} day{'s' if days != 1 else ''} ago"
362
+ except Exception:
363
+ return "Unknown"
364
+
365
+
366
+ COLOR_PALETTE = [
367
+ "#3B82F6",
368
+ "#EF4444",
369
+ "#10B981",
370
+ "#F59E0B",
371
+ "#8B5CF6",
372
+ "#EC4899",
373
+ "#06B6D4",
374
+ "#84CC16",
375
+ "#F97316",
376
+ "#6366F1",
377
+ ]
378
+
379
+
380
+ def get_color_mapping(runs: list[str], smoothing: bool) -> dict[str, str]:
381
+ """Generate color mapping for runs, with transparency for original data when smoothing is enabled."""
382
+ color_map = {}
383
+
384
+ for i, run in enumerate(runs):
385
+ base_color = COLOR_PALETTE[i % len(COLOR_PALETTE)]
386
+
387
+ if smoothing:
388
+ color_map[run] = base_color + "4D"
389
+ color_map[f"{run}_smoothed"] = base_color
390
+ else:
391
+ color_map[run] = base_color
392
+
393
+ return color_map
394
+
395
+
396
+ def downsample(
397
+ df: pd.DataFrame,
398
+ x: str,
399
+ y: str,
400
+ color: str | None,
401
+ x_lim: tuple[float, float] | None = None,
402
+ ) -> pd.DataFrame:
403
+ if df.empty:
404
+ return df
405
+
406
+ columns_to_keep = [x, y]
407
+ if color is not None and color in df.columns:
408
+ columns_to_keep.append(color)
409
+ df = df[columns_to_keep].copy()
410
+
411
+ n_bins = 100
412
+
413
+ if color is not None and color in df.columns:
414
+ groups = df.groupby(color)
415
+ else:
416
+ groups = [(None, df)]
417
+
418
+ downsampled_indices = []
419
+
420
+ for _, group_df in groups:
421
+ if group_df.empty:
422
+ continue
423
+
424
+ group_df = group_df.sort_values(x)
425
+
426
+ if x_lim is not None:
427
+ x_min, x_max = x_lim
428
+ before_point = group_df[group_df[x] < x_min].tail(1)
429
+ after_point = group_df[group_df[x] > x_max].head(1)
430
+ group_df = group_df[(group_df[x] >= x_min) & (group_df[x] <= x_max)]
431
+ else:
432
+ before_point = after_point = None
433
+ x_min = group_df[x].min()
434
+ x_max = group_df[x].max()
435
+
436
+ if before_point is not None and not before_point.empty:
437
+ downsampled_indices.extend(before_point.index.tolist())
438
+ if after_point is not None and not after_point.empty:
439
+ downsampled_indices.extend(after_point.index.tolist())
440
+
441
+ if group_df.empty:
442
+ continue
443
+
444
+ if x_min == x_max:
445
+ min_y_idx = group_df[y].idxmin()
446
+ max_y_idx = group_df[y].idxmax()
447
+ if min_y_idx != max_y_idx:
448
+ downsampled_indices.extend([min_y_idx, max_y_idx])
449
+ else:
450
+ downsampled_indices.append(min_y_idx)
451
+ continue
452
+
453
+ if len(group_df) < 500:
454
+ downsampled_indices.extend(group_df.index.tolist())
455
+ continue
456
+
457
+ bins = np.linspace(x_min, x_max, n_bins + 1)
458
+ group_df["bin"] = pd.cut(
459
+ group_df[x], bins=bins, labels=False, include_lowest=True
460
+ )
461
+
462
+ for bin_idx in group_df["bin"].dropna().unique():
463
+ bin_data = group_df[group_df["bin"] == bin_idx]
464
+ if bin_data.empty:
465
+ continue
466
+
467
+ min_y_idx = bin_data[y].idxmin()
468
+ max_y_idx = bin_data[y].idxmax()
469
+
470
+ downsampled_indices.append(min_y_idx)
471
+ if min_y_idx != max_y_idx:
472
+ downsampled_indices.append(max_y_idx)
473
+
474
+ unique_indices = list(set(downsampled_indices))
475
+
476
+ downsampled_df = df.loc[unique_indices].copy()
477
+
478
+ if color is not None:
479
+ downsampled_df = (
480
+ downsampled_df.groupby(color, sort=False)[downsampled_df.columns]
481
+ .apply(lambda group: group.sort_values(x))
482
+ .reset_index(drop=True)
483
+ )
484
+ else:
485
+ downsampled_df = downsampled_df.sort_values(x).reset_index(drop=True)
486
+
487
+ downsampled_df = downsampled_df.drop(columns=["bin"], errors="ignore")
488
+
489
+ return downsampled_df
490
+
491
+
492
+ def sort_metrics_by_prefix(metrics: list[str]) -> list[str]:
493
+ """
494
+ Sort metrics by grouping prefixes together for dropdown/list display.
495
+ Metrics without prefixes come first, then grouped by prefix.
496
+
497
+ Args:
498
+ metrics: List of metric names
499
+
500
+ Returns:
501
+ List of metric names sorted by prefix
502
+
503
+ Example:
504
+ Input: ["train/loss", "loss", "train/acc", "val/loss"]
505
+ Output: ["loss", "train/acc", "train/loss", "val/loss"]
506
+ """
507
+ groups = group_metrics_by_prefix(metrics)
508
+ result = []
509
+
510
+ if "charts" in groups:
511
+ result.extend(groups["charts"])
512
+
513
+ for group_name in sorted(groups.keys()):
514
+ if group_name != "charts":
515
+ result.extend(groups[group_name])
516
+
517
+ return result
518
+
519
+
520
+ def group_metrics_by_prefix(metrics: list[str]) -> dict[str, list[str]]:
521
+ """
522
+ Group metrics by their prefix. Metrics without prefix go to 'charts' group.
523
+
524
+ Args:
525
+ metrics: List of metric names
526
+
527
+ Returns:
528
+ Dictionary with prefix names as keys and lists of metrics as values
529
+
530
+ Example:
531
+ Input: ["loss", "accuracy", "train/loss", "train/acc", "val/loss"]
532
+ Output: {
533
+ "charts": ["loss", "accuracy"],
534
+ "train": ["train/loss", "train/acc"],
535
+ "val": ["val/loss"]
536
+ }
537
+ """
538
+ no_prefix = []
539
+ with_prefix = []
540
+
541
+ for metric in metrics:
542
+ if "/" in metric:
543
+ with_prefix.append(metric)
544
+ else:
545
+ no_prefix.append(metric)
546
+
547
+ no_prefix.sort()
548
+
549
+ prefix_groups = {}
550
+ for metric in with_prefix:
551
+ prefix = metric.split("/")[0]
552
+ if prefix not in prefix_groups:
553
+ prefix_groups[prefix] = []
554
+ prefix_groups[prefix].append(metric)
555
+
556
+ for prefix in prefix_groups:
557
+ prefix_groups[prefix].sort()
558
+
559
+ groups = {}
560
+ if no_prefix:
561
+ groups["charts"] = no_prefix
562
+
563
+ for prefix in sorted(prefix_groups.keys()):
564
+ groups[prefix] = prefix_groups[prefix]
565
+
566
+ return groups
567
+
568
+
569
+ def group_metrics_with_subprefixes(metrics: list[str]) -> dict:
570
+ """
571
+ Group metrics with simple 2-level nested structure detection.
572
+
573
+ Returns a dictionary where each prefix group can have:
574
+ - direct_metrics: list of metrics at this level (e.g., "train/acc")
575
+ - subgroups: dict of subgroup name -> list of metrics (e.g., "loss" -> ["train/loss/norm", "train/loss/unnorm"])
576
+
577
+ Example:
578
+ Input: ["loss", "train/acc", "train/loss/normalized", "train/loss/unnormalized", "val/loss"]
579
+ Output: {
580
+ "charts": {
581
+ "direct_metrics": ["loss"],
582
+ "subgroups": {}
583
+ },
584
+ "train": {
585
+ "direct_metrics": ["train/acc"],
586
+ "subgroups": {
587
+ "loss": ["train/loss/normalized", "train/loss/unnormalized"]
588
+ }
589
+ },
590
+ "val": {
591
+ "direct_metrics": ["val/loss"],
592
+ "subgroups": {}
593
+ }
594
+ }
595
+ """
596
+ result = {}
597
+
598
+ for metric in metrics:
599
+ if "/" not in metric:
600
+ if "charts" not in result:
601
+ result["charts"] = {"direct_metrics": [], "subgroups": {}}
602
+ result["charts"]["direct_metrics"].append(metric)
603
+ else:
604
+ parts = metric.split("/")
605
+ main_prefix = parts[0]
606
+
607
+ if main_prefix not in result:
608
+ result[main_prefix] = {"direct_metrics": [], "subgroups": {}}
609
+
610
+ if len(parts) == 2:
611
+ result[main_prefix]["direct_metrics"].append(metric)
612
+ else:
613
+ subprefix = parts[1]
614
+ if subprefix not in result[main_prefix]["subgroups"]:
615
+ result[main_prefix]["subgroups"][subprefix] = []
616
+ result[main_prefix]["subgroups"][subprefix].append(metric)
617
+
618
+ for group_data in result.values():
619
+ group_data["direct_metrics"].sort()
620
+ for subgroup_metrics in group_data["subgroups"].values():
621
+ subgroup_metrics.sort()
622
+
623
+ if "charts" in result and not result["charts"]["direct_metrics"]:
624
+ del result["charts"]
625
+
626
+ return result
627
+
628
+
629
+ def get_sync_status(scheduler: "CommitScheduler | DummyCommitScheduler") -> int | None:
630
+ """Get the sync status from the CommitScheduler in an integer number of minutes, or None if not synced yet."""
631
+ if getattr(
632
+ scheduler, "last_push_time", None
633
+ ): # DummyCommitScheduler doesn't have last_push_time
634
+ time_diff = time.time() - scheduler.last_push_time
635
+ return int(time_diff / 60)
636
+ else:
637
+ return None
638
+
639
+
640
+ def generate_embed_code(project: str, metrics: str, selected_runs: list = None) -> str:
641
+ """Generate the embed iframe code based on current settings."""
642
+ space_host = os.environ.get("SPACE_HOST", "")
643
+ if not space_host:
644
+ return ""
645
+
646
+ params = []
647
+
648
+ if project:
649
+ params.append(f"project={project}")
650
+
651
+ if metrics and metrics.strip():
652
+ params.append(f"metrics={metrics}")
653
+
654
+ if selected_runs:
655
+ runs_param = ",".join(selected_runs)
656
+ params.append(f"runs={runs_param}")
657
+
658
+ params.append("sidebar=hidden")
659
+ params.append("navbar=hidden")
660
+
661
+ query_string = "&".join(params)
662
+ embed_url = f"https://{space_host}?{query_string}"
663
+
664
+ return f'<iframe src="{embed_url}" style="width:1600px; height:500px; border:0;"></iframe>'
665
+
666
+
667
+ def serialize_values(metrics):
668
+ """
669
+ Serialize infinity and NaN values in metrics dict to make it JSON-compliant.
670
+ Only handles top-level float values.
671
+
672
+ Converts:
673
+ - float('inf') -> "Infinity"
674
+ - float('-inf') -> "-Infinity"
675
+ - float('nan') -> "NaN"
676
+
677
+ Example:
678
+ {"loss": float('inf'), "accuracy": 0.95} -> {"loss": "Infinity", "accuracy": 0.95}
679
+ """
680
+ if not isinstance(metrics, dict):
681
+ return metrics
682
+
683
+ result = {}
684
+ for key, value in metrics.items():
685
+ if isinstance(value, float):
686
+ if math.isinf(value):
687
+ result[key] = "Infinity" if value > 0 else "-Infinity"
688
+ elif math.isnan(value):
689
+ result[key] = "NaN"
690
+ else:
691
+ result[key] = value
692
+ elif isinstance(value, np.floating):
693
+ float_val = float(value)
694
+ if math.isinf(float_val):
695
+ result[key] = "Infinity" if float_val > 0 else "-Infinity"
696
+ elif math.isnan(float_val):
697
+ result[key] = "NaN"
698
+ else:
699
+ result[key] = float_val
700
+ else:
701
+ result[key] = value
702
+ return result
703
+
704
+
705
+ def deserialize_values(metrics):
706
+ """
707
+ Deserialize infinity and NaN string values back to their numeric forms.
708
+ Only handles top-level string values.
709
+
710
+ Converts:
711
+ - "Infinity" -> float('inf')
712
+ - "-Infinity" -> float('-inf')
713
+ - "NaN" -> float('nan')
714
+
715
+ Example:
716
+ {"loss": "Infinity", "accuracy": 0.95} -> {"loss": float('inf'), "accuracy": 0.95}
717
+ """
718
+ if not isinstance(metrics, dict):
719
+ return metrics
720
+
721
+ result = {}
722
+ for key, value in metrics.items():
723
+ if value == "Infinity":
724
+ result[key] = float("inf")
725
+ elif value == "-Infinity":
726
+ result[key] = float("-inf")
727
+ elif value == "NaN":
728
+ result[key] = float("nan")
729
+ else:
730
+ result[key] = value
731
+ return result
732
+
733
+
734
+ def get_full_url(base_url: str, project: str | None, write_token: str) -> str:
735
+ params = []
736
+ if project:
737
+ params.append(f"project={project}")
738
+ params.append(f"write_token={write_token}")
739
+ return base_url + "?" + "&".join(params)
740
+
741
+
742
+ def embed_url_in_notebook(url: str) -> None:
743
+ try:
744
+ from IPython.display import HTML, display
745
+
746
+ embed_code = HTML(
747
+ f'<div><iframe src="{url}" width="100%" height="1000px" allow="autoplay; camera; microphone; clipboard-read; clipboard-write;" frameborder="0" allowfullscreen></iframe></div>'
748
+ )
749
+ display(embed_code)
750
+ except ImportError:
751
+ pass
752
+
753
+
754
+ def to_json_safe(obj):
755
+ if isinstance(obj, (str, int, float, bool, type(None))):
756
+ return obj
757
+ if isinstance(obj, np.generic):
758
+ return obj.item()
759
+ if isinstance(obj, dict):
760
+ return {str(k): to_json_safe(v) for k, v in obj.items()}
761
+ if isinstance(obj, (list, tuple, set)):
762
+ return [to_json_safe(v) for v in obj]
763
+ if hasattr(obj, "to_dict") and callable(obj.to_dict):
764
+ return to_json_safe(obj.to_dict())
765
+ if hasattr(obj, "__dict__"):
766
+ return {
767
+ str(k): to_json_safe(v)
768
+ for k, v in vars(obj).items()
769
+ if not k.startswith("_")
770
+ }
771
+ return str(obj)
version.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 0.4.1.dev0
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}")