merve HF Staff commited on
Commit
10d7861
·
verified ·
1 Parent(s): b237745

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. CHANGELOG.md +42 -0
  3. __init__.py +339 -0
  4. __pycache__/__init__.cpython-312.pyc +0 -0
  5. __pycache__/cli.cpython-312.pyc +0 -0
  6. __pycache__/commit_scheduler.cpython-312.pyc +0 -0
  7. __pycache__/context_vars.cpython-312.pyc +0 -0
  8. __pycache__/deploy.cpython-312.pyc +0 -0
  9. __pycache__/dummy_commit_scheduler.cpython-312.pyc +0 -0
  10. __pycache__/histogram.cpython-312.pyc +0 -0
  11. __pycache__/imports.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. assets/trackio_logo_dark.png +0 -0
  18. assets/trackio_logo_light.png +0 -0
  19. assets/trackio_logo_old.png +3 -0
  20. assets/trackio_logo_type_dark.png +0 -0
  21. assets/trackio_logo_type_dark_transparent.png +0 -0
  22. assets/trackio_logo_type_light.png +0 -0
  23. assets/trackio_logo_type_light_transparent.png +0 -0
  24. cli.py +37 -0
  25. commit_scheduler.py +391 -0
  26. context_vars.py +18 -0
  27. deploy.py +258 -0
  28. dummy_commit_scheduler.py +12 -0
  29. histogram.py +68 -0
  30. imports.py +302 -0
  31. media/__init__.py +34 -0
  32. media/__pycache__/__init__.cpython-312.pyc +0 -0
  33. media/__pycache__/audio_writer.cpython-312.pyc +0 -0
  34. media/__pycache__/file_storage.cpython-312.pyc +0 -0
  35. media/__pycache__/media.cpython-312.pyc +0 -0
  36. media/__pycache__/utils.cpython-312.pyc +0 -0
  37. media/__pycache__/video_writer.cpython-312.pyc +0 -0
  38. media/audio_writer.py +128 -0
  39. media/file_storage.py +37 -0
  40. media/media.py +378 -0
  41. media/utils.py +23 -0
  42. media/video_writer.py +109 -0
  43. package.json +6 -0
  44. py.typed +0 -0
  45. run.py +192 -0
  46. sqlite_storage.py +677 -0
  47. table.py +53 -0
  48. typehints.py +18 -0
  49. ui/__init__.py +10 -0
  50. ui/__pycache__/__init__.cpython-312.pyc +0 -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
CHANGELOG.md ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # trackio
2
+
3
+ ## 0.7.0
4
+
5
+ ### Features
6
+
7
+ - [#277](https://github.com/gradio-app/trackio/pull/277) [`db35601`](https://github.com/gradio-app/trackio/commit/db35601b9c023423c4654c9909b8ab73e58737de) - fix: make grouped runs view reflect live updates. Thanks @Saba9!
8
+ - [#320](https://github.com/gradio-app/trackio/pull/320) [`24ae739`](https://github.com/gradio-app/trackio/commit/24ae73969b09fb3126acd2f91647cdfbf8cf72a1) - Add additional query parms for xmin, xmax, and smoothing. Thanks @abidlabs!
9
+ - [#270](https://github.com/gradio-app/trackio/pull/270) [`cd1dfc3`](https://github.com/gradio-app/trackio/commit/cd1dfc3dc641b4499ac6d4a1b066fa8e2b52c57b) - feature: add support for logging audio. Thanks @Saba9!
10
+
11
+ ## 0.6.0
12
+
13
+ ### Features
14
+
15
+ - [#309](https://github.com/gradio-app/trackio/pull/309) [`1df2353`](https://github.com/gradio-app/trackio/commit/1df23534d6c01938c8db9c0f584ffa23e8d6021d) - Add histogram support with wandb-compatible API. Thanks @abidlabs!
16
+ - [#315](https://github.com/gradio-app/trackio/pull/315) [`76ba060`](https://github.com/gradio-app/trackio/commit/76ba06055dc43ca8f03b79f3e72d761949bd19a8) - Add guards to avoid silent fails. Thanks @Xmaster6y!
17
+ - [#313](https://github.com/gradio-app/trackio/pull/313) [`a606b3e`](https://github.com/gradio-app/trackio/commit/a606b3e1c5edf3d4cf9f31bd50605226a5a1c5d0) - No longer prevent certain keys from being used. Instead, dunderify them to prevent collisions with internal usage. Thanks @abidlabs!
18
+ - [#317](https://github.com/gradio-app/trackio/pull/317) [`27370a5`](https://github.com/gradio-app/trackio/commit/27370a595d0dbdf7eebbe7159d2ba778f039da44) - quick fixes for trackio.histogram. Thanks @abidlabs!
19
+ - [#312](https://github.com/gradio-app/trackio/pull/312) [`aa0f3bf`](https://github.com/gradio-app/trackio/commit/aa0f3bf372e7a0dd592a38af699c998363830eeb) - Fix video logging by adding TRACKIO_DIR to allowed_paths. Thanks @abidlabs!
20
+
21
+ ## 0.5.3
22
+
23
+ ### Features
24
+
25
+ - [#300](https://github.com/gradio-app/trackio/pull/300) [`5e4cacf`](https://github.com/gradio-app/trackio/commit/5e4cacf2e7ce527b4ce60de3a5bc05d2c02c77fb) - Adds more environment variables to allow customization of Trackio dashboard. Thanks @abidlabs!
26
+
27
+ ## 0.5.2
28
+
29
+ ### Features
30
+
31
+ - [#293](https://github.com/gradio-app/trackio/pull/293) [`64afc28`](https://github.com/gradio-app/trackio/commit/64afc28d3ea1dfd821472dc6bf0b8ed35a9b74be) - Ensures that the TRACKIO_DIR environment variable is respected. Thanks @abidlabs!
32
+ - [#287](https://github.com/gradio-app/trackio/pull/287) [`cd3e929`](https://github.com/gradio-app/trackio/commit/cd3e9294320949e6b8b829239069a43d5d7ff4c1) - fix(sqlite): unify .sqlite extension, allow export when DBs exist, clean WAL sidecars on import. Thanks @vaibhav-research!
33
+
34
+ ### Fixes
35
+
36
+ - [#291](https://github.com/gradio-app/trackio/pull/291) [`3b5adc3`](https://github.com/gradio-app/trackio/commit/3b5adc3d1f452dbab7a714d235f4974782f93730) - Fix the wheel build. Thanks @pngwn!
37
+
38
+ ## 0.5.1
39
+
40
+ ### Fixes
41
+
42
+ - [#278](https://github.com/gradio-app/trackio/pull/278) [`314c054`](https://github.com/gradio-app/trackio/commit/314c05438007ddfea3383e06fd19143e27468e2d) - Fix row orientation of metrics plots. Thanks @abidlabs!
__init__.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import json
3
+ import logging
4
+ import os
5
+ import warnings
6
+ import webbrowser
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from gradio.blocks import BUILT_IN_THEMES
11
+ from gradio.themes import Default as DefaultTheme
12
+ from gradio.themes import ThemeClass
13
+ from gradio_client import Client
14
+ from huggingface_hub import SpaceStorage
15
+
16
+ from trackio import context_vars, deploy, utils
17
+ from trackio.histogram import Histogram
18
+ from trackio.imports import import_csv, import_tf_events
19
+ from trackio.media import TrackioAudio, TrackioImage, TrackioVideo
20
+ from trackio.run import Run
21
+ from trackio.sqlite_storage import SQLiteStorage
22
+ from trackio.table import Table
23
+ from trackio.ui.main import demo
24
+ from trackio.utils import TRACKIO_DIR, TRACKIO_LOGO_DIR
25
+
26
+ logging.getLogger("httpx").setLevel(logging.WARNING)
27
+
28
+ warnings.filterwarnings(
29
+ "ignore",
30
+ message="Empty session being created. Install gradio\\[oauth\\]",
31
+ category=UserWarning,
32
+ module="gradio.helpers",
33
+ )
34
+
35
+ __version__ = json.loads(Path(__file__).parent.joinpath("package.json").read_text())[
36
+ "version"
37
+ ]
38
+
39
+ __all__ = [
40
+ "init",
41
+ "log",
42
+ "finish",
43
+ "show",
44
+ "import_csv",
45
+ "import_tf_events",
46
+ "Image",
47
+ "Video",
48
+ "Audio",
49
+ "Table",
50
+ "Histogram",
51
+ ]
52
+
53
+ Image = TrackioImage
54
+ Video = TrackioVideo
55
+ Audio = TrackioAudio
56
+
57
+
58
+ config = {}
59
+
60
+ DEFAULT_THEME = "default"
61
+
62
+
63
+ def init(
64
+ project: str,
65
+ name: str | None = None,
66
+ group: str | None = None,
67
+ space_id: str | None = None,
68
+ space_storage: SpaceStorage | None = None,
69
+ dataset_id: str | None = None,
70
+ config: dict | None = None,
71
+ resume: str = "never",
72
+ settings: Any = None,
73
+ private: bool | None = None,
74
+ embed: bool = True,
75
+ ) -> Run:
76
+ """
77
+ Creates a new Trackio project and returns a [`Run`] object.
78
+
79
+ Args:
80
+ project (`str`):
81
+ The name of the project (can be an existing project to continue tracking or
82
+ a new project to start tracking from scratch).
83
+ name (`str`, *optional*):
84
+ The name of the run (if not provided, a default name will be generated).
85
+ group (`str`, *optional*):
86
+ The name of the group which this run belongs to in order to help organize
87
+ related runs together. You can toggle the entire group's visibilitiy in the
88
+ dashboard.
89
+ space_id (`str`, *optional*):
90
+ If provided, the project will be logged to a Hugging Face Space instead of
91
+ a local directory. Should be a complete Space name like
92
+ `"username/reponame"` or `"orgname/reponame"`, or just `"reponame"` in which
93
+ case the Space will be created in the currently-logged-in Hugging Face
94
+ user's namespace. If the Space does not exist, it will be created. If the
95
+ Space already exists, the project will be logged to it.
96
+ space_storage ([`~huggingface_hub.SpaceStorage`], *optional*):
97
+ Choice of persistent storage tier.
98
+ dataset_id (`str`, *optional*):
99
+ If a `space_id` is provided, a persistent Hugging Face Dataset will be
100
+ created and the metrics will be synced to it every 5 minutes. Specify a
101
+ Dataset with name like `"username/datasetname"` or `"orgname/datasetname"`,
102
+ or `"datasetname"` (uses currently-logged-in Hugging Face user's namespace),
103
+ or `None` (uses the same name as the Space but with the `"_dataset"`
104
+ suffix). If the Dataset does not exist, it will be created. If the Dataset
105
+ already exists, the project will be appended to it.
106
+ config (`dict`, *optional*):
107
+ A dictionary of configuration options. Provided for compatibility with
108
+ `wandb.init()`.
109
+ resume (`str`, *optional*, defaults to `"never"`):
110
+ Controls how to handle resuming a run. Can be one of:
111
+
112
+ - `"must"`: Must resume the run with the given name, raises error if run
113
+ doesn't exist
114
+ - `"allow"`: Resume the run if it exists, otherwise create a new run
115
+ - `"never"`: Never resume a run, always create a new one
116
+ private (`bool`, *optional*):
117
+ Whether to make the Space private. If None (default), the repo will be
118
+ public unless the organization's default is private. This value is ignored
119
+ if the repo already exists.
120
+ settings (`Any`, *optional*):
121
+ Not used. Provided for compatibility with `wandb.init()`.
122
+ embed (`bool`, *optional*, defaults to `True`):
123
+ If running inside a jupyter/Colab notebook, whether the dashboard should
124
+ automatically be embedded in the cell when trackio.init() is called.
125
+
126
+ Returns:
127
+ `Run`: A [`Run`] object that can be used to log metrics and finish the run.
128
+ """
129
+ if settings is not None:
130
+ warnings.warn(
131
+ "* 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."
132
+ )
133
+
134
+ if space_id is None and dataset_id is not None:
135
+ raise ValueError("Must provide a `space_id` when `dataset_id` is provided.")
136
+ space_id, dataset_id = utils.preprocess_space_and_dataset_ids(space_id, dataset_id)
137
+ url = context_vars.current_server.get()
138
+ share_url = context_vars.current_share_server.get()
139
+
140
+ if url is None:
141
+ if space_id is None:
142
+ _, url, share_url = demo.launch(
143
+ show_api=False,
144
+ inline=False,
145
+ quiet=True,
146
+ prevent_thread_lock=True,
147
+ show_error=True,
148
+ favicon_path=TRACKIO_LOGO_DIR / "trackio_logo_light.png",
149
+ allowed_paths=[TRACKIO_LOGO_DIR, TRACKIO_DIR],
150
+ )
151
+ else:
152
+ url = space_id
153
+ share_url = None
154
+ context_vars.current_server.set(url)
155
+ context_vars.current_share_server.set(share_url)
156
+ if (
157
+ context_vars.current_project.get() is None
158
+ or context_vars.current_project.get() != project
159
+ ):
160
+ print(f"* Trackio project initialized: {project}")
161
+
162
+ if dataset_id is not None:
163
+ os.environ["TRACKIO_DATASET_ID"] = dataset_id
164
+ print(
165
+ f"* Trackio metrics will be synced to Hugging Face Dataset: {dataset_id}"
166
+ )
167
+ if space_id is None:
168
+ print(f"* Trackio metrics logged to: {TRACKIO_DIR}")
169
+ if utils.is_in_notebook() and embed:
170
+ base_url = share_url + "/" if share_url else url
171
+ full_url = utils.get_full_url(
172
+ base_url, project=project, write_token=demo.write_token
173
+ )
174
+ utils.embed_url_in_notebook(full_url)
175
+ else:
176
+ utils.print_dashboard_instructions(project)
177
+ else:
178
+ deploy.create_space_if_not_exists(
179
+ space_id, space_storage, dataset_id, private
180
+ )
181
+ user_name, space_name = space_id.split("/")
182
+ space_url = deploy.SPACE_HOST_URL.format(
183
+ user_name=user_name, space_name=space_name
184
+ )
185
+ print(f"* View dashboard by going to: {space_url}")
186
+ if utils.is_in_notebook() and embed:
187
+ utils.embed_url_in_notebook(space_url)
188
+ context_vars.current_project.set(project)
189
+
190
+ client = None
191
+ if not space_id:
192
+ client = Client(url, verbose=False)
193
+
194
+ if resume == "must":
195
+ if name is None:
196
+ raise ValueError("Must provide a run name when resume='must'")
197
+ if name not in SQLiteStorage.get_runs(project):
198
+ raise ValueError(f"Run '{name}' does not exist in project '{project}'")
199
+ resumed = True
200
+ elif resume == "allow":
201
+ resumed = name is not None and name in SQLiteStorage.get_runs(project)
202
+ elif resume == "never":
203
+ if name is not None and name in SQLiteStorage.get_runs(project):
204
+ warnings.warn(
205
+ f"* Warning: resume='never' but a run '{name}' already exists in "
206
+ f"project '{project}'. Generating a new name and instead. If you want "
207
+ "to resume this run, call init() with resume='must' or resume='allow'."
208
+ )
209
+ name = None
210
+ resumed = False
211
+ else:
212
+ raise ValueError("resume must be one of: 'must', 'allow', or 'never'")
213
+
214
+ run = Run(
215
+ url=url,
216
+ project=project,
217
+ client=client,
218
+ name=name,
219
+ group=group,
220
+ config=config,
221
+ space_id=space_id,
222
+ )
223
+
224
+ if resumed:
225
+ print(f"* Resumed existing run: {run.name}")
226
+ else:
227
+ print(f"* Created new run: {run.name}")
228
+
229
+ context_vars.current_run.set(run)
230
+ globals()["config"] = run.config
231
+ return run
232
+
233
+
234
+ def log(metrics: dict, step: int | None = None) -> None:
235
+ """
236
+ Logs metrics to the current run.
237
+
238
+ Args:
239
+ metrics (`dict`):
240
+ A dictionary of metrics to log.
241
+ step (`int`, *optional*):
242
+ The step number. If not provided, the step will be incremented
243
+ automatically.
244
+ """
245
+ run = context_vars.current_run.get()
246
+ if run is None:
247
+ raise RuntimeError("Call trackio.init() before trackio.log().")
248
+ run.log(
249
+ metrics=metrics,
250
+ step=step,
251
+ )
252
+
253
+
254
+ def finish():
255
+ """
256
+ Finishes the current run.
257
+ """
258
+ run = context_vars.current_run.get()
259
+ if run is None:
260
+ raise RuntimeError("Call trackio.init() before trackio.finish().")
261
+ run.finish()
262
+
263
+
264
+ def show(
265
+ project: str | None = None,
266
+ theme: str | ThemeClass | None = None,
267
+ mcp_server: bool | None = None,
268
+ ):
269
+ """
270
+ Launches the Trackio dashboard.
271
+
272
+ Args:
273
+ project (`str`, *optional*):
274
+ The name of the project whose runs to show. If not provided, all projects
275
+ will be shown and the user can select one.
276
+ theme (`str` or `ThemeClass`, *optional*):
277
+ A Gradio Theme to use for the dashboard instead of the default Gradio theme,
278
+ can be a built-in theme (e.g. `'soft'`, `'citrus'`), a theme from the Hub
279
+ (e.g. `"gstaff/xkcd"`), or a custom Theme class. If not provided, the
280
+ `TRACKIO_THEME` environment variable will be used, or if that is not set, the
281
+ default Gradio theme will be used.
282
+ mcp_server (`bool`, *optional*):
283
+ If `True`, the Trackio dashboard will be set up as an MCP server and certain
284
+ functions will be added as MCP tools. If `None` (default behavior), then the
285
+ `GRADIO_MCP_SERVER` environment variable will be used to determine if the
286
+ MCP server should be enabled (which is `"True"` on Hugging Face Spaces).
287
+ """
288
+ theme = theme or os.environ.get("TRACKIO_THEME", DEFAULT_THEME)
289
+
290
+ if theme != DEFAULT_THEME:
291
+ # TODO: It's a little hacky to reproduce this theme-setting logic from Gradio Blocks,
292
+ # but in Gradio 6.0, the theme will be set in `launch()` instead, which means that we
293
+ # will be able to remove this code.
294
+ if isinstance(theme, str):
295
+ if theme.lower() in BUILT_IN_THEMES:
296
+ theme = BUILT_IN_THEMES[theme.lower()]
297
+ else:
298
+ try:
299
+ theme = ThemeClass.from_hub(theme)
300
+ except Exception as e:
301
+ warnings.warn(f"Cannot load {theme}. Caught Exception: {str(e)}")
302
+ theme = DefaultTheme()
303
+ if not isinstance(theme, ThemeClass):
304
+ warnings.warn("Theme should be a class loaded from gradio.themes")
305
+ theme = DefaultTheme()
306
+ demo.theme: ThemeClass = theme
307
+ demo.theme_css = theme._get_theme_css()
308
+ demo.stylesheets = theme._stylesheets
309
+ theme_hasher = hashlib.sha256()
310
+ theme_hasher.update(demo.theme_css.encode("utf-8"))
311
+ demo.theme_hash = theme_hasher.hexdigest()
312
+
313
+ _mcp_server = (
314
+ mcp_server
315
+ if mcp_server is not None
316
+ else os.environ.get("GRADIO_MCP_SERVER", "False") == "True"
317
+ )
318
+
319
+ _, url, share_url = demo.launch(
320
+ show_api=_mcp_server,
321
+ quiet=True,
322
+ inline=False,
323
+ prevent_thread_lock=True,
324
+ favicon_path=TRACKIO_LOGO_DIR / "trackio_logo_light.png",
325
+ allowed_paths=[TRACKIO_LOGO_DIR, TRACKIO_DIR],
326
+ mcp_server=_mcp_server,
327
+ )
328
+
329
+ base_url = share_url + "/" if share_url else url
330
+ full_url = utils.get_full_url(
331
+ base_url, project=project, write_token=demo.write_token
332
+ )
333
+
334
+ if not utils.is_in_notebook():
335
+ print(f"* Trackio UI launched at: {full_url}")
336
+ webbrowser.open(full_url)
337
+ utils.block_main_thread_until_keyboard_interrupt()
338
+ else:
339
+ utils.embed_url_in_notebook(full_url)
__pycache__/__init__.cpython-312.pyc ADDED
Binary file (14.8 kB). View file
 
__pycache__/cli.cpython-312.pyc ADDED
Binary file (1.73 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 (10.3 kB). View file
 
__pycache__/dummy_commit_scheduler.cpython-312.pyc ADDED
Binary file (1.03 kB). View file
 
__pycache__/histogram.cpython-312.pyc ADDED
Binary file (2.98 kB). View file
 
__pycache__/imports.cpython-312.pyc ADDED
Binary file (13.2 kB). View file
 
__pycache__/run.cpython-312.pyc ADDED
Binary file (9.3 kB). View file
 
__pycache__/sqlite_storage.cpython-312.pyc ADDED
Binary file (31.4 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 (27.7 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,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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="default",
20
+ help="A Gradio Theme to use for the dashboard instead of the default, can be a built-in theme (e.g. 'soft', 'citrus'), or a theme from the Hub (e.g. 'gstaff/xkcd').",
21
+ )
22
+ ui_parser.add_argument(
23
+ "--mcp-server",
24
+ action="store_true",
25
+ help="Enable MCP server functionality. The Trackio dashboard will be set up as an MCP server and certain functions will be exposed as MCP tools.",
26
+ )
27
+
28
+ args = parser.parse_args()
29
+
30
+ if args.command == "show":
31
+ show(args.project, args.theme, args.mcp_server)
32
+ else:
33
+ parser.print_help()
34
+
35
+
36
+ if __name__ == "__main__":
37
+ 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,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ plotly>=6.0.0,<7.0.0"""
104
+ else:
105
+ requirements_content = f"""pyarrow>=21.0
106
+ trackio=={trackio.__version__}
107
+ plotly>=6.0.0,<7.0.0"""
108
+
109
+ requirements_buffer = io.BytesIO(requirements_content.encode("utf-8"))
110
+ hf_api.upload_file(
111
+ path_or_fileobj=requirements_buffer,
112
+ path_in_repo="requirements.txt",
113
+ repo_id=space_id,
114
+ repo_type="space",
115
+ )
116
+
117
+ huggingface_hub.utils.disable_progress_bars()
118
+
119
+ if is_source_install:
120
+ hf_api.upload_folder(
121
+ repo_id=space_id,
122
+ repo_type="space",
123
+ folder_path=trackio_path,
124
+ ignore_patterns=["README.md"],
125
+ )
126
+ else:
127
+ app_file_content = """import trackio
128
+ trackio.show()"""
129
+ app_file_buffer = io.BytesIO(app_file_content.encode("utf-8"))
130
+ hf_api.upload_file(
131
+ path_or_fileobj=app_file_buffer,
132
+ path_in_repo="ui/main.py",
133
+ repo_id=space_id,
134
+ repo_type="space",
135
+ )
136
+
137
+ if hf_token := huggingface_hub.utils.get_token():
138
+ huggingface_hub.add_space_secret(space_id, "HF_TOKEN", hf_token)
139
+ if dataset_id is not None:
140
+ huggingface_hub.add_space_variable(space_id, "TRACKIO_DATASET_ID", dataset_id)
141
+
142
+ if logo_light_url := os.environ.get("TRACKIO_LOGO_LIGHT_URL"):
143
+ huggingface_hub.add_space_variable(
144
+ space_id, "TRACKIO_LOGO_LIGHT_URL", logo_light_url
145
+ )
146
+ if logo_dark_url := os.environ.get("TRACKIO_LOGO_DARK_URL"):
147
+ huggingface_hub.add_space_variable(
148
+ space_id, "TRACKIO_LOGO_DARK_URL", logo_dark_url
149
+ )
150
+
151
+ if plot_order := os.environ.get("TRACKIO_PLOT_ORDER"):
152
+ huggingface_hub.add_space_variable(space_id, "TRACKIO_PLOT_ORDER", plot_order)
153
+
154
+ if theme := os.environ.get("TRACKIO_THEME"):
155
+ huggingface_hub.add_space_variable(space_id, "TRACKIO_THEME", theme)
156
+
157
+
158
+ def create_space_if_not_exists(
159
+ space_id: str,
160
+ space_storage: huggingface_hub.SpaceStorage | None = None,
161
+ dataset_id: str | None = None,
162
+ private: bool | None = None,
163
+ ) -> None:
164
+ """
165
+ 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.
166
+
167
+ Args:
168
+ space_id: The ID of the Space to create.
169
+ dataset_id: The ID of the Dataset to add to the Space.
170
+ private: Whether to make the Space private. If None (default), the repo will be
171
+ public unless the organization's default is private. This value is ignored if
172
+ the repo already exists.
173
+ """
174
+ if "/" not in space_id:
175
+ raise ValueError(
176
+ f"Invalid space ID: {space_id}. Must be in the format: username/reponame or orgname/reponame."
177
+ )
178
+ if dataset_id is not None and "/" not in dataset_id:
179
+ raise ValueError(
180
+ f"Invalid dataset ID: {dataset_id}. Must be in the format: username/datasetname or orgname/datasetname."
181
+ )
182
+ try:
183
+ huggingface_hub.repo_info(space_id, repo_type="space")
184
+ print(f"* Found existing space: {SPACE_URL.format(space_id=space_id)}")
185
+ if dataset_id is not None:
186
+ huggingface_hub.add_space_variable(
187
+ space_id, "TRACKIO_DATASET_ID", dataset_id
188
+ )
189
+ if logo_light_url := os.environ.get("TRACKIO_LOGO_LIGHT_URL"):
190
+ huggingface_hub.add_space_variable(
191
+ space_id, "TRACKIO_LOGO_LIGHT_URL", logo_light_url
192
+ )
193
+ if logo_dark_url := os.environ.get("TRACKIO_LOGO_DARK_URL"):
194
+ huggingface_hub.add_space_variable(
195
+ space_id, "TRACKIO_LOGO_DARK_URL", logo_dark_url
196
+ )
197
+
198
+ if plot_order := os.environ.get("TRACKIO_PLOT_ORDER"):
199
+ huggingface_hub.add_space_variable(
200
+ space_id, "TRACKIO_PLOT_ORDER", plot_order
201
+ )
202
+
203
+ if theme := os.environ.get("TRACKIO_THEME"):
204
+ huggingface_hub.add_space_variable(space_id, "TRACKIO_THEME", theme)
205
+ return
206
+ except RepositoryNotFoundError:
207
+ pass
208
+ except HTTPError as e:
209
+ if e.response.status_code in [401, 403]: # unauthorized or forbidden
210
+ print("Need 'write' access token to create a Spaces repo.")
211
+ huggingface_hub.login(add_to_git_credential=False)
212
+ huggingface_hub.add_space_variable(
213
+ space_id, "TRACKIO_DATASET_ID", dataset_id
214
+ )
215
+ else:
216
+ raise ValueError(f"Failed to create Space: {e}")
217
+
218
+ print(f"* Creating new space: {SPACE_URL.format(space_id=space_id)}")
219
+ deploy_as_space(space_id, space_storage, dataset_id, private)
220
+
221
+
222
+ def wait_until_space_exists(
223
+ space_id: str,
224
+ ) -> None:
225
+ """
226
+ Blocks the current thread until the space exists.
227
+ May raise a TimeoutError if this takes quite a while.
228
+
229
+ Args:
230
+ space_id: The ID of the Space to wait for.
231
+ """
232
+ delay = 1
233
+ for _ in range(10):
234
+ try:
235
+ Client(space_id, verbose=False)
236
+ return
237
+ except (ReadTimeout, ValueError):
238
+ time.sleep(delay)
239
+ delay = min(delay * 2, 30)
240
+ raise TimeoutError("Waiting for space to exist took longer than expected")
241
+
242
+
243
+ def upload_db_to_space(project: str, space_id: str) -> None:
244
+ """
245
+ Uploads the database of a local Trackio project to a Hugging Face Space.
246
+
247
+ Args:
248
+ project: The name of the project to upload.
249
+ space_id: The ID of the Space to upload to.
250
+ """
251
+ db_path = SQLiteStorage.get_project_db_path(project)
252
+ client = Client(space_id, verbose=False)
253
+ client.predict(
254
+ api_name="/upload_db_to_space",
255
+ project=project,
256
+ uploaded_db=handle_file(db_path),
257
+ hf_token=huggingface_hub.utils.get_token(),
258
+ )
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()
histogram.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ import numpy as np
4
+
5
+
6
+ class Histogram:
7
+ """
8
+ Histogram data type for Trackio, compatible with wandb.Histogram.
9
+
10
+ Example:
11
+ ```python
12
+ import trackio
13
+ import numpy as np
14
+
15
+ # Create histogram from sequence
16
+ data = np.random.randn(1000)
17
+ trackio.log({"distribution": trackio.Histogram(data)})
18
+
19
+ # Create histogram from numpy histogram
20
+ hist, bins = np.histogram(data, bins=30)
21
+ trackio.log({"distribution": trackio.Histogram(np_histogram=(hist, bins))})
22
+
23
+ # Specify custom number of bins
24
+ trackio.log({"distribution": trackio.Histogram(data, num_bins=50)})
25
+ ```
26
+
27
+ Args:
28
+ sequence: Optional sequence of values to create histogram from
29
+ np_histogram: Optional pre-computed numpy histogram (hist, bins) tuple
30
+ num_bins: Number of bins for the histogram (default 64, max 512)
31
+ """
32
+
33
+ TYPE = "trackio.histogram"
34
+
35
+ def __init__(
36
+ self,
37
+ sequence: Any = None,
38
+ np_histogram: tuple | None = None,
39
+ num_bins: int = 64,
40
+ ):
41
+ if sequence is None and np_histogram is None:
42
+ raise ValueError("Must provide either sequence or np_histogram")
43
+
44
+ if sequence is not None and np_histogram is not None:
45
+ raise ValueError("Cannot provide both sequence and np_histogram")
46
+
47
+ num_bins = min(num_bins, 512)
48
+
49
+ if np_histogram is not None:
50
+ self.histogram, self.bins = np_histogram
51
+ self.histogram = np.asarray(self.histogram)
52
+ self.bins = np.asarray(self.bins)
53
+ else:
54
+ data = np.asarray(sequence).flatten()
55
+ data = data[np.isfinite(data)]
56
+ if len(data) == 0:
57
+ self.histogram = np.array([])
58
+ self.bins = np.array([])
59
+ else:
60
+ self.histogram, self.bins = np.histogram(data, bins=num_bins)
61
+
62
+ def _to_dict(self) -> dict:
63
+ """Convert histogram to dictionary for storage."""
64
+ return {
65
+ "_type": self.TYPE,
66
+ "bins": self.bins.tolist(),
67
+ "values": self.histogram.tolist(),
68
+ }
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/__init__.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Media module for Trackio.
3
+
4
+ This module contains all media-related functionality including:
5
+ - TrackioImage, TrackioVideo, TrackioAudio classes
6
+ - Video writing utilities
7
+ - Audio conversion utilities
8
+ """
9
+
10
+ try:
11
+ from trackio.media.audio_writer import write_audio
12
+ from trackio.media.file_storage import FileStorage
13
+ from trackio.media.media import (
14
+ TrackioAudio,
15
+ TrackioImage,
16
+ TrackioMedia,
17
+ TrackioVideo,
18
+ )
19
+ from trackio.media.video_writer import write_video
20
+ except ImportError:
21
+ from media.audio_writer import write_audio
22
+ from media.file_storage import FileStorage
23
+ from media.media import TrackioAudio, TrackioImage, TrackioMedia, TrackioVideo
24
+ from media.video_writer import write_video
25
+
26
+ __all__ = [
27
+ "TrackioMedia",
28
+ "TrackioImage",
29
+ "TrackioVideo",
30
+ "TrackioAudio",
31
+ "FileStorage",
32
+ "write_video",
33
+ "write_audio",
34
+ ]
media/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (989 Bytes). View file
 
media/__pycache__/audio_writer.cpython-312.pyc ADDED
Binary file (6.82 kB). View file
 
media/__pycache__/file_storage.cpython-312.pyc ADDED
Binary file (1.65 kB). View file
 
media/__pycache__/media.cpython-312.pyc ADDED
Binary file (18.7 kB). View file
 
media/__pycache__/utils.cpython-312.pyc ADDED
Binary file (1.36 kB). View file
 
media/__pycache__/video_writer.cpython-312.pyc ADDED
Binary file (4.42 kB). View file
 
media/audio_writer.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ from pathlib import Path
3
+ from typing import Literal
4
+
5
+ import numpy as np
6
+
7
+ try: # absolute imports when installed
8
+ from trackio.media.utils import check_ffmpeg_installed, check_path
9
+ except ImportError: # relative imports for local execution on Spaces
10
+ from media.utils import check_ffmpeg_installed, check_path
11
+
12
+ # Try to import pydub, but make it optional
13
+ try:
14
+ from pydub import AudioSegment
15
+
16
+ PYDUB_AVAILABLE = True
17
+ except ImportError:
18
+ PYDUB_AVAILABLE = False
19
+ AudioSegment = None
20
+
21
+ SUPPORTED_FORMATS = ["wav", "mp3"]
22
+ AudioFormatType = Literal["wav", "mp3"]
23
+
24
+
25
+ def ensure_int16_pcm(data: np.ndarray) -> np.ndarray:
26
+ """
27
+ Convert input audio array to contiguous int16 PCM.
28
+ Peak normalization is applied to floating inputs.
29
+ """
30
+ arr = np.asarray(data)
31
+ if arr.ndim not in (1, 2):
32
+ raise ValueError("Audio data must be 1D (mono) or 2D ([samples, channels])")
33
+
34
+ if arr.dtype != np.int16:
35
+ warnings.warn(
36
+ f"Converting {arr.dtype} audio to int16 PCM; pass int16 to avoid conversion.",
37
+ stacklevel=2,
38
+ )
39
+
40
+ arr = np.nan_to_num(arr, copy=False)
41
+
42
+ # Floating types: normalize to peak 1.0, then scale to int16
43
+ if np.issubdtype(arr.dtype, np.floating):
44
+ max_abs = float(np.max(np.abs(arr))) if arr.size else 0.0
45
+ if max_abs > 0.0:
46
+ arr = arr / max_abs
47
+ out = (arr * 32767.0).clip(-32768, 32767).astype(np.int16, copy=False)
48
+ return np.ascontiguousarray(out)
49
+
50
+ converters: dict[np.dtype, callable] = {
51
+ np.dtype(np.int16): lambda a: a,
52
+ np.dtype(np.int32): lambda a: (
53
+ (a.astype(np.int32) // 65536).astype(np.int16, copy=False)
54
+ ),
55
+ np.dtype(np.uint16): lambda a: (
56
+ (a.astype(np.int32) - 32768).astype(np.int16, copy=False)
57
+ ),
58
+ np.dtype(np.uint8): lambda a: (
59
+ (a.astype(np.int32) * 257 - 32768).astype(np.int16, copy=False)
60
+ ),
61
+ np.dtype(np.int8): lambda a: (
62
+ (a.astype(np.int32) * 256).astype(np.int16, copy=False)
63
+ ),
64
+ }
65
+
66
+ conv = converters.get(arr.dtype)
67
+ if conv is not None:
68
+ out = conv(arr)
69
+ return np.ascontiguousarray(out)
70
+ raise TypeError(f"Unsupported audio dtype: {arr.dtype}")
71
+
72
+
73
+ def write_audio(
74
+ data: np.ndarray,
75
+ sample_rate: int,
76
+ filename: str | Path,
77
+ format: AudioFormatType = "wav",
78
+ ) -> None:
79
+ if not isinstance(sample_rate, int) or sample_rate <= 0:
80
+ raise ValueError(f"Invalid sample_rate: {sample_rate}")
81
+ if format not in SUPPORTED_FORMATS:
82
+ raise ValueError(
83
+ f"Unsupported format: {format}. Supported: {SUPPORTED_FORMATS}"
84
+ )
85
+
86
+ check_path(filename)
87
+
88
+ pcm = ensure_int16_pcm(data)
89
+
90
+ # If pydub is missing, allow WAV fallback, otherwise require pydub
91
+ if not PYDUB_AVAILABLE:
92
+ if format == "wav":
93
+ write_wav_simple(filename, pcm, sample_rate)
94
+ return
95
+ raise ImportError(
96
+ "pydub is required for non-WAV formats. Install with: pip install pydub"
97
+ )
98
+
99
+ if format != "wav":
100
+ check_ffmpeg_installed()
101
+
102
+ channels = 1 if pcm.ndim == 1 else pcm.shape[1]
103
+ audio = AudioSegment(
104
+ pcm.tobytes(),
105
+ frame_rate=sample_rate,
106
+ sample_width=2, # int16
107
+ channels=channels,
108
+ )
109
+
110
+ file = audio.export(str(filename), format=format)
111
+ file.close()
112
+
113
+
114
+ def write_wav_simple(
115
+ file_path: str | Path, data: np.ndarray, sample_rate: int = 44100
116
+ ) -> None:
117
+ """Fallback for basic WAV export when pydub is not available."""
118
+ import wave
119
+
120
+ pcm = ensure_int16_pcm(data)
121
+ if pcm.ndim > 2:
122
+ raise ValueError("Audio data must be 1D (mono) or 2D (stereo)")
123
+
124
+ with wave.open(str(file_path), "wb") as wav_file:
125
+ wav_file.setnchannels(1 if pcm.ndim == 1 else pcm.shape[1])
126
+ wav_file.setsampwidth(2) # 16-bit = 2 bytes
127
+ wav_file.setframerate(sample_rate)
128
+ wav_file.writeframes(pcm.tobytes())
media/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
media/media.py ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.media.audio_writer import AudioFormatType, write_audio
13
+ from trackio.media.file_storage import FileStorage
14
+ from trackio.media.video_writer import write_video
15
+ from trackio.utils import MEDIA_DIR
16
+ except ImportError: # relative imports for local execution on Spaces
17
+ from media.audio_writer import AudioFormatType, write_audio
18
+ from media.file_storage import FileStorage
19
+ from media.video_writer import write_video
20
+ from utils import MEDIA_DIR
21
+
22
+
23
+ class TrackioMedia(ABC):
24
+ """
25
+ Abstract base class for Trackio media objects
26
+ Provides shared functionality for file handling and serialization.
27
+ """
28
+
29
+ TYPE: str
30
+
31
+ def __init_subclass__(cls, **kwargs):
32
+ """Ensure subclasses define the TYPE attribute."""
33
+ super().__init_subclass__(**kwargs)
34
+ if not hasattr(cls, "TYPE") or cls.TYPE is None:
35
+ raise TypeError(f"Class {cls.__name__} must define TYPE attribute")
36
+
37
+ def __init__(self, value, caption: str | None = None):
38
+ self.caption = caption
39
+ self._value = value
40
+ self._file_path: Path | None = None
41
+
42
+ if isinstance(self._value, str | Path):
43
+ if not os.path.isfile(self._value):
44
+ raise ValueError(f"File not found: {self._value}")
45
+
46
+ def _file_extension(self) -> str:
47
+ if self._file_path:
48
+ return self._file_path.suffix[1:].lower()
49
+ if isinstance(self._value, str | Path):
50
+ path = Path(self._value)
51
+ return path.suffix[1:].lower()
52
+ if hasattr(self, "_format") and self._format:
53
+ return self._format
54
+ return "unknown"
55
+
56
+ def _get_relative_file_path(self) -> Path | None:
57
+ return self._file_path
58
+
59
+ def _get_absolute_file_path(self) -> Path | None:
60
+ if self._file_path:
61
+ return MEDIA_DIR / self._file_path
62
+ return None
63
+
64
+ def _save(self, project: str, run: str, step: int = 0):
65
+ if self._file_path:
66
+ return
67
+
68
+ media_dir = FileStorage.init_project_media_path(project, run, step)
69
+ filename = f"{uuid.uuid4()}.{self._file_extension()}"
70
+ file_path = media_dir / filename
71
+
72
+ self._save_media(file_path)
73
+ self._file_path = file_path.relative_to(MEDIA_DIR)
74
+
75
+ @abstractmethod
76
+ def _save_media(self, file_path: Path):
77
+ """
78
+ Performs the actual media saving logic.
79
+ """
80
+ pass
81
+
82
+ def _to_dict(self) -> dict:
83
+ if not self._file_path:
84
+ raise ValueError("Media must be saved to file before serialization")
85
+ return {
86
+ "_type": self.TYPE,
87
+ "file_path": str(self._get_relative_file_path()),
88
+ "caption": self.caption,
89
+ }
90
+
91
+
92
+ TrackioImageSourceType = str | Path | np.ndarray | PILImage.Image
93
+
94
+
95
+ class TrackioImage(TrackioMedia):
96
+ """
97
+ Initializes an Image object.
98
+
99
+ Example:
100
+ ```python
101
+ import trackio
102
+ import numpy as np
103
+ from PIL import Image
104
+
105
+ # Create an image from numpy array
106
+ image_data = np.random.randint(0, 255, (64, 64, 3), dtype=np.uint8)
107
+ image = trackio.Image(image_data, caption="Random image")
108
+ trackio.log({"my_image": image})
109
+
110
+ # Create an image from PIL Image
111
+ pil_image = Image.new('RGB', (100, 100), color='red')
112
+ image = trackio.Image(pil_image, caption="Red square")
113
+ trackio.log({"red_image": image})
114
+
115
+ # Create an image from file path
116
+ image = trackio.Image("path/to/image.jpg", caption="Photo from file")
117
+ trackio.log({"file_image": image})
118
+ ```
119
+
120
+ Args:
121
+ value (`str`, `Path`, `numpy.ndarray`, or `PIL.Image`, *optional*):
122
+ A path to an image, a PIL Image, or a numpy array of shape (height, width, channels).
123
+ If numpy array, should be of type `np.uint8` with RGB values in the range `[0, 255]`.
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 not isinstance(self._value, TrackioImageSourceType):
135
+ raise ValueError(
136
+ f"Invalid value type, expected {TrackioImageSourceType}, got {type(self._value)}"
137
+ )
138
+ if isinstance(self._value, np.ndarray) and self._value.dtype != np.uint8:
139
+ raise ValueError(
140
+ f"Invalid value dtype, expected np.uint8, got {self._value.dtype}"
141
+ )
142
+ if (
143
+ isinstance(self._value, np.ndarray | PILImage.Image)
144
+ and self._format is None
145
+ ):
146
+ self._format = "png"
147
+
148
+ def _as_pil(self) -> PILImage.Image | None:
149
+ try:
150
+ if isinstance(self._value, np.ndarray):
151
+ arr = np.asarray(self._value).astype("uint8")
152
+ return PILImage.fromarray(arr).convert("RGBA")
153
+ if isinstance(self._value, PILImage.Image):
154
+ return self._value.convert("RGBA")
155
+ except Exception as e:
156
+ raise ValueError(f"Failed to process image data: {self._value}") from e
157
+ return None
158
+
159
+ def _save_media(self, file_path: Path):
160
+ if pil := self._as_pil():
161
+ pil.save(file_path, format=self._format)
162
+ elif isinstance(self._value, str | Path):
163
+ if os.path.isfile(self._value):
164
+ shutil.copy(self._value, file_path)
165
+ else:
166
+ raise ValueError(f"File not found: {self._value}")
167
+
168
+
169
+ TrackioVideoSourceType = str | Path | np.ndarray
170
+ TrackioVideoFormatType = Literal["gif", "mp4", "webm"]
171
+
172
+
173
+ class TrackioVideo(TrackioMedia):
174
+ """
175
+ Initializes a Video object.
176
+
177
+ Example:
178
+ ```python
179
+ import trackio
180
+ import numpy as np
181
+
182
+ # Create a simple video from numpy array
183
+ frames = np.random.randint(0, 255, (10, 3, 64, 64), dtype=np.uint8)
184
+ video = trackio.Video(frames, caption="Random video", fps=30)
185
+
186
+ # Create a batch of videos
187
+ batch_frames = np.random.randint(0, 255, (3, 10, 3, 64, 64), dtype=np.uint8)
188
+ batch_video = trackio.Video(batch_frames, caption="Batch of videos", fps=15)
189
+
190
+ # Create video from file path
191
+ video = trackio.Video("path/to/video.mp4", caption="Video from file")
192
+ ```
193
+
194
+ Args:
195
+ value (`str`, `Path`, or `numpy.ndarray`, *optional*):
196
+ A path to a video file, or a numpy array.
197
+ If numpy array, should be of type `np.uint8` with RGB values in the range `[0, 255]`.
198
+ It is expected to have shape of either (frames, channels, height, width) or (batch, frames, channels, height, width).
199
+ For the latter, the videos will be tiled into a grid.
200
+ caption (`str`, *optional*):
201
+ A string caption for the video.
202
+ fps (`int`, *optional*):
203
+ Frames per second for the video. Only used when value is an ndarray. Default is `24`.
204
+ format (`Literal["gif", "mp4", "webm"]`, *optional*):
205
+ Video format ("gif", "mp4", or "webm"). Only used when value is an ndarray. Default is "gif".
206
+ """
207
+
208
+ TYPE = "trackio.video"
209
+
210
+ def __init__(
211
+ self,
212
+ value: TrackioVideoSourceType,
213
+ caption: str | None = None,
214
+ fps: int | None = None,
215
+ format: TrackioVideoFormatType | None = None,
216
+ ):
217
+ super().__init__(value, caption)
218
+
219
+ if not isinstance(self._value, TrackioVideoSourceType):
220
+ raise ValueError(
221
+ f"Invalid value type, expected {TrackioVideoSourceType}, got {type(self._value)}"
222
+ )
223
+ if isinstance(self._value, np.ndarray):
224
+ if self._value.dtype != np.uint8:
225
+ raise ValueError(
226
+ f"Invalid value dtype, expected np.uint8, got {self._value.dtype}"
227
+ )
228
+ if format is None:
229
+ format = "gif"
230
+ if fps is None:
231
+ fps = 24
232
+ self._fps = fps
233
+ self._format = format
234
+
235
+ @property
236
+ def _codec(self) -> str:
237
+ match self._format:
238
+ case "gif":
239
+ return "gif"
240
+ case "mp4":
241
+ return "h264"
242
+ case "webm":
243
+ return "vp9"
244
+ case _:
245
+ raise ValueError(f"Unsupported format: {self._format}")
246
+
247
+ def _save_media(self, file_path: Path):
248
+ if isinstance(self._value, np.ndarray):
249
+ video = TrackioVideo._process_ndarray(self._value)
250
+ write_video(file_path, video, fps=self._fps, codec=self._codec)
251
+ elif isinstance(self._value, str | Path):
252
+ if os.path.isfile(self._value):
253
+ shutil.copy(self._value, file_path)
254
+ else:
255
+ raise ValueError(f"File not found: {self._value}")
256
+
257
+ @staticmethod
258
+ def _process_ndarray(value: np.ndarray) -> np.ndarray:
259
+ # Verify value is either 4D (single video) or 5D array (batched videos).
260
+ # Expected format: (frames, channels, height, width) or (batch, frames, channels, height, width)
261
+ if value.ndim < 4:
262
+ raise ValueError(
263
+ "Video requires at least 4 dimensions (frames, channels, height, width)"
264
+ )
265
+ if value.ndim > 5:
266
+ raise ValueError(
267
+ "Videos can have at most 5 dimensions (batch, frames, channels, height, width)"
268
+ )
269
+ if value.ndim == 4:
270
+ # Reshape to 5D with single batch: (1, frames, channels, height, width)
271
+ value = value[np.newaxis, ...]
272
+
273
+ value = TrackioVideo._tile_batched_videos(value)
274
+ return value
275
+
276
+ @staticmethod
277
+ def _tile_batched_videos(video: np.ndarray) -> np.ndarray:
278
+ """
279
+ Tiles a batch of videos into a grid of videos.
280
+
281
+ Input format: (batch, frames, channels, height, width) - original FCHW format
282
+ Output format: (frames, total_height, total_width, channels)
283
+ """
284
+ batch_size, frames, channels, height, width = video.shape
285
+
286
+ next_pow2 = 1 << (batch_size - 1).bit_length()
287
+ if batch_size != next_pow2:
288
+ pad_len = next_pow2 - batch_size
289
+ pad_shape = (pad_len, frames, channels, height, width)
290
+ padding = np.zeros(pad_shape, dtype=video.dtype)
291
+ video = np.concatenate((video, padding), axis=0)
292
+ batch_size = next_pow2
293
+
294
+ n_rows = 1 << ((batch_size.bit_length() - 1) // 2)
295
+ n_cols = batch_size // n_rows
296
+
297
+ # Reshape to grid layout: (n_rows, n_cols, frames, channels, height, width)
298
+ video = video.reshape(n_rows, n_cols, frames, channels, height, width)
299
+
300
+ # Rearrange dimensions to (frames, total_height, total_width, channels)
301
+ video = video.transpose(2, 0, 4, 1, 5, 3)
302
+ video = video.reshape(frames, n_rows * height, n_cols * width, channels)
303
+ return video
304
+
305
+
306
+ TrackioAudioSourceType = str | Path | np.ndarray
307
+
308
+
309
+ class TrackioAudio(TrackioMedia):
310
+ """
311
+ Initializes an Audio object.
312
+
313
+ Example:
314
+ ```python
315
+ import trackio
316
+ import numpy as np
317
+
318
+ # Generate a 1-second 440 Hz sine wave (mono)
319
+ sr = 16000
320
+ t = np.linspace(0, 1, sr, endpoint=False)
321
+ wave = 0.2 * np.sin(2 * np.pi * 440 * t)
322
+ audio = trackio.Audio(wave, caption="A4 sine", sample_rate=sr, format="wav")
323
+ trackio.log({"tone": audio})
324
+
325
+ # Stereo from numpy array (shape: samples, 2)
326
+ stereo = np.stack([wave, wave], axis=1)
327
+ audio = trackio.Audio(stereo, caption="Stereo", sample_rate=sr, format="mp3")
328
+ trackio.log({"stereo": audio})
329
+
330
+ # From an existing file
331
+ audio = trackio.Audio("path/to/audio.wav", caption="From file")
332
+ trackio.log({"file_audio": audio})
333
+ ```
334
+
335
+ Args:
336
+ value (`str`, `Path`, or `numpy.ndarray`, *optional*):
337
+ A path to an audio file, or a numpy array.
338
+ The array should be shaped `(samples,)` for mono or `(samples, 2)` for stereo.
339
+ Float arrays will be peak-normalized and converted to 16-bit PCM; integer arrays will be converted to 16-bit PCM as needed.
340
+ caption (`str`, *optional*):
341
+ A string caption for the audio.
342
+ sample_rate (`int`, *optional*):
343
+ Sample rate in Hz. Required when `value` is a numpy array.
344
+ format (`Literal["wav", "mp3"]`, *optional*):
345
+ Audio format used when `value` is a numpy array. Default is "wav".
346
+ """
347
+
348
+ TYPE = "trackio.audio"
349
+
350
+ def __init__(
351
+ self,
352
+ value: TrackioAudioSourceType,
353
+ caption: str | None = None,
354
+ sample_rate: int | None = None,
355
+ format: AudioFormatType | None = None,
356
+ ):
357
+ super().__init__(value, caption)
358
+ if isinstance(value, np.ndarray):
359
+ if sample_rate is None:
360
+ raise ValueError("Sample rate is required when value is an ndarray")
361
+ if format is None:
362
+ format = "wav"
363
+ self._format = format
364
+ self._sample_rate = sample_rate
365
+
366
+ def _save_media(self, file_path: Path):
367
+ if isinstance(self._value, np.ndarray):
368
+ write_audio(
369
+ data=self._value,
370
+ sample_rate=self._sample_rate,
371
+ filename=file_path,
372
+ format=self._format,
373
+ )
374
+ elif isinstance(self._value, str | Path):
375
+ if os.path.isfile(self._value):
376
+ shutil.copy(self._value, file_path)
377
+ else:
378
+ raise ValueError(f"File not found: {self._value}")
media/utils.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import shutil
2
+ from pathlib import Path
3
+
4
+
5
+ def check_path(file_path: str | Path) -> None:
6
+ """Raise an error if the parent directory does not exist."""
7
+ file_path = Path(file_path)
8
+ if not file_path.parent.exists():
9
+ try:
10
+ file_path.parent.mkdir(parents=True, exist_ok=True)
11
+ except OSError as e:
12
+ raise ValueError(
13
+ f"Failed to create parent directory {file_path.parent}: {e}"
14
+ )
15
+
16
+
17
+ def check_ffmpeg_installed() -> None:
18
+ """Raise an error if ffmpeg is not available on the system PATH."""
19
+ if shutil.which("ffmpeg") is None:
20
+ raise RuntimeError(
21
+ "ffmpeg is required to write video but was not found on your system. "
22
+ "Please install ffmpeg and ensure it is available on your PATH."
23
+ )
media/video_writer.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ from pathlib import Path
3
+ from typing import Literal
4
+
5
+ import numpy as np
6
+
7
+ try: # absolute imports when installed
8
+ from trackio.media.utils import check_ffmpeg_installed, check_path
9
+ except ImportError: # relative imports for local execution on Spaces
10
+ from media.utils import check_ffmpeg_installed, check_path
11
+
12
+ VideoCodec = Literal["h264", "vp9", "gif"]
13
+
14
+
15
+ def _check_array_format(video: np.ndarray) -> None:
16
+ """Raise an error if the array is not in the expected format."""
17
+ if not (video.ndim == 4 and video.shape[-1] == 3):
18
+ raise ValueError(
19
+ f"Expected RGB input shaped (F, H, W, 3), got {video.shape}. "
20
+ f"Input has {video.ndim} dimensions, expected 4."
21
+ )
22
+ if video.dtype != np.uint8:
23
+ raise TypeError(
24
+ f"Expected dtype=uint8, got {video.dtype}. "
25
+ "Please convert your video data to uint8 format."
26
+ )
27
+
28
+
29
+ def write_video(
30
+ file_path: str | Path, video: np.ndarray, fps: float, codec: VideoCodec
31
+ ) -> None:
32
+ """RGB uint8 only, shape (F, H, W, 3)."""
33
+ check_ffmpeg_installed()
34
+ check_path(file_path)
35
+
36
+ if codec not in {"h264", "vp9", "gif"}:
37
+ raise ValueError("Unsupported codec. Use h264, vp9, or gif.")
38
+
39
+ arr = np.asarray(video)
40
+ _check_array_format(arr)
41
+
42
+ frames = np.ascontiguousarray(arr)
43
+ _, height, width, _ = frames.shape
44
+ out_path = str(file_path)
45
+
46
+ cmd = [
47
+ "ffmpeg",
48
+ "-y",
49
+ "-f",
50
+ "rawvideo",
51
+ "-s",
52
+ f"{width}x{height}",
53
+ "-pix_fmt",
54
+ "rgb24",
55
+ "-r",
56
+ str(fps),
57
+ "-i",
58
+ "-",
59
+ "-an",
60
+ ]
61
+
62
+ if codec == "gif":
63
+ video_filter = "split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse"
64
+ cmd += [
65
+ "-vf",
66
+ video_filter,
67
+ "-loop",
68
+ "0",
69
+ ]
70
+ elif codec == "h264":
71
+ cmd += [
72
+ "-vcodec",
73
+ "libx264",
74
+ "-pix_fmt",
75
+ "yuv420p",
76
+ "-movflags",
77
+ "+faststart",
78
+ ]
79
+ elif codec == "vp9":
80
+ bpp = 0.08
81
+ bps = int(width * height * fps * bpp)
82
+ if bps >= 1_000_000:
83
+ bitrate = f"{round(bps / 1_000_000)}M"
84
+ elif bps >= 1_000:
85
+ bitrate = f"{round(bps / 1_000)}k"
86
+ else:
87
+ bitrate = str(max(bps, 1))
88
+ cmd += [
89
+ "-vcodec",
90
+ "libvpx-vp9",
91
+ "-b:v",
92
+ bitrate,
93
+ "-pix_fmt",
94
+ "yuv420p",
95
+ ]
96
+ cmd += [out_path]
97
+ proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
98
+ try:
99
+ for frame in frames:
100
+ proc.stdin.write(frame.tobytes())
101
+ finally:
102
+ if proc.stdin:
103
+ proc.stdin.close()
104
+ stderr = (
105
+ proc.stderr.read().decode("utf-8", errors="ignore") if proc.stderr else ""
106
+ )
107
+ ret = proc.wait()
108
+ if ret != 0:
109
+ raise RuntimeError(f"ffmpeg failed with code {ret}\n{stderr}")
package.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "name": "trackio",
3
+ "version": "0.7.0",
4
+ "description": "",
5
+ "python": "true"
6
+ }
py.typed ADDED
File without changes
run.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import threading
2
+ import time
3
+ import warnings
4
+ from datetime import datetime, timezone
5
+
6
+ import huggingface_hub
7
+ from gradio_client import Client, handle_file
8
+
9
+ from trackio import utils
10
+ from trackio.histogram import Histogram
11
+ from trackio.media import TrackioMedia
12
+ from trackio.sqlite_storage import SQLiteStorage
13
+ from trackio.table import Table
14
+ from trackio.typehints import LogEntry, UploadEntry
15
+
16
+ BATCH_SEND_INTERVAL = 0.5
17
+
18
+
19
+ class Run:
20
+ def __init__(
21
+ self,
22
+ url: str,
23
+ project: str,
24
+ client: Client | None,
25
+ name: str | None = None,
26
+ group: str | None = None,
27
+ config: dict | None = None,
28
+ space_id: str | None = None,
29
+ ):
30
+ self.url = url
31
+ self.project = project
32
+ self._client_lock = threading.Lock()
33
+ self._client_thread = None
34
+ self._client = client
35
+ self._space_id = space_id
36
+ self.name = name or utils.generate_readable_name(
37
+ SQLiteStorage.get_runs(project), space_id
38
+ )
39
+ self.group = group
40
+ self.config = utils.to_json_safe(config or {})
41
+
42
+ if isinstance(self.config, dict):
43
+ for key in self.config:
44
+ if key.startswith("_"):
45
+ raise ValueError(
46
+ f"Config key '{key}' is reserved (keys starting with '_' are reserved for internal use)"
47
+ )
48
+
49
+ self.config["_Username"] = self._get_username()
50
+ self.config["_Created"] = datetime.now(timezone.utc).isoformat()
51
+ self.config["_Group"] = self.group
52
+
53
+ self._queued_logs: list[LogEntry] = []
54
+ self._queued_uploads: list[UploadEntry] = []
55
+ self._stop_flag = threading.Event()
56
+ self._config_logged = False
57
+
58
+ self._client_thread = threading.Thread(target=self._init_client_background)
59
+ self._client_thread.daemon = True
60
+ self._client_thread.start()
61
+
62
+ def _get_username(self) -> str | None:
63
+ """Get the current HuggingFace username if logged in, otherwise None."""
64
+ try:
65
+ who = huggingface_hub.whoami()
66
+ return who["name"] if who else None
67
+ except Exception:
68
+ return None
69
+
70
+ def _batch_sender(self):
71
+ """Send batched logs every BATCH_SEND_INTERVAL."""
72
+ while not self._stop_flag.is_set() or len(self._queued_logs) > 0:
73
+ # If the stop flag has been set, then just quickly send all
74
+ # the logs and exit.
75
+ if not self._stop_flag.is_set():
76
+ time.sleep(BATCH_SEND_INTERVAL)
77
+
78
+ with self._client_lock:
79
+ if self._client is None:
80
+ return
81
+ if self._queued_logs:
82
+ logs_to_send = self._queued_logs.copy()
83
+ self._queued_logs.clear()
84
+ self._client.predict(
85
+ api_name="/bulk_log",
86
+ logs=logs_to_send,
87
+ hf_token=huggingface_hub.utils.get_token(),
88
+ )
89
+ if self._queued_uploads:
90
+ uploads_to_send = self._queued_uploads.copy()
91
+ self._queued_uploads.clear()
92
+ self._client.predict(
93
+ api_name="/bulk_upload_media",
94
+ uploads=uploads_to_send,
95
+ hf_token=huggingface_hub.utils.get_token(),
96
+ )
97
+
98
+ def _init_client_background(self):
99
+ if self._client is None:
100
+ fib = utils.fibo()
101
+ for sleep_coefficient in fib:
102
+ try:
103
+ client = Client(self.url, verbose=False)
104
+
105
+ with self._client_lock:
106
+ self._client = client
107
+ break
108
+ except Exception:
109
+ pass
110
+ if sleep_coefficient is not None:
111
+ time.sleep(0.1 * sleep_coefficient)
112
+
113
+ self._batch_sender()
114
+
115
+ def _process_media(self, metrics, step: int | None) -> dict:
116
+ """
117
+ Serialize media in metrics and upload to space if needed.
118
+ """
119
+ serializable_metrics = {}
120
+ if not step:
121
+ step = 0
122
+ for key, value in metrics.items():
123
+ if isinstance(value, TrackioMedia):
124
+ value._save(self.project, self.name, step)
125
+ serializable_metrics[key] = value._to_dict()
126
+ if self._space_id:
127
+ # Upload local media when deploying to space
128
+ upload_entry: UploadEntry = {
129
+ "project": self.project,
130
+ "run": self.name,
131
+ "step": step,
132
+ "uploaded_file": handle_file(value._get_absolute_file_path()),
133
+ }
134
+ with self._client_lock:
135
+ self._queued_uploads.append(upload_entry)
136
+ else:
137
+ serializable_metrics[key] = value
138
+ return serializable_metrics
139
+
140
+ @staticmethod
141
+ def _replace_tables(metrics):
142
+ for k, v in metrics.items():
143
+ if isinstance(v, (Table, Histogram)):
144
+ metrics[k] = v._to_dict()
145
+
146
+ def log(self, metrics: dict, step: int | None = None):
147
+ renamed_keys = []
148
+ new_metrics = {}
149
+
150
+ for k, v in metrics.items():
151
+ if k in utils.RESERVED_KEYS or k.startswith("__"):
152
+ new_key = f"__{k}"
153
+ renamed_keys.append(k)
154
+ new_metrics[new_key] = v
155
+ else:
156
+ new_metrics[k] = v
157
+
158
+ if renamed_keys:
159
+ warnings.warn(f"Reserved keys renamed: {renamed_keys} → '__{{key}}'")
160
+
161
+ metrics = new_metrics
162
+ Run._replace_tables(metrics)
163
+
164
+ metrics = self._process_media(metrics, step)
165
+ metrics = utils.serialize_values(metrics)
166
+
167
+ config_to_log = None
168
+ if not self._config_logged and self.config:
169
+ config_to_log = utils.to_json_safe(self.config)
170
+ self._config_logged = True
171
+
172
+ log_entry: LogEntry = {
173
+ "project": self.project,
174
+ "run": self.name,
175
+ "metrics": metrics,
176
+ "step": step,
177
+ "config": config_to_log,
178
+ }
179
+
180
+ with self._client_lock:
181
+ self._queued_logs.append(log_entry)
182
+
183
+ def finish(self):
184
+ """Cleanup when run is finished."""
185
+ self._stop_flag.set()
186
+
187
+ # Wait for the batch sender to finish before joining the client thread.
188
+ time.sleep(2 * BATCH_SEND_INTERVAL)
189
+
190
+ if self._client_thread is not None:
191
+ print("* Run finished. Uploading logs to Trackio (please wait...)")
192
+ self._client_thread.join()
sqlite_storage.py ADDED
@@ -0,0 +1,677 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import platform
3
+ import sqlite3
4
+ import time
5
+ from datetime import datetime
6
+ from pathlib import Path
7
+ from threading import Lock
8
+
9
+ try:
10
+ import fcntl
11
+ except ImportError: # fcntl is not available on Windows
12
+ fcntl = None
13
+
14
+ import huggingface_hub as hf
15
+ import orjson
16
+ import pandas as pd
17
+
18
+ try: # absolute imports when installed from PyPI
19
+ from trackio.commit_scheduler import CommitScheduler
20
+ from trackio.dummy_commit_scheduler import DummyCommitScheduler
21
+ from trackio.utils import (
22
+ TRACKIO_DIR,
23
+ deserialize_values,
24
+ serialize_values,
25
+ )
26
+ except ImportError: # relative imports when installed from source on Spaces
27
+ from commit_scheduler import CommitScheduler
28
+ from dummy_commit_scheduler import DummyCommitScheduler
29
+ from utils import TRACKIO_DIR, deserialize_values, serialize_values
30
+
31
+ DB_EXT = ".db"
32
+
33
+
34
+ class ProcessLock:
35
+ """A file-based lock that works across processes. Is a no-op on Windows."""
36
+
37
+ def __init__(self, lockfile_path: Path):
38
+ self.lockfile_path = lockfile_path
39
+ self.lockfile = None
40
+ self.is_windows = platform.system() == "Windows"
41
+
42
+ def __enter__(self):
43
+ """Acquire the lock with retry logic."""
44
+ if self.is_windows:
45
+ return self
46
+ self.lockfile_path.parent.mkdir(parents=True, exist_ok=True)
47
+ self.lockfile = open(self.lockfile_path, "w")
48
+
49
+ max_retries = 100
50
+ for attempt in range(max_retries):
51
+ try:
52
+ fcntl.flock(self.lockfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
53
+ return self
54
+ except IOError:
55
+ if attempt < max_retries - 1:
56
+ time.sleep(0.1)
57
+ else:
58
+ raise IOError("Could not acquire database lock after 10 seconds")
59
+
60
+ def __exit__(self, exc_type, exc_val, exc_tb):
61
+ """Release the lock."""
62
+ if self.is_windows:
63
+ return
64
+
65
+ if self.lockfile:
66
+ fcntl.flock(self.lockfile.fileno(), fcntl.LOCK_UN)
67
+ self.lockfile.close()
68
+
69
+
70
+ class SQLiteStorage:
71
+ _dataset_import_attempted = False
72
+ _current_scheduler: CommitScheduler | DummyCommitScheduler | None = None
73
+ _scheduler_lock = Lock()
74
+
75
+ @staticmethod
76
+ def _get_connection(db_path: Path) -> sqlite3.Connection:
77
+ conn = sqlite3.connect(str(db_path), timeout=30.0)
78
+ # Keep WAL for concurrency + performance on many small writes
79
+ conn.execute("PRAGMA journal_mode = WAL")
80
+ # ---- Minimal perf tweaks for many tiny transactions ----
81
+ # NORMAL = fsync at critical points only (safer than OFF, much faster than FULL)
82
+ conn.execute("PRAGMA synchronous = NORMAL")
83
+ # Keep temp data in memory to avoid disk hits during small writes
84
+ conn.execute("PRAGMA temp_store = MEMORY")
85
+ # Give SQLite a bit more room for cache (negative = KB, engine-managed)
86
+ conn.execute("PRAGMA cache_size = -20000")
87
+ # --------------------------------------------------------
88
+ conn.row_factory = sqlite3.Row
89
+ return conn
90
+
91
+ @staticmethod
92
+ def _get_process_lock(project: str) -> ProcessLock:
93
+ lockfile_path = TRACKIO_DIR / f"{project}.lock"
94
+ return ProcessLock(lockfile_path)
95
+
96
+ @staticmethod
97
+ def get_project_db_filename(project: str) -> str:
98
+ """Get the database filename for a specific project."""
99
+ safe_project_name = "".join(
100
+ c for c in project if c.isalnum() or c in ("-", "_")
101
+ ).rstrip()
102
+ if not safe_project_name:
103
+ safe_project_name = "default"
104
+ return f"{safe_project_name}{DB_EXT}"
105
+
106
+ @staticmethod
107
+ def get_project_db_path(project: str) -> Path:
108
+ """Get the database path for a specific project."""
109
+ filename = SQLiteStorage.get_project_db_filename(project)
110
+ return TRACKIO_DIR / filename
111
+
112
+ @staticmethod
113
+ def init_db(project: str) -> Path:
114
+ """
115
+ Initialize the SQLite database with required tables.
116
+ Returns the database path.
117
+ """
118
+ db_path = SQLiteStorage.get_project_db_path(project)
119
+ db_path.parent.mkdir(parents=True, exist_ok=True)
120
+ with SQLiteStorage._get_process_lock(project):
121
+ with sqlite3.connect(str(db_path), timeout=30.0) as conn:
122
+ conn.execute("PRAGMA journal_mode = WAL")
123
+ conn.execute("PRAGMA synchronous = NORMAL")
124
+ conn.execute("PRAGMA temp_store = MEMORY")
125
+ conn.execute("PRAGMA cache_size = -20000")
126
+ cursor = conn.cursor()
127
+ cursor.execute(
128
+ """
129
+ CREATE TABLE IF NOT EXISTS metrics (
130
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
131
+ timestamp TEXT NOT NULL,
132
+ run_name TEXT NOT NULL,
133
+ step INTEGER NOT NULL,
134
+ metrics TEXT NOT NULL
135
+ )
136
+ """
137
+ )
138
+ cursor.execute(
139
+ """
140
+ CREATE TABLE IF NOT EXISTS configs (
141
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
142
+ run_name TEXT NOT NULL,
143
+ config TEXT NOT NULL,
144
+ created_at TEXT NOT NULL,
145
+ UNIQUE(run_name)
146
+ )
147
+ """
148
+ )
149
+ cursor.execute(
150
+ """
151
+ CREATE INDEX IF NOT EXISTS idx_metrics_run_step
152
+ ON metrics(run_name, step)
153
+ """
154
+ )
155
+ cursor.execute(
156
+ """
157
+ CREATE INDEX IF NOT EXISTS idx_configs_run_name
158
+ ON configs(run_name)
159
+ """
160
+ )
161
+ cursor.execute(
162
+ """
163
+ CREATE INDEX IF NOT EXISTS idx_metrics_run_timestamp
164
+ ON metrics(run_name, timestamp)
165
+ """
166
+ )
167
+ conn.commit()
168
+ return db_path
169
+
170
+ @staticmethod
171
+ def export_to_parquet():
172
+ """
173
+ Exports all projects' DB files as Parquet under the same path but with extension ".parquet".
174
+ """
175
+ # don't attempt to export (potentially wrong/blank) data before importing for the first time
176
+ if not SQLiteStorage._dataset_import_attempted:
177
+ return
178
+ if not TRACKIO_DIR.exists():
179
+ return
180
+
181
+ all_paths = os.listdir(TRACKIO_DIR)
182
+ db_names = [f for f in all_paths if f.endswith(DB_EXT)]
183
+ for db_name in db_names:
184
+ db_path = TRACKIO_DIR / db_name
185
+ parquet_path = db_path.with_suffix(".parquet")
186
+ if (not parquet_path.exists()) or (
187
+ db_path.stat().st_mtime > parquet_path.stat().st_mtime
188
+ ):
189
+ with sqlite3.connect(str(db_path)) as conn:
190
+ df = pd.read_sql("SELECT * FROM metrics", conn)
191
+ # break out the single JSON metrics column into individual columns
192
+ metrics = df["metrics"].copy()
193
+ metrics = pd.DataFrame(
194
+ metrics.apply(
195
+ lambda x: deserialize_values(orjson.loads(x))
196
+ ).values.tolist(),
197
+ index=df.index,
198
+ )
199
+ del df["metrics"]
200
+ for col in metrics.columns:
201
+ df[col] = metrics[col]
202
+
203
+ df.to_parquet(parquet_path)
204
+
205
+ @staticmethod
206
+ def _cleanup_wal_sidecars(db_path: Path) -> None:
207
+ """Remove leftover -wal/-shm files for a DB basename (prevents disk I/O errors)."""
208
+ for suffix in ("-wal", "-shm"):
209
+ sidecar = Path(str(db_path) + suffix)
210
+ try:
211
+ if sidecar.exists():
212
+ sidecar.unlink()
213
+ except Exception:
214
+ pass
215
+
216
+ @staticmethod
217
+ def import_from_parquet():
218
+ """
219
+ Imports to all DB files that have matching files under the same path but with extension ".parquet".
220
+ """
221
+ if not TRACKIO_DIR.exists():
222
+ return
223
+
224
+ all_paths = os.listdir(TRACKIO_DIR)
225
+ parquet_names = [f for f in all_paths if f.endswith(".parquet")]
226
+ for pq_name in parquet_names:
227
+ parquet_path = TRACKIO_DIR / pq_name
228
+ db_path = parquet_path.with_suffix(DB_EXT)
229
+
230
+ SQLiteStorage._cleanup_wal_sidecars(db_path)
231
+
232
+ df = pd.read_parquet(parquet_path)
233
+ # fix up df to have a single JSON metrics column
234
+ if "metrics" not in df.columns:
235
+ # separate other columns from metrics
236
+ metrics = df.copy()
237
+ other_cols = ["id", "timestamp", "run_name", "step"]
238
+ df = df[other_cols]
239
+ for col in other_cols:
240
+ del metrics[col]
241
+ # combine them all into a single metrics col
242
+ metrics = orjson.loads(metrics.to_json(orient="records"))
243
+ df["metrics"] = [orjson.dumps(serialize_values(row)) for row in metrics]
244
+
245
+ with sqlite3.connect(str(db_path), timeout=30.0) as conn:
246
+ df.to_sql("metrics", conn, if_exists="replace", index=False)
247
+ conn.commit()
248
+
249
+ @staticmethod
250
+ def get_scheduler():
251
+ """
252
+ Get the scheduler for the database based on the environment variables.
253
+ This applies to both local and Spaces.
254
+ """
255
+ with SQLiteStorage._scheduler_lock:
256
+ if SQLiteStorage._current_scheduler is not None:
257
+ return SQLiteStorage._current_scheduler
258
+ hf_token = os.environ.get("HF_TOKEN")
259
+ dataset_id = os.environ.get("TRACKIO_DATASET_ID")
260
+ space_repo_name = os.environ.get("SPACE_REPO_NAME")
261
+ if dataset_id is None or space_repo_name is None:
262
+ scheduler = DummyCommitScheduler()
263
+ else:
264
+ scheduler = CommitScheduler(
265
+ repo_id=dataset_id,
266
+ repo_type="dataset",
267
+ folder_path=TRACKIO_DIR,
268
+ private=True,
269
+ allow_patterns=["*.parquet", "media/**/*"],
270
+ squash_history=True,
271
+ token=hf_token,
272
+ on_before_commit=SQLiteStorage.export_to_parquet,
273
+ )
274
+ SQLiteStorage._current_scheduler = scheduler
275
+ return scheduler
276
+
277
+ @staticmethod
278
+ def log(project: str, run: str, metrics: dict, step: int | None = None):
279
+ """
280
+ Safely log 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
+ This method is not used in the latest versions of Trackio (replaced by bulk_log) but
285
+ is kept for backwards compatibility for users who are connecting to a newer version of
286
+ a Trackio Spaces dashboard with an older version of Trackio installed locally.
287
+ """
288
+ db_path = SQLiteStorage.init_db(project)
289
+ with SQLiteStorage._get_process_lock(project):
290
+ with SQLiteStorage._get_connection(db_path) as conn:
291
+ cursor = conn.cursor()
292
+ cursor.execute(
293
+ """
294
+ SELECT MAX(step)
295
+ FROM metrics
296
+ WHERE run_name = ?
297
+ """,
298
+ (run,),
299
+ )
300
+ last_step = cursor.fetchone()[0]
301
+ current_step = (
302
+ 0
303
+ if step is None and last_step is None
304
+ else (step if step is not None else last_step + 1)
305
+ )
306
+ current_timestamp = datetime.now().isoformat()
307
+ cursor.execute(
308
+ """
309
+ INSERT INTO metrics
310
+ (timestamp, run_name, step, metrics)
311
+ VALUES (?, ?, ?, ?)
312
+ """,
313
+ (
314
+ current_timestamp,
315
+ run,
316
+ current_step,
317
+ orjson.dumps(serialize_values(metrics)),
318
+ ),
319
+ )
320
+ conn.commit()
321
+
322
+ @staticmethod
323
+ def bulk_log(
324
+ project: str,
325
+ run: str,
326
+ metrics_list: list[dict],
327
+ steps: list[int] | None = None,
328
+ timestamps: list[str] | None = None,
329
+ config: dict | None = None,
330
+ ):
331
+ """
332
+ Safely log bulk metrics to the database. Before logging, this method will ensure the database exists
333
+ and is set up with the correct tables. It also uses a cross-process lock to prevent
334
+ database locking errors when multiple processes access the same database.
335
+ """
336
+ if not metrics_list:
337
+ return
338
+
339
+ if timestamps is None:
340
+ timestamps = [datetime.now().isoformat()] * len(metrics_list)
341
+
342
+ db_path = SQLiteStorage.init_db(project)
343
+ with SQLiteStorage._get_process_lock(project):
344
+ with SQLiteStorage._get_connection(db_path) as conn:
345
+ cursor = conn.cursor()
346
+
347
+ if steps is None:
348
+ steps = list(range(len(metrics_list)))
349
+ elif any(s is None for s in steps):
350
+ cursor.execute(
351
+ "SELECT MAX(step) FROM metrics WHERE run_name = ?", (run,)
352
+ )
353
+ last_step = cursor.fetchone()[0]
354
+ current_step = 0 if last_step is None else last_step + 1
355
+ processed_steps = []
356
+ for step in steps:
357
+ if step is None:
358
+ processed_steps.append(current_step)
359
+ current_step += 1
360
+ else:
361
+ processed_steps.append(step)
362
+ steps = processed_steps
363
+
364
+ if len(metrics_list) != len(steps) or len(metrics_list) != len(
365
+ timestamps
366
+ ):
367
+ raise ValueError(
368
+ "metrics_list, steps, and timestamps must have the same length"
369
+ )
370
+
371
+ data = []
372
+ for i, metrics in enumerate(metrics_list):
373
+ data.append(
374
+ (
375
+ timestamps[i],
376
+ run,
377
+ steps[i],
378
+ orjson.dumps(serialize_values(metrics)),
379
+ )
380
+ )
381
+
382
+ cursor.executemany(
383
+ """
384
+ INSERT INTO metrics
385
+ (timestamp, run_name, step, metrics)
386
+ VALUES (?, ?, ?, ?)
387
+ """,
388
+ data,
389
+ )
390
+
391
+ if config:
392
+ current_timestamp = datetime.now().isoformat()
393
+ cursor.execute(
394
+ """
395
+ INSERT OR REPLACE INTO configs
396
+ (run_name, config, created_at)
397
+ VALUES (?, ?, ?)
398
+ """,
399
+ (
400
+ run,
401
+ orjson.dumps(serialize_values(config)),
402
+ current_timestamp,
403
+ ),
404
+ )
405
+
406
+ conn.commit()
407
+
408
+ @staticmethod
409
+ def get_logs(project: str, run: str) -> list[dict]:
410
+ """Retrieve logs for a specific run. Logs include the step count (int) and the timestamp (datetime object)."""
411
+ db_path = SQLiteStorage.get_project_db_path(project)
412
+ if not db_path.exists():
413
+ return []
414
+
415
+ with SQLiteStorage._get_connection(db_path) as conn:
416
+ cursor = conn.cursor()
417
+ cursor.execute(
418
+ """
419
+ SELECT timestamp, step, metrics
420
+ FROM metrics
421
+ WHERE run_name = ?
422
+ ORDER BY timestamp
423
+ """,
424
+ (run,),
425
+ )
426
+
427
+ rows = cursor.fetchall()
428
+ results = []
429
+ for row in rows:
430
+ metrics = orjson.loads(row["metrics"])
431
+ metrics = deserialize_values(metrics)
432
+ metrics["timestamp"] = row["timestamp"]
433
+ metrics["step"] = row["step"]
434
+ results.append(metrics)
435
+ return results
436
+
437
+ @staticmethod
438
+ def load_from_dataset():
439
+ dataset_id = os.environ.get("TRACKIO_DATASET_ID")
440
+ space_repo_name = os.environ.get("SPACE_REPO_NAME")
441
+ if dataset_id is not None and space_repo_name is not None:
442
+ hfapi = hf.HfApi()
443
+ updated = False
444
+ if not TRACKIO_DIR.exists():
445
+ TRACKIO_DIR.mkdir(parents=True, exist_ok=True)
446
+ with SQLiteStorage.get_scheduler().lock:
447
+ try:
448
+ files = hfapi.list_repo_files(dataset_id, repo_type="dataset")
449
+ for file in files:
450
+ # Download parquet and media assets
451
+ if not (file.endswith(".parquet") or file.startswith("media/")):
452
+ continue
453
+ if (TRACKIO_DIR / file).exists():
454
+ continue
455
+ hf.hf_hub_download(
456
+ dataset_id, file, repo_type="dataset", local_dir=TRACKIO_DIR
457
+ )
458
+ updated = True
459
+ except hf.errors.EntryNotFoundError:
460
+ pass
461
+ except hf.errors.RepositoryNotFoundError:
462
+ pass
463
+ if updated:
464
+ SQLiteStorage.import_from_parquet()
465
+ SQLiteStorage._dataset_import_attempted = True
466
+
467
+ @staticmethod
468
+ def get_projects() -> list[str]:
469
+ """
470
+ Get list of all projects by scanning the database files in the trackio directory.
471
+ """
472
+ if not SQLiteStorage._dataset_import_attempted:
473
+ SQLiteStorage.load_from_dataset()
474
+
475
+ projects: set[str] = set()
476
+ if not TRACKIO_DIR.exists():
477
+ return []
478
+
479
+ for db_file in TRACKIO_DIR.glob(f"*{DB_EXT}"):
480
+ project_name = db_file.stem
481
+ projects.add(project_name)
482
+ return sorted(projects)
483
+
484
+ @staticmethod
485
+ def get_runs(project: str) -> list[str]:
486
+ """Get list of all runs for a project."""
487
+ db_path = SQLiteStorage.get_project_db_path(project)
488
+ if not db_path.exists():
489
+ return []
490
+
491
+ with SQLiteStorage._get_connection(db_path) as conn:
492
+ cursor = conn.cursor()
493
+ cursor.execute(
494
+ "SELECT DISTINCT run_name FROM metrics",
495
+ )
496
+ return [row[0] for row in cursor.fetchall()]
497
+
498
+ @staticmethod
499
+ def get_max_steps_for_runs(project: str) -> dict[str, int]:
500
+ """Get the maximum step for each run in a project."""
501
+ db_path = SQLiteStorage.get_project_db_path(project)
502
+ if not db_path.exists():
503
+ return {}
504
+
505
+ with SQLiteStorage._get_connection(db_path) as conn:
506
+ cursor = conn.cursor()
507
+ cursor.execute(
508
+ """
509
+ SELECT run_name, MAX(step) as max_step
510
+ FROM metrics
511
+ GROUP BY run_name
512
+ """
513
+ )
514
+
515
+ results = {}
516
+ for row in cursor.fetchall():
517
+ results[row["run_name"]] = row["max_step"]
518
+
519
+ return results
520
+
521
+ @staticmethod
522
+ def store_config(project: str, run: str, config: dict) -> None:
523
+ """Store configuration for a run."""
524
+ db_path = SQLiteStorage.init_db(project)
525
+
526
+ with SQLiteStorage._get_process_lock(project):
527
+ with SQLiteStorage._get_connection(db_path) as conn:
528
+ cursor = conn.cursor()
529
+ current_timestamp = datetime.now().isoformat()
530
+
531
+ cursor.execute(
532
+ """
533
+ INSERT OR REPLACE INTO configs
534
+ (run_name, config, created_at)
535
+ VALUES (?, ?, ?)
536
+ """,
537
+ (run, orjson.dumps(serialize_values(config)), current_timestamp),
538
+ )
539
+ conn.commit()
540
+
541
+ @staticmethod
542
+ def get_run_config(project: str, run: str) -> dict | None:
543
+ """Get configuration for a specific run."""
544
+ db_path = SQLiteStorage.get_project_db_path(project)
545
+ if not db_path.exists():
546
+ return None
547
+
548
+ with SQLiteStorage._get_connection(db_path) as conn:
549
+ cursor = conn.cursor()
550
+ try:
551
+ cursor.execute(
552
+ """
553
+ SELECT config FROM configs WHERE run_name = ?
554
+ """,
555
+ (run,),
556
+ )
557
+
558
+ row = cursor.fetchone()
559
+ if row:
560
+ config = orjson.loads(row["config"])
561
+ return deserialize_values(config)
562
+ return None
563
+ except sqlite3.OperationalError as e:
564
+ if "no such table: configs" in str(e):
565
+ return None
566
+ raise
567
+
568
+ @staticmethod
569
+ def delete_run(project: str, run: str) -> bool:
570
+ """Delete a run from the database (both metrics and config)."""
571
+ db_path = SQLiteStorage.get_project_db_path(project)
572
+ if not db_path.exists():
573
+ return False
574
+
575
+ with SQLiteStorage._get_process_lock(project):
576
+ with SQLiteStorage._get_connection(db_path) as conn:
577
+ cursor = conn.cursor()
578
+ try:
579
+ cursor.execute("DELETE FROM metrics WHERE run_name = ?", (run,))
580
+ cursor.execute("DELETE FROM configs WHERE run_name = ?", (run,))
581
+ conn.commit()
582
+ return True
583
+ except sqlite3.Error:
584
+ return False
585
+
586
+ @staticmethod
587
+ def get_all_run_configs(project: str) -> dict[str, dict]:
588
+ """Get configurations for all runs in a project."""
589
+ db_path = SQLiteStorage.get_project_db_path(project)
590
+ if not db_path.exists():
591
+ return {}
592
+
593
+ with SQLiteStorage._get_connection(db_path) as conn:
594
+ cursor = conn.cursor()
595
+ try:
596
+ cursor.execute(
597
+ """
598
+ SELECT run_name, config FROM configs
599
+ """
600
+ )
601
+
602
+ results = {}
603
+ for row in cursor.fetchall():
604
+ config = orjson.loads(row["config"])
605
+ results[row["run_name"]] = deserialize_values(config)
606
+ return results
607
+ except sqlite3.OperationalError as e:
608
+ if "no such table: configs" in str(e):
609
+ return {}
610
+ raise
611
+
612
+ @staticmethod
613
+ def get_metric_values(project: str, run: str, metric_name: str) -> list[dict]:
614
+ """Get all values for a specific metric in a project/run."""
615
+ db_path = SQLiteStorage.get_project_db_path(project)
616
+ if not db_path.exists():
617
+ return []
618
+
619
+ with SQLiteStorage._get_connection(db_path) as conn:
620
+ cursor = conn.cursor()
621
+ cursor.execute(
622
+ """
623
+ SELECT timestamp, step, metrics
624
+ FROM metrics
625
+ WHERE run_name = ?
626
+ ORDER BY timestamp
627
+ """,
628
+ (run,),
629
+ )
630
+
631
+ rows = cursor.fetchall()
632
+ results = []
633
+ for row in rows:
634
+ metrics = orjson.loads(row["metrics"])
635
+ metrics = deserialize_values(metrics)
636
+ if metric_name in metrics:
637
+ results.append(
638
+ {
639
+ "timestamp": row["timestamp"],
640
+ "step": row["step"],
641
+ "value": metrics[metric_name],
642
+ }
643
+ )
644
+ return results
645
+
646
+ @staticmethod
647
+ def get_all_metrics_for_run(project: str, run: str) -> list[str]:
648
+ """Get all metric names for a specific project/run."""
649
+ db_path = SQLiteStorage.get_project_db_path(project)
650
+ if not db_path.exists():
651
+ return []
652
+
653
+ with SQLiteStorage._get_connection(db_path) as conn:
654
+ cursor = conn.cursor()
655
+ cursor.execute(
656
+ """
657
+ SELECT metrics
658
+ FROM metrics
659
+ WHERE run_name = ?
660
+ ORDER BY timestamp
661
+ """,
662
+ (run,),
663
+ )
664
+
665
+ rows = cursor.fetchall()
666
+ all_metrics = set()
667
+ for row in rows:
668
+ metrics = orjson.loads(row["metrics"])
669
+ metrics = deserialize_values(metrics)
670
+ for key in metrics.keys():
671
+ if key not in ["timestamp", "step"]:
672
+ all_metrics.add(key)
673
+ return sorted(list(all_metrics))
674
+
675
+ def finish(self):
676
+ """Cleanup when run is finished."""
677
+ 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