abidlabs HF Staff commited on
Commit
30ebc6b
·
verified ·
1 Parent(s): 4e04b32

Upload folder using huggingface_hub

Browse files
Files changed (46) hide show
  1. .gitattributes +1 -0
  2. trackio/CHANGELOG.md +212 -0
  3. trackio/__init__.py +734 -0
  4. trackio/alerts.py +184 -0
  5. trackio/api.py +87 -0
  6. trackio/apple_gpu.py +253 -0
  7. trackio/assets/badge.png +0 -0
  8. trackio/assets/trackio_logo_dark.png +0 -0
  9. trackio/assets/trackio_logo_light.png +0 -0
  10. trackio/assets/trackio_logo_old.png +3 -0
  11. trackio/assets/trackio_logo_type_dark.png +0 -0
  12. trackio/assets/trackio_logo_type_dark_transparent.png +0 -0
  13. trackio/assets/trackio_logo_type_light.png +0 -0
  14. trackio/assets/trackio_logo_type_light_transparent.png +0 -0
  15. trackio/bucket_storage.py +94 -0
  16. trackio/cli.py +1238 -0
  17. trackio/cli_helpers.py +158 -0
  18. trackio/commit_scheduler.py +310 -0
  19. trackio/context_vars.py +18 -0
  20. trackio/deploy.py +806 -0
  21. trackio/dummy_commit_scheduler.py +19 -0
  22. trackio/frontend/dist/assets/index-Cs1UkfOV.css +1 -0
  23. trackio/frontend/dist/assets/index-UYQ1xITV.js +0 -0
  24. trackio/frontend/dist/index.html +14 -0
  25. trackio/frontend/eslint.config.js +42 -0
  26. trackio/frontend/index.html +13 -0
  27. trackio/frontend_server.py +63 -0
  28. trackio/gpu.py +357 -0
  29. trackio/histogram.py +71 -0
  30. trackio/imports.py +290 -0
  31. trackio/markdown.py +21 -0
  32. trackio/media/__init__.py +27 -0
  33. trackio/media/audio.py +167 -0
  34. trackio/media/image.py +84 -0
  35. trackio/media/media.py +79 -0
  36. trackio/media/utils.py +60 -0
  37. trackio/media/video.py +246 -0
  38. trackio/package.json +6 -0
  39. trackio/py.typed +0 -0
  40. trackio/remote_client.py +28 -0
  41. trackio/run.py +739 -0
  42. trackio/server.py +729 -0
  43. trackio/sqlite_storage.py +1906 -0
  44. trackio/table.py +173 -0
  45. trackio/typehints.py +39 -0
  46. trackio/utils.py +933 -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
+ trackio/assets/trackio_logo_old.png filter=lfs diff=lfs merge=lfs -text
trackio/CHANGELOG.md ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # trackio
2
+
3
+ ## 0.21.0
4
+
5
+ ### Features
6
+
7
+ - [#467](https://github.com/gradio-app/trackio/pull/467) [`f357deb`](https://github.com/gradio-app/trackio/commit/f357debf78957e4c1f2b901bee4f77cf397298b4) - Allow logged metrics as x-axis choices. Thanks @abidlabs!
8
+ - [#474](https://github.com/gradio-app/trackio/pull/474) [`655673d`](https://github.com/gradio-app/trackio/commit/655673d4c6b7c8b7ee8f87f2589f2dbbc3d2ef91) - Fix file descriptor leak from `sqlite3.connect`. Thanks @abidlabs!
9
+ - [#470](https://github.com/gradio-app/trackio/pull/470) [`bea8c9d`](https://github.com/gradio-app/trackio/commit/bea8c9dcae0b59d071b6c779c97ee525c9bbf6e7) - Restores tooltips to line plots and fixes the call to uses TTL instead of OAuth. Thanks @abidlabs!
10
+ - [#471](https://github.com/gradio-app/trackio/pull/471) [`246fce0`](https://github.com/gradio-app/trackio/commit/246fce0a01619e1c2c538c67b3e460883334d500) - Deprecate dataset backend in favor of buckets. Thanks @abidlabs!
11
+ - [#465](https://github.com/gradio-app/trackio/pull/465) [`3e11174`](https://github.com/gradio-app/trackio/commit/3e1117438bb8168b802245a33059affa558ae519) - Use HF buckets as backend. Thanks @abidlabs!
12
+ - [#469](https://github.com/gradio-app/trackio/pull/469) [`915d170`](https://github.com/gradio-app/trackio/commit/915d17045133172b59195acfdcc70709229668aa) - Make static Spaces work with Buckets and also allow conversion from Gradio SDK to Static Spaces. Thanks @abidlabs!
13
+
14
+ ## 0.20.2
15
+
16
+ ### Features
17
+
18
+ - [#464](https://github.com/gradio-app/trackio/pull/464) [`c89ebb3`](https://github.com/gradio-app/trackio/commit/c89ebb3b50f695bc7f16cbc6f46dce86f79a01e9) - Improve rendering of curves. Thanks @abidlabs!
19
+ - [#462](https://github.com/gradio-app/trackio/pull/462) [`9160b78`](https://github.com/gradio-app/trackio/commit/9160b78ff6f258f0b87a4f34a24e7d0b5dfbf2fb) - Refactor plot title to display only the metric name without the path. Thanks @qgallouedec!
20
+
21
+ ## 0.20.1
22
+
23
+ ### Features
24
+
25
+ - [#454](https://github.com/gradio-app/trackio/pull/454) [`22881db`](https://github.com/gradio-app/trackio/commit/22881dbbbb6b81197a00a19853771007093d61e4) - Bar chart single point. Thanks @abidlabs!
26
+ - [#455](https://github.com/gradio-app/trackio/pull/455) [`f8db51a`](https://github.com/gradio-app/trackio/commit/f8db51a20ca61ef703f3f2c2ee1ebd9c4f239cf2) - Adds a static Trackio mode via `trackio.sync(sdk="static")` and support for the `TRACKIO_SPACE_ID` environment variable. Thanks @abidlabs!
27
+
28
+ ## 0.20.0
29
+
30
+ ### Features
31
+
32
+ - [#450](https://github.com/gradio-app/trackio/pull/450) [`b0571ef`](https://github.com/gradio-app/trackio/commit/b0571ef6207a1ce346696f858ad2b7b584dd194f) - Use Svelte source for Gradio components directly in Trackio dashboard. Thanks @abidlabs!
33
+
34
+ ## 0.19.0
35
+
36
+ ### Features
37
+
38
+ - [#445](https://github.com/gradio-app/trackio/pull/445) [`cef4a58`](https://github.com/gradio-app/trackio/commit/cef4a583cb76f4091fc6c0e5783124ee84f8e243) - Add remote HF Space support to CLI. Thanks @abidlabs!
39
+ - [#444](https://github.com/gradio-app/trackio/pull/444) [`358f2a9`](https://github.com/gradio-app/trackio/commit/358f2a9ca238ee8b90b5a8c96220da287e0698fb) - Fix alerts placeholder flashing on reports page. Thanks @abidlabs!
40
+
41
+ ## 0.18.0
42
+
43
+ ### Features
44
+
45
+ - [#435](https://github.com/gradio-app/trackio/pull/435) [`4a47112`](https://github.com/gradio-app/trackio/commit/4a471128e18a39e45fad48a67fd711c5ae9e4aed) - feat: allow hiding section header accordions. Thanks @Saba9!
46
+ - [#439](https://github.com/gradio-app/trackio/pull/439) [`18e9650`](https://github.com/gradio-app/trackio/commit/18e96503d5a3a7cf926e92782d457e23c19942bd) - Add alerts with webhooks, CLI, and documentation. Thanks @abidlabs!
47
+ - [#438](https://github.com/gradio-app/trackio/pull/438) [`0875ccd`](https://github.com/gradio-app/trackio/commit/0875ccd3d8a41b1376f64030f21cfe8cdcc73b05) - Add "share this view" functionality. Thanks @qgallouedec!
48
+ - [#409](https://github.com/gradio-app/trackio/pull/409) [`9282403`](https://github.com/gradio-app/trackio/commit/9282403d8896d48679b0f888208a7ba5bdd4271a) - Add Apple Silicon GPU and system monitoring support. Thanks @znation!
49
+ - [#434](https://github.com/gradio-app/trackio/pull/434) [`4193223`](https://github.com/gradio-app/trackio/commit/41932230a3a2e1c16405dba08ecba5a42f11d1a8) - fix: table slider crash. Thanks @Saba9!
50
+
51
+ ### Fixes
52
+
53
+ - [#441](https://github.com/gradio-app/trackio/pull/441) [`3a2d11d`](https://github.com/gradio-app/trackio/commit/3a2d11dab0b4b37c925abc30ef84b0e2910321ee) - preserve x-axis step when toggling run checkboxes. Thanks @Saba9!
54
+
55
+ ## 0.17.0
56
+
57
+ ### Features
58
+
59
+ - [#428](https://github.com/gradio-app/trackio/pull/428) [`f7dd1ce`](https://github.com/gradio-app/trackio/commit/f7dd1ce2dc8a1936f9983467fcbcf93bfef01e09) - feat: add ability to rename runs. Thanks @Saba9!
60
+ - [#437](https://github.com/gradio-app/trackio/pull/437) [`2727c0b`](https://github.com/gradio-app/trackio/commit/2727c0b0755f48f7f186162ea45185c98f6b5516) - Add markdown reports across Trackio. Thanks @abidlabs!
61
+ - [#427](https://github.com/gradio-app/trackio/pull/427) [`5aeb9ed`](https://github.com/gradio-app/trackio/commit/5aeb9edcfd2068d309d9d64f172dcbcc327be1ab) - Make Trackio logging much more robust. Thanks @abidlabs!
62
+
63
+ ## 0.16.1
64
+
65
+ ### Features
66
+
67
+ - [#431](https://github.com/gradio-app/trackio/pull/431) [`c7ce55b`](https://github.com/gradio-app/trackio/commit/c7ce55b14dd5eb0c2165fb15df17dd60721c9325) - Lazy load the UI when trackio is imported. Thanks @abidlabs!
68
+
69
+ ## 0.16.0
70
+
71
+ ### Features
72
+
73
+ - [#426](https://github.com/gradio-app/trackio/pull/426) [`ead4dc8`](https://github.com/gradio-app/trackio/commit/ead4dc8e74ee2d8e47d61bca0a7668456acf49be) - Fix redundant double rendering of group checkboxes. Thanks @abidlabs!
74
+ - [#413](https://github.com/gradio-app/trackio/pull/413) [`39c4750`](https://github.com/gradio-app/trackio/commit/39c4750951d554ba6eb4d58847c6bb444b2891a8) - Check `dist-packages` when checking for source installation. Thanks @sergiopaniego!
75
+ - [#423](https://github.com/gradio-app/trackio/pull/423) [`2e52ab3`](https://github.com/gradio-app/trackio/commit/2e52ab303e3041718a6a56fbf84d0848aca9ad67) - Fix legend outline visibility issue. Thanks @Raghunath-Balaji!
76
+ - [#407](https://github.com/gradio-app/trackio/pull/407) [`c8a384d`](https://github.com/gradio-app/trackio/commit/c8a384ddfe5a295cecf862a26178d40e48acb424) - Fix pytests that were failling locally on MacOS. Thanks @abidlabs!
77
+ - [#405](https://github.com/gradio-app/trackio/pull/405) [`35aae4e`](https://github.com/gradio-app/trackio/commit/35aae4e3aa3e2b2888887528478b9dc6a9808bda) - Add conditional padding for HF Space dashboard when not in iframe. Thanks @znation!
78
+
79
+ ## 0.15.0
80
+
81
+ ### Features
82
+
83
+ - [#397](https://github.com/gradio-app/trackio/pull/397) [`6b38ad0`](https://github.com/gradio-app/trackio/commit/6b38ad02e5d73a0df49c4eede7e91331282ece04) - Adds `--host` cli option support. Thanks @abidlabs!
84
+ - [#396](https://github.com/gradio-app/trackio/pull/396) [`4a4d1ab`](https://github.com/gradio-app/trackio/commit/4a4d1ab85e63d923132a3fa7afa5d90e16431bec) - Fix run selection issue. Thanks @abidlabs!
85
+ - [#394](https://github.com/gradio-app/trackio/pull/394) [`c47a3a3`](https://github.com/gradio-app/trackio/commit/c47a3a31f8c4b83bce1aa7fc22eeba3d9021ad3d) - Add wandb-compatible API for trackio. Thanks @abidlabs!
86
+ - [#378](https://github.com/gradio-app/trackio/pull/378) [`b02046a`](https://github.com/gradio-app/trackio/commit/b02046a5b0dad7c9854e099a87f884afba4aecb2) - Add JSON export button for line plots and upgrade gradio dependency. Thanks @JamshedAli18!
87
+
88
+ ## 0.14.2
89
+
90
+ ### Features
91
+
92
+ - [#386](https://github.com/gradio-app/trackio/pull/386) [`f9452cd`](https://github.com/gradio-app/trackio/commit/f9452cdb8f0819368f3610f7ac0ed08957305275) - Fixing some issues related to deployed Trackio Spaces. Thanks @abidlabs!
93
+
94
+ ## 0.14.1
95
+
96
+ ### Features
97
+
98
+ - [#382](https://github.com/gradio-app/trackio/pull/382) [`44fe9bb`](https://github.com/gradio-app/trackio/commit/44fe9bb264fb2aafb0ec302ff15227c045819a2c) - Fix app file path when Trackio is not installed from source. Thanks @abidlabs!
99
+ - [#380](https://github.com/gradio-app/trackio/pull/380) [`c3f4cff`](https://github.com/gradio-app/trackio/commit/c3f4cff74bc5676e812773d8571454894fcdc7cc) - Add CLI commands for querying projects, runs, and metrics. Thanks @abidlabs!
100
+
101
+ ## 0.14.0
102
+
103
+ ### Features
104
+
105
+ - [#377](https://github.com/gradio-app/trackio/pull/377) [`5c5015b`](https://github.com/gradio-app/trackio/commit/5c5015b68c85c5de51111dad983f735c27b9a05f) - fixed wrapping issue in Runs table. Thanks @gaganchapa!
106
+ - [#374](https://github.com/gradio-app/trackio/pull/374) [`388e26b`](https://github.com/gradio-app/trackio/commit/388e26b9e9f24cd7ad203affe9b709be885b3d24) - Save Optimized Parquet files. Thanks @lhoestq!
107
+ - [#371](https://github.com/gradio-app/trackio/pull/371) [`fbace9c`](https://github.com/gradio-app/trackio/commit/fbace9cd7732c166f34d268f54b05bb06846cc5d) - Add GPU metrics logging. Thanks @kashif!
108
+ - [#367](https://github.com/gradio-app/trackio/pull/367) [`862840c`](https://github.com/gradio-app/trackio/commit/862840c13e30fc960cbee5b9eac4d3c25beba9de) - Add option to only show latest run, and fix the double logo issue. Thanks @abidlabs!
109
+
110
+ ## 0.13.1
111
+
112
+ ### Features
113
+
114
+ - [#369](https://github.com/gradio-app/trackio/pull/369) [`767e9fe`](https://github.com/gradio-app/trackio/commit/767e9fe095d7c6ed102016caf927c1517fb8618c) - tiny pr removing unnecessary code. Thanks @abidlabs!
115
+
116
+ ## 0.13.0
117
+
118
+ ### Features
119
+
120
+ - [#358](https://github.com/gradio-app/trackio/pull/358) [`073715d`](https://github.com/gradio-app/trackio/commit/073715d1caf8282f68890117f09c3ac301205312) - Improvements to `trackio.sync()`. Thanks @abidlabs!
121
+
122
+ ## 0.12.0
123
+
124
+ ### Features
125
+
126
+ - [#357](https://github.com/gradio-app/trackio/pull/357) [`02ba815`](https://github.com/gradio-app/trackio/commit/02ba815358060f1966052de051a5bdb09702920e) - Redesign media and tables to show up on separate page. Thanks @abidlabs!
127
+ - [#359](https://github.com/gradio-app/trackio/pull/359) [`08fe9c9`](https://github.com/gradio-app/trackio/commit/08fe9c9ddd7fe99ee811555fdfb62df9ab88e939) - docs: Improve docstrings. Thanks @qgallouedec!
128
+
129
+ ## 0.11.0
130
+
131
+ ### Features
132
+
133
+ - [#355](https://github.com/gradio-app/trackio/pull/355) [`ea51f49`](https://github.com/gradio-app/trackio/commit/ea51f4954922f21be76ef828700420fe9a912c4b) - Color code run checkboxes and match with plot lines. Thanks @abidlabs!
134
+ - [#353](https://github.com/gradio-app/trackio/pull/353) [`8abe691`](https://github.com/gradio-app/trackio/commit/8abe6919aeefe21fc7a23af814883efbb037c21f) - Remove show_api from demo.launch. Thanks @sergiopaniego!
135
+ - [#351](https://github.com/gradio-app/trackio/pull/351) [`8a8957e`](https://github.com/gradio-app/trackio/commit/8a8957e530dd7908d1fef7f2df030303f808101f) - Add `trackio.save()`. Thanks @abidlabs!
136
+
137
+ ## 0.10.0
138
+
139
+ ### Features
140
+
141
+ - [#305](https://github.com/gradio-app/trackio/pull/305) [`e64883a`](https://github.com/gradio-app/trackio/commit/e64883a51f7b8b93f7d48b8afe55acdb62238b71) - bump to gradio 6.0, make `trackio` compatible, and fix related issues. Thanks @abidlabs!
142
+
143
+ ## 0.9.1
144
+
145
+ ### Features
146
+
147
+ - [#344](https://github.com/gradio-app/trackio/pull/344) [`7e01024`](https://github.com/gradio-app/trackio/commit/7e010241d9a34794e0ce0dc19c1a6f0cf94ba856) - Avoid redundant calls to /whoami-v2. Thanks @Wauplin!
148
+
149
+ ## 0.9.0
150
+
151
+ ### Features
152
+
153
+ - [#343](https://github.com/gradio-app/trackio/pull/343) [`51bea30`](https://github.com/gradio-app/trackio/commit/51bea30f2877adff8e6497466d3a799400a0a049) - Sync offline projects to Hugging Face spaces. Thanks @candemircan!
154
+ - [#341](https://github.com/gradio-app/trackio/pull/341) [`4fd841f`](https://github.com/gradio-app/trackio/commit/4fd841fa190e15071b02f6fba7683ef4f393a654) - Adds a basic UI test to `trackio`. Thanks @abidlabs!
155
+ - [#339](https://github.com/gradio-app/trackio/pull/339) [`011d91b`](https://github.com/gradio-app/trackio/commit/011d91bb6ae266516fd250a349285670a8049d05) - Allow customzing the trackio color palette. Thanks @abidlabs!
156
+
157
+ ## 0.8.1
158
+
159
+ ### Features
160
+
161
+ - [#336](https://github.com/gradio-app/trackio/pull/336) [`5f9f51d`](https://github.com/gradio-app/trackio/commit/5f9f51dac8677f240d7c42c3e3b2660a22aee138) - Support a list of `Trackio.Image` in a `trackio.Table` cell. Thanks @abidlabs!
162
+
163
+ ## 0.8.0
164
+
165
+ ### Features
166
+
167
+ - [#331](https://github.com/gradio-app/trackio/pull/331) [`2c02d0f`](https://github.com/gradio-app/trackio/commit/2c02d0fd0a5824160528782402bb0dd4083396d5) - Truncate table string values that are greater than 250 characters (configuirable via env variable). Thanks @abidlabs!
168
+ - [#324](https://github.com/gradio-app/trackio/pull/324) [`50b2122`](https://github.com/gradio-app/trackio/commit/50b2122e7965ac82a72e6cb3b7d048bc10a2a6b1) - Add log y-axis functionality to UI. Thanks @abidlabs!
169
+ - [#326](https://github.com/gradio-app/trackio/pull/326) [`61dc1f4`](https://github.com/gradio-app/trackio/commit/61dc1f40af2f545f8e70395ddf0dbb8aee6b60d5) - Fix: improve table rendering for metrics in Trackio Dashboard. Thanks @vigneshwaran!
170
+ - [#328](https://github.com/gradio-app/trackio/pull/328) [`6857cbb`](https://github.com/gradio-app/trackio/commit/6857cbbe557a59a4642f210ec42566d108294e63) - Support trackio.Table with trackio.Image columns. Thanks @abidlabs!
171
+ - [#323](https://github.com/gradio-app/trackio/pull/323) [`6857cbb`](https://github.com/gradio-app/trackio/commit/6857cbbe557a59a4642f210ec42566d108294e63) - add Trackio client implementations in Go, Rust, and JS. Thanks @vaibhav-research!
172
+
173
+ ## 0.7.0
174
+
175
+ ### Features
176
+
177
+ - [#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!
178
+ - [#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!
179
+ - [#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!
180
+
181
+ ## 0.6.0
182
+
183
+ ### Features
184
+
185
+ - [#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!
186
+ - [#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!
187
+ - [#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!
188
+ - [#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!
189
+ - [#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!
190
+
191
+ ## 0.5.3
192
+
193
+ ### Features
194
+
195
+ - [#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!
196
+
197
+ ## 0.5.2
198
+
199
+ ### Features
200
+
201
+ - [#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!
202
+ - [#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!
203
+
204
+ ### Fixes
205
+
206
+ - [#291](https://github.com/gradio-app/trackio/pull/291) [`3b5adc3`](https://github.com/gradio-app/trackio/commit/3b5adc3d1f452dbab7a714d235f4974782f93730) - Fix the wheel build. Thanks @pngwn!
207
+
208
+ ## 0.5.1
209
+
210
+ ### Fixes
211
+
212
+ - [#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!
trackio/__init__.py ADDED
@@ -0,0 +1,734 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import atexit
2
+ import glob
3
+ import json
4
+ import logging
5
+ import os
6
+ import shutil
7
+ import warnings
8
+ import webbrowser
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ import huggingface_hub
13
+ from gradio.themes import ThemeClass
14
+ from gradio.utils import TupleNoPrint
15
+ from gradio_client import Client, handle_file
16
+ from huggingface_hub import SpaceStorage
17
+ from huggingface_hub.errors import LocalTokenNotFoundError
18
+
19
+ from trackio import context_vars, deploy, utils
20
+ from trackio.alerts import AlertLevel
21
+ from trackio.api import Api
22
+ from trackio.apple_gpu import apple_gpu_available
23
+ from trackio.apple_gpu import log_apple_gpu as _log_apple_gpu
24
+ from trackio.deploy import sync
25
+ from trackio.frontend_server import mount_frontend
26
+ from trackio.gpu import gpu_available
27
+ from trackio.gpu import log_gpu as _log_nvidia_gpu
28
+ from trackio.histogram import Histogram
29
+ from trackio.imports import import_csv, import_tf_events
30
+ from trackio.markdown import Markdown
31
+ from trackio.media import (
32
+ TrackioAudio,
33
+ TrackioImage,
34
+ TrackioVideo,
35
+ get_project_media_path,
36
+ )
37
+ from trackio.run import Run
38
+ from trackio.server import make_trackio_server
39
+ from trackio.sqlite_storage import SQLiteStorage
40
+ from trackio.table import Table
41
+ from trackio.typehints import UploadEntry
42
+ from trackio.utils import TRACKIO_DIR, TRACKIO_LOGO_DIR
43
+
44
+ logging.getLogger("httpx").setLevel(logging.WARNING)
45
+
46
+ warnings.filterwarnings(
47
+ "ignore",
48
+ message="Empty session being created. Install gradio\\[oauth\\]",
49
+ category=UserWarning,
50
+ module="gradio.helpers",
51
+ )
52
+
53
+ __version__ = json.loads(Path(__file__).parent.joinpath("package.json").read_text())[
54
+ "version"
55
+ ]
56
+
57
+ __all__ = [
58
+ "init",
59
+ "log",
60
+ "log_system",
61
+ "log_gpu",
62
+ "finish",
63
+ "alert",
64
+ "AlertLevel",
65
+ "show",
66
+ "sync",
67
+ "delete_project",
68
+ "import_csv",
69
+ "import_tf_events",
70
+ "save",
71
+ "Image",
72
+ "Video",
73
+ "Audio",
74
+ "Table",
75
+ "Histogram",
76
+ "Markdown",
77
+ "Api",
78
+ ]
79
+
80
+ Image = TrackioImage
81
+ Video = TrackioVideo
82
+ Audio = TrackioAudio
83
+
84
+
85
+ config = {}
86
+
87
+ _atexit_registered = False
88
+ _projects_notified_auto_log_hw: set[str] = set()
89
+
90
+
91
+ def _cleanup_current_run():
92
+ run = context_vars.current_run.get()
93
+ if run is not None:
94
+ try:
95
+ run.finish()
96
+ except Exception:
97
+ pass
98
+
99
+
100
+ def init(
101
+ project: str,
102
+ name: str | None = None,
103
+ group: str | None = None,
104
+ space_id: str | None = None,
105
+ space_storage: SpaceStorage | None = None,
106
+ dataset_id: str | None = None,
107
+ bucket_id: str | None = None,
108
+ config: dict | None = None,
109
+ resume: str = "never",
110
+ settings: Any = None,
111
+ private: bool | None = None,
112
+ embed: bool = True,
113
+ auto_log_gpu: bool | None = None,
114
+ gpu_log_interval: float = 10.0,
115
+ webhook_url: str | None = None,
116
+ webhook_min_level: AlertLevel | str | None = None,
117
+ ) -> Run:
118
+ """
119
+ Creates a new Trackio project and returns a [`Run`] object.
120
+
121
+ Args:
122
+ project (`str`):
123
+ The name of the project (can be an existing project to continue tracking or
124
+ a new project to start tracking from scratch).
125
+ name (`str`, *optional*):
126
+ The name of the run (if not provided, a default name will be generated).
127
+ group (`str`, *optional*):
128
+ The name of the group which this run belongs to in order to help organize
129
+ related runs together. You can toggle the entire group's visibilitiy in the
130
+ dashboard.
131
+ space_id (`str`, *optional*):
132
+ If provided, the project will be logged to a Hugging Face Space instead of
133
+ a local directory. Should be a complete Space name like
134
+ `"username/reponame"` or `"orgname/reponame"`, or just `"reponame"` in which
135
+ case the Space will be created in the currently-logged-in Hugging Face
136
+ user's namespace. If the Space does not exist, it will be created. If the
137
+ Space already exists, the project will be logged to it. Can also be set
138
+ via the `TRACKIO_SPACE_ID` environment variable.
139
+ space_storage ([`~huggingface_hub.SpaceStorage`], *optional*):
140
+ Choice of persistent storage tier.
141
+ dataset_id (`str`, *optional*):
142
+ Deprecated. Use `bucket_id` instead.
143
+ bucket_id (`str`, *optional*):
144
+ The ID of the Hugging Face Bucket to use for metric persistence. By default,
145
+ when a `space_id` is provided and `bucket_id` is not explicitly set, a
146
+ bucket is auto-generated from the space_id. Buckets provide
147
+ S3-like storage without git overhead - the SQLite database is stored directly
148
+ via `hf-mount` in the Space. Specify a Bucket with name like
149
+ `"username/bucketname"` or just `"bucketname"`.
150
+ config (`dict`, *optional*):
151
+ A dictionary of configuration options. Provided for compatibility with
152
+ `wandb.init()`.
153
+ resume (`str`, *optional*, defaults to `"never"`):
154
+ Controls how to handle resuming a run. Can be one of:
155
+
156
+ - `"must"`: Must resume the run with the given name, raises error if run
157
+ doesn't exist
158
+ - `"allow"`: Resume the run if it exists, otherwise create a new run
159
+ - `"never"`: Never resume a run, always create a new one
160
+ private (`bool`, *optional*):
161
+ Whether to make the Space private. If None (default), the repo will be
162
+ public unless the organization's default is private. This value is ignored
163
+ if the repo already exists.
164
+ settings (`Any`, *optional*):
165
+ Not used. Provided for compatibility with `wandb.init()`.
166
+ embed (`bool`, *optional*, defaults to `True`):
167
+ If running inside a Jupyter/Colab notebook, whether the dashboard should
168
+ automatically be embedded in the cell when trackio.init() is called. For
169
+ local runs, this launches a local Gradio app and embeds it. For Space runs,
170
+ this embeds the Space URL. In Colab, the local dashboard will be accessible
171
+ via a public share URL (default Gradio behavior).
172
+ auto_log_gpu (`bool` or `None`, *optional*, defaults to `None`):
173
+ Controls automatic GPU metrics logging. If `None` (default), GPU logging
174
+ is automatically enabled when `nvidia-ml-py` is installed and an NVIDIA
175
+ GPU or Apple M series is detected. Set to `True` to force enable or
176
+ `False` to disable.
177
+ gpu_log_interval (`float`, *optional*, defaults to `10.0`):
178
+ The interval in seconds between automatic GPU metric logs.
179
+ Only used when `auto_log_gpu=True`.
180
+ webhook_url (`str`, *optional*):
181
+ A webhook URL to POST alert payloads to when `trackio.alert()` is
182
+ called. Supports Slack and Discord webhook URLs natively (payloads
183
+ are formatted automatically). Can also be set via the
184
+ `TRACKIO_WEBHOOK_URL` environment variable. Individual alerts can
185
+ override this URL by passing `webhook_url` to `trackio.alert()`.
186
+ webhook_min_level (`AlertLevel` or `str`, *optional*):
187
+ Minimum alert level that should trigger webhook delivery.
188
+ For example, `AlertLevel.WARN` sends only `WARN` and `ERROR`
189
+ alerts to the webhook destination. Can also be set via
190
+ `TRACKIO_WEBHOOK_MIN_LEVEL`.
191
+ Returns:
192
+ `Run`: A [`Run`] object that can be used to log metrics and finish the run.
193
+ """
194
+ if settings is not None:
195
+ warnings.warn(
196
+ "* 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."
197
+ )
198
+
199
+ space_id = space_id or os.environ.get("TRACKIO_SPACE_ID")
200
+ bucket_id = bucket_id or os.environ.get("TRACKIO_BUCKET_ID")
201
+ if space_id is None and dataset_id is not None:
202
+ raise ValueError("Must provide a `space_id` when `dataset_id` is provided.")
203
+ if dataset_id is not None and bucket_id is not None:
204
+ raise ValueError("Cannot provide both `dataset_id` and `bucket_id`.")
205
+ try:
206
+ space_id, dataset_id, bucket_id = utils.preprocess_space_and_dataset_ids(
207
+ space_id, dataset_id, bucket_id
208
+ )
209
+ except LocalTokenNotFoundError as e:
210
+ raise LocalTokenNotFoundError(
211
+ f"You must be logged in to Hugging Face locally when `space_id` is provided to deploy to a Space. {e}"
212
+ ) from e
213
+
214
+ url = context_vars.current_server.get()
215
+
216
+ if space_id is not None:
217
+ if url is None:
218
+ url = space_id
219
+ context_vars.current_server.set(url)
220
+ context_vars.current_space_id.set(space_id)
221
+
222
+ _should_embed_local = False
223
+
224
+ if (
225
+ context_vars.current_project.get() is None
226
+ or context_vars.current_project.get() != project
227
+ ):
228
+ print(f"* Trackio project initialized: {project}")
229
+
230
+ if bucket_id is not None:
231
+ os.environ["TRACKIO_BUCKET_ID"] = bucket_id
232
+ bucket_url = f"https://huggingface.co/buckets/{bucket_id}"
233
+ print(
234
+ f"* Trackio metrics will be synced to Hugging Face Bucket: {bucket_url}"
235
+ )
236
+ elif dataset_id is not None:
237
+ os.environ["TRACKIO_DATASET_ID"] = dataset_id
238
+ print(
239
+ f"* Trackio metrics will be synced to Hugging Face Dataset: {dataset_id}"
240
+ )
241
+ if space_id is None:
242
+ print(f"* Trackio metrics logged to: {TRACKIO_DIR}")
243
+ _should_embed_local = embed and utils.is_in_notebook()
244
+ if not _should_embed_local:
245
+ utils.print_dashboard_instructions(project)
246
+ else:
247
+ deploy.create_space_if_not_exists(
248
+ space_id,
249
+ space_storage,
250
+ dataset_id,
251
+ bucket_id,
252
+ private,
253
+ )
254
+ user_name, space_name = space_id.split("/")
255
+ space_url = deploy.SPACE_HOST_URL.format(
256
+ user_name=user_name, space_name=space_name
257
+ )
258
+ if utils.is_in_notebook() and embed:
259
+ utils.embed_url_in_notebook(space_url)
260
+ context_vars.current_project.set(project)
261
+
262
+ if resume == "must":
263
+ if name is None:
264
+ raise ValueError("Must provide a run name when resume='must'")
265
+ if name not in SQLiteStorage.get_runs(project):
266
+ raise ValueError(f"Run '{name}' does not exist in project '{project}'")
267
+ resumed = True
268
+ elif resume == "allow":
269
+ resumed = name is not None and name in SQLiteStorage.get_runs(project)
270
+ elif resume == "never":
271
+ if name is not None and name in SQLiteStorage.get_runs(project):
272
+ warnings.warn(
273
+ f"* Warning: resume='never' but a run '{name}' already exists in "
274
+ f"project '{project}'. Generating a new name and instead. If you want "
275
+ "to resume this run, call init() with resume='must' or resume='allow'."
276
+ )
277
+ name = None
278
+ resumed = False
279
+ else:
280
+ raise ValueError("resume must be one of: 'must', 'allow', or 'never'")
281
+
282
+ if auto_log_gpu is None:
283
+ nvidia_available = gpu_available()
284
+ apple_available = apple_gpu_available()
285
+ auto_log_gpu = nvidia_available or apple_available
286
+ if project not in _projects_notified_auto_log_hw:
287
+ if nvidia_available:
288
+ print("* NVIDIA GPU detected, enabling automatic GPU metrics logging")
289
+ elif apple_available:
290
+ print(
291
+ "* Apple Silicon detected, enabling automatic system metrics logging"
292
+ )
293
+ if nvidia_available or apple_available:
294
+ _projects_notified_auto_log_hw.add(project)
295
+
296
+ run = Run(
297
+ url=url,
298
+ project=project,
299
+ client=None,
300
+ name=name,
301
+ group=group,
302
+ config=config,
303
+ space_id=space_id,
304
+ auto_log_gpu=auto_log_gpu,
305
+ gpu_log_interval=gpu_log_interval,
306
+ webhook_url=webhook_url,
307
+ webhook_min_level=webhook_min_level,
308
+ )
309
+
310
+ if space_id is not None:
311
+ SQLiteStorage.set_project_metadata(project, "space_id", space_id)
312
+ if SQLiteStorage.has_pending_data(project):
313
+ run._has_local_buffer = True
314
+
315
+ global _atexit_registered
316
+ if not _atexit_registered:
317
+ atexit.register(_cleanup_current_run)
318
+ _atexit_registered = True
319
+
320
+ if resumed:
321
+ print(f"* Resumed existing run: {run.name}")
322
+ else:
323
+ print(f"* Created new run: {run.name}")
324
+
325
+ context_vars.current_run.set(run)
326
+ globals()["config"] = run.config
327
+
328
+ if _should_embed_local:
329
+ show(project=project, open_browser=False, block_thread=False)
330
+
331
+ return run
332
+
333
+
334
+ def log(metrics: dict, step: int | None = None) -> None:
335
+ """
336
+ Logs metrics to the current run.
337
+
338
+ Args:
339
+ metrics (`dict`):
340
+ A dictionary of metrics to log.
341
+ step (`int`, *optional*):
342
+ The step number. If not provided, the step will be incremented
343
+ automatically.
344
+ """
345
+ run = context_vars.current_run.get()
346
+ if run is None:
347
+ raise RuntimeError("Call trackio.init() before trackio.log().")
348
+ run.log(
349
+ metrics=metrics,
350
+ step=step,
351
+ )
352
+
353
+
354
+ def log_system(metrics: dict) -> None:
355
+ """
356
+ Logs system metrics (GPU, etc.) to the current run using timestamps instead of steps.
357
+
358
+ Args:
359
+ metrics (`dict`):
360
+ A dictionary of system metrics to log.
361
+ """
362
+ run = context_vars.current_run.get()
363
+ if run is None:
364
+ raise RuntimeError("Call trackio.init() before trackio.log_system().")
365
+ run.log_system(metrics=metrics)
366
+
367
+
368
+ def log_gpu(run: Run | None = None, device: int | None = None) -> dict:
369
+ """
370
+ Log GPU metrics to the current or specified run as system metrics.
371
+ Automatically detects whether an NVIDIA or Apple GPU is available and calls
372
+ the appropriate logging method.
373
+
374
+ Args:
375
+ run: Optional Run instance. If None, uses current run from context.
376
+ device: CUDA device index to collect metrics from (NVIDIA GPUs only).
377
+ If None, collects from all GPUs visible to this process.
378
+ This parameter is ignored for Apple GPUs.
379
+
380
+ Returns:
381
+ dict: The GPU metrics that were logged.
382
+
383
+ Example:
384
+ ```python
385
+ import trackio
386
+
387
+ run = trackio.init(project="my-project")
388
+ trackio.log({"loss": 0.5})
389
+ trackio.log_gpu()
390
+ trackio.log_gpu(device=0)
391
+ ```
392
+ """
393
+ if run is None:
394
+ run = context_vars.current_run.get()
395
+ if run is None:
396
+ raise RuntimeError("Call trackio.init() before trackio.log_gpu().")
397
+
398
+ if gpu_available():
399
+ return _log_nvidia_gpu(run=run, device=device)
400
+ elif apple_gpu_available():
401
+ return _log_apple_gpu(run=run)
402
+ else:
403
+ warnings.warn(
404
+ "No GPU detected. Install nvidia-ml-py for NVIDIA GPU support "
405
+ "or psutil for Apple Silicon support."
406
+ )
407
+ return {}
408
+
409
+
410
+ def finish():
411
+ """
412
+ Finishes the current run.
413
+ """
414
+ run = context_vars.current_run.get()
415
+ if run is None:
416
+ raise RuntimeError("Call trackio.init() before trackio.finish().")
417
+ run.finish()
418
+
419
+
420
+ def alert(
421
+ title: str,
422
+ text: str | None = None,
423
+ level: AlertLevel = AlertLevel.WARN,
424
+ webhook_url: str | None = None,
425
+ ) -> None:
426
+ """
427
+ Fires an alert immediately on the current run. The alert is printed to the
428
+ terminal, stored in the database, and displayed in the dashboard. If a
429
+ webhook URL is configured (via `trackio.init()`, the `TRACKIO_WEBHOOK_URL`
430
+ environment variable, or the `webhook_url` parameter here), the alert is
431
+ also POSTed to that URL.
432
+
433
+ Args:
434
+ title (`str`):
435
+ A short title for the alert.
436
+ text (`str`, *optional*):
437
+ A longer description with details about the alert.
438
+ level (`AlertLevel`, *optional*, defaults to `AlertLevel.WARN`):
439
+ The severity level. One of `AlertLevel.INFO`, `AlertLevel.WARN`,
440
+ or `AlertLevel.ERROR`.
441
+ webhook_url (`str`, *optional*):
442
+ A webhook URL to send this specific alert to. Overrides any
443
+ URL set in `trackio.init()` or the `TRACKIO_WEBHOOK_URL`
444
+ environment variable. Supports Slack and Discord webhook
445
+ URLs natively.
446
+ """
447
+ run = context_vars.current_run.get()
448
+ if run is None:
449
+ raise RuntimeError("Call trackio.init() before trackio.alert().")
450
+ run.alert(title=title, text=text, level=level, webhook_url=webhook_url)
451
+
452
+
453
+ def delete_project(project: str, force: bool = False) -> bool:
454
+ """
455
+ Deletes a project by removing its local SQLite database.
456
+
457
+ Args:
458
+ project (`str`):
459
+ The name of the project to delete.
460
+ force (`bool`, *optional*, defaults to `False`):
461
+ If `True`, deletes the project without prompting for confirmation.
462
+ If `False`, prompts the user to confirm before deleting.
463
+
464
+ Returns:
465
+ `bool`: `True` if the project was deleted, `False` otherwise.
466
+ """
467
+ db_path = SQLiteStorage.get_project_db_path(project)
468
+
469
+ if not db_path.exists():
470
+ print(f"* Project '{project}' does not exist.")
471
+ return False
472
+
473
+ if not force:
474
+ response = input(
475
+ f"Are you sure you want to delete project '{project}'? "
476
+ f"This will permanently delete all runs and metrics. (y/N): "
477
+ )
478
+ if response.lower() not in ["y", "yes"]:
479
+ print("* Deletion cancelled.")
480
+ return False
481
+
482
+ try:
483
+ db_path.unlink()
484
+
485
+ for suffix in ("-wal", "-shm"):
486
+ sidecar = Path(str(db_path) + suffix)
487
+ if sidecar.exists():
488
+ sidecar.unlink()
489
+
490
+ print(f"* Project '{project}' has been deleted.")
491
+ return True
492
+ except Exception as e:
493
+ print(f"* Error deleting project '{project}': {e}")
494
+ return False
495
+
496
+
497
+ def save(
498
+ glob_str: str | Path,
499
+ project: str | None = None,
500
+ ) -> str:
501
+ """
502
+ Saves files to a project (not linked to a specific run). If Trackio is running
503
+ locally, the file(s) will be copied to the project's files directory. If Trackio is
504
+ running in a Space, the file(s) will be uploaded to the Space's files directory.
505
+
506
+ Args:
507
+ glob_str (`str` or `Path`):
508
+ The file path or glob pattern to save. Can be a single file or a pattern
509
+ matching multiple files (e.g., `"*.py"`, `"models/**/*.pth"`).
510
+ project (`str`, *optional*):
511
+ The name of the project to save files to. If not provided, uses the current
512
+ project from `trackio.init()`. If no project is initialized, raises an
513
+ error.
514
+
515
+ Returns:
516
+ `str`: The path where the file(s) were saved (project's files directory).
517
+
518
+ Example:
519
+ ```python
520
+ import trackio
521
+
522
+ trackio.init(project="my-project")
523
+ trackio.save("config.yaml")
524
+ trackio.save("models/*.pth")
525
+ ```
526
+ """
527
+ if project is None:
528
+ project = context_vars.current_project.get()
529
+ if project is None:
530
+ raise RuntimeError(
531
+ "No project specified. Either call trackio.init() first or provide a "
532
+ "project parameter to trackio.save()."
533
+ )
534
+
535
+ glob_str = Path(glob_str)
536
+ base_path = Path.cwd().resolve()
537
+
538
+ matched_files = []
539
+ if glob_str.is_file():
540
+ matched_files = [glob_str.resolve()]
541
+ else:
542
+ pattern = str(glob_str)
543
+ if not glob_str.is_absolute():
544
+ pattern = str((Path.cwd() / glob_str).resolve())
545
+ matched_files = [
546
+ Path(f).resolve()
547
+ for f in glob.glob(pattern, recursive=True)
548
+ if Path(f).is_file()
549
+ ]
550
+
551
+ if not matched_files:
552
+ raise ValueError(f"No files found matching pattern: {glob_str}")
553
+
554
+ current_run = context_vars.current_run.get()
555
+ is_local = (
556
+ current_run._is_local
557
+ if current_run is not None
558
+ else (context_vars.current_space_id.get() is None)
559
+ )
560
+
561
+ if is_local:
562
+ for file_path in matched_files:
563
+ try:
564
+ relative_to_base = file_path.relative_to(base_path)
565
+ except ValueError:
566
+ relative_to_base = Path(file_path.name)
567
+
568
+ if current_run is not None:
569
+ current_run._queue_upload(
570
+ file_path,
571
+ step=None,
572
+ relative_path=str(relative_to_base.parent),
573
+ use_run_name=False,
574
+ )
575
+ else:
576
+ media_path = get_project_media_path(
577
+ project=project,
578
+ run=None,
579
+ step=None,
580
+ relative_path=str(relative_to_base),
581
+ )
582
+ shutil.copy(str(file_path), str(media_path))
583
+ else:
584
+ url = context_vars.current_server.get()
585
+
586
+ upload_entries = []
587
+ for file_path in matched_files:
588
+ try:
589
+ relative_to_base = file_path.relative_to(base_path)
590
+ except ValueError:
591
+ relative_to_base = Path(file_path.name)
592
+
593
+ if current_run is not None:
594
+ current_run._queue_upload(
595
+ file_path,
596
+ step=None,
597
+ relative_path=str(relative_to_base.parent),
598
+ use_run_name=False,
599
+ )
600
+ else:
601
+ upload_entry: UploadEntry = {
602
+ "project": project,
603
+ "run": None,
604
+ "step": None,
605
+ "relative_path": str(relative_to_base),
606
+ "uploaded_file": handle_file(file_path),
607
+ }
608
+ upload_entries.append(upload_entry)
609
+
610
+ if upload_entries:
611
+ if url is None:
612
+ raise RuntimeError(
613
+ "No server available. Call trackio.init() before trackio.save() to start the server."
614
+ )
615
+
616
+ try:
617
+ client = Client(url, verbose=False, httpx_kwargs={"timeout": 90})
618
+ client.predict(
619
+ api_name="/bulk_upload_media",
620
+ uploads=upload_entries,
621
+ hf_token=huggingface_hub.utils.get_token(),
622
+ )
623
+ except Exception as e:
624
+ warnings.warn(
625
+ f"Failed to upload files: {e}. "
626
+ "Files may not be available in the dashboard."
627
+ )
628
+
629
+ return str(utils.MEDIA_DIR / project / "files")
630
+
631
+
632
+ def show(
633
+ project: str | None = None,
634
+ *,
635
+ theme: str | ThemeClass | None = None,
636
+ mcp_server: bool | None = None,
637
+ footer: bool = True,
638
+ color_palette: list[str] | None = None,
639
+ open_browser: bool = True,
640
+ block_thread: bool | None = None,
641
+ host: str | None = None,
642
+ ):
643
+ """
644
+ Launches the Trackio dashboard.
645
+
646
+ Args:
647
+ project (`str`, *optional*):
648
+ The name of the project whose runs to show. If not provided, all projects
649
+ will be shown and the user can select one.
650
+ theme (`str` or `ThemeClass`, *optional*):
651
+ A Gradio Theme to use for the dashboard instead of the default Gradio theme,
652
+ can be a built-in theme (e.g. `'soft'`, `'citrus'`), a theme from the Hub
653
+ (e.g. `"gstaff/xkcd"`), or a custom Theme class. If not provided, the
654
+ `TRACKIO_THEME` environment variable will be used, or if that is not set,
655
+ the default Gradio theme will be used.
656
+ mcp_server (`bool`, *optional*):
657
+ If `True`, the Trackio dashboard will be set up as an MCP server and certain
658
+ functions will be added as MCP tools. If `None` (default behavior), then the
659
+ `GRADIO_MCP_SERVER` environment variable will be used to determine if the
660
+ MCP server should be enabled (which is `"True"` on Hugging Face Spaces).
661
+ footer (`bool`, *optional*, defaults to `True`):
662
+ Whether to show the Gradio footer. When `False`, the footer will be hidden.
663
+ This can also be controlled via the `footer` query parameter in the URL.
664
+ color_palette (`list[str]`, *optional*):
665
+ A list of hex color codes to use for plot lines. If not provided, the
666
+ `TRACKIO_COLOR_PALETTE` environment variable will be used (comma-separated
667
+ hex codes), or if that is not set, the default color palette will be used.
668
+ Example: `['#FF0000', '#00FF00', '#0000FF']`
669
+ open_browser (`bool`, *optional*, defaults to `True`):
670
+ If `True` and not in a notebook, a new browser tab will be opened with the
671
+ dashboard. If `False`, the browser will not be opened.
672
+ block_thread (`bool`, *optional*):
673
+ If `True`, the main thread will be blocked until the dashboard is closed.
674
+ If `None` (default behavior), then the main thread will not be blocked if the
675
+ dashboard is launched in a notebook, otherwise the main thread will be blocked.
676
+ host (`str`, *optional*):
677
+ The host to bind the server to. If not provided, defaults to `'127.0.0.1'`
678
+ (localhost only). Set to `'0.0.0.0'` to allow remote access.
679
+
680
+ Returns:
681
+ `app`: The Gradio app object corresponding to the dashboard launched by Trackio.
682
+ `url`: The local URL of the dashboard.
683
+ `share_url`: The public share URL of the dashboard.
684
+ `full_url`: The full URL of the dashboard including the write token (will use the public share URL if launched publicly, otherwise the local URL).
685
+ """
686
+ if color_palette is not None:
687
+ os.environ["TRACKIO_COLOR_PALETTE"] = ",".join(color_palette)
688
+
689
+ theme = theme or os.environ.get("TRACKIO_THEME")
690
+
691
+ _mcp_server = (
692
+ mcp_server
693
+ if mcp_server is not None
694
+ else os.environ.get("GRADIO_MCP_SERVER", "False") == "True"
695
+ )
696
+
697
+ server = make_trackio_server()
698
+ mount_frontend(server)
699
+
700
+ _, url, share_url = server.launch(
701
+ quiet=True,
702
+ inline=False,
703
+ prevent_thread_lock=True,
704
+ favicon_path=TRACKIO_LOGO_DIR / "trackio_logo_light.png",
705
+ allowed_paths=[TRACKIO_LOGO_DIR, TRACKIO_DIR],
706
+ mcp_server=_mcp_server,
707
+ theme=theme,
708
+ server_name=host,
709
+ )
710
+
711
+ base_url = share_url + "/" if share_url else url
712
+ dashboard_url = base_url.rstrip("/") + "/"
713
+ if project:
714
+ dashboard_url += f"?project={project}"
715
+ full_url = utils.get_full_url(
716
+ base_url.rstrip("/"),
717
+ project=project,
718
+ write_token=server.write_token,
719
+ footer=footer,
720
+ )
721
+
722
+ if not utils.is_in_notebook():
723
+ print(f"* Trackio UI launched at: {dashboard_url}")
724
+ print(f"* Gradio API available at: {base_url}")
725
+ if open_browser:
726
+ webbrowser.open(dashboard_url)
727
+ block_thread = block_thread if block_thread is not None else True
728
+ else:
729
+ utils.embed_url_in_notebook(dashboard_url)
730
+ block_thread = block_thread if block_thread is not None else False
731
+
732
+ if block_thread:
733
+ utils.block_main_thread_until_keyboard_interrupt()
734
+ return TupleNoPrint((server, url, share_url, full_url))
trackio/alerts.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ import ssl
4
+ import urllib.request
5
+ from enum import Enum
6
+
7
+ try:
8
+ import certifi
9
+
10
+ _SSL_CONTEXT = ssl.create_default_context(cafile=certifi.where())
11
+ except ImportError:
12
+ _SSL_CONTEXT = None
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class AlertLevel(str, Enum):
18
+ INFO = "info"
19
+ WARN = "warn"
20
+ ERROR = "error"
21
+
22
+
23
+ ALERT_LEVEL_ORDER = {
24
+ AlertLevel.INFO: 0,
25
+ AlertLevel.WARN: 1,
26
+ AlertLevel.ERROR: 2,
27
+ }
28
+
29
+ ALERT_COLORS = {
30
+ AlertLevel.INFO: "\033[94m",
31
+ AlertLevel.WARN: "\033[93m",
32
+ AlertLevel.ERROR: "\033[91m",
33
+ }
34
+ RESET_COLOR = "\033[0m"
35
+
36
+ LEVEL_EMOJI = {
37
+ AlertLevel.INFO: "ℹ️",
38
+ AlertLevel.WARN: "⚠️",
39
+ AlertLevel.ERROR: "🚨",
40
+ }
41
+
42
+
43
+ def format_alert_terminal(
44
+ level: AlertLevel, title: str, text: str | None, step: int | None
45
+ ) -> str:
46
+ color = ALERT_COLORS.get(level, "")
47
+ step_str = f" (step {step})" if step is not None else ""
48
+ if text:
49
+ return f"{color}[TRACKIO {level.value.upper()}]{RESET_COLOR} {title}: {text}{step_str}"
50
+ return f"{color}[TRACKIO {level.value.upper()}]{RESET_COLOR} {title}{step_str}"
51
+
52
+
53
+ def _is_slack_url(url: str) -> bool:
54
+ return "hooks.slack.com" in url
55
+
56
+
57
+ def _is_discord_url(url: str) -> bool:
58
+ return "discord.com/api/webhooks" in url or "discordapp.com/api/webhooks" in url
59
+
60
+
61
+ def _build_slack_payload(
62
+ level: AlertLevel,
63
+ title: str,
64
+ text: str | None,
65
+ project: str,
66
+ run: str,
67
+ step: int | None,
68
+ ) -> dict:
69
+ emoji = LEVEL_EMOJI.get(level, "")
70
+ step_str = f" • Step {step}" if step is not None else ""
71
+ header = f"{emoji} *[{level.value.upper()}] {title}*"
72
+ context = f"Project: {project} • Run: {run}{step_str}"
73
+ blocks = [
74
+ {"type": "section", "text": {"type": "mrkdwn", "text": header}},
75
+ ]
76
+ if text:
77
+ blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": text}})
78
+ blocks.append(
79
+ {"type": "context", "elements": [{"type": "mrkdwn", "text": context}]}
80
+ )
81
+ return {"blocks": blocks}
82
+
83
+
84
+ def _build_discord_payload(
85
+ level: AlertLevel,
86
+ title: str,
87
+ text: str | None,
88
+ project: str,
89
+ run: str,
90
+ step: int | None,
91
+ ) -> dict:
92
+ color_map = {
93
+ AlertLevel.INFO: 3447003,
94
+ AlertLevel.WARN: 16776960,
95
+ AlertLevel.ERROR: 15158332,
96
+ }
97
+ emoji = LEVEL_EMOJI.get(level, "")
98
+ step_str = f" • Step {step}" if step is not None else ""
99
+ embed = {
100
+ "title": f"{emoji} [{level.value.upper()}] {title}",
101
+ "color": color_map.get(level, 0),
102
+ "footer": {"text": f"Project: {project} • Run: {run}{step_str}"},
103
+ }
104
+ if text:
105
+ embed["description"] = text
106
+ return {"embeds": [embed]}
107
+
108
+
109
+ def _build_generic_payload(
110
+ level: AlertLevel,
111
+ title: str,
112
+ text: str | None,
113
+ project: str,
114
+ run: str,
115
+ step: int | None,
116
+ timestamp: str | None,
117
+ ) -> dict:
118
+ return {
119
+ "level": level.value,
120
+ "title": title,
121
+ "text": text,
122
+ "project": project,
123
+ "run": run,
124
+ "step": step,
125
+ "timestamp": timestamp,
126
+ }
127
+
128
+
129
+ def parse_alert_level(level: AlertLevel | str) -> AlertLevel:
130
+ if isinstance(level, AlertLevel):
131
+ return level
132
+ normalized = level.lower().strip()
133
+ try:
134
+ return AlertLevel(normalized)
135
+ except ValueError as e:
136
+ allowed = ", ".join(lvl.value for lvl in AlertLevel)
137
+ raise ValueError(
138
+ f"Invalid alert level '{level}'. Expected one of: {allowed}."
139
+ ) from e
140
+
141
+
142
+ def resolve_webhook_min_level(
143
+ webhook_min_level: AlertLevel | str | None,
144
+ ) -> AlertLevel | None:
145
+ if webhook_min_level is None:
146
+ return None
147
+ return parse_alert_level(webhook_min_level)
148
+
149
+
150
+ def should_send_webhook(
151
+ level: AlertLevel, webhook_min_level: AlertLevel | None
152
+ ) -> bool:
153
+ if webhook_min_level is None:
154
+ return True
155
+ return ALERT_LEVEL_ORDER[level] >= ALERT_LEVEL_ORDER[webhook_min_level]
156
+
157
+
158
+ def send_webhook(
159
+ url: str,
160
+ level: AlertLevel,
161
+ title: str,
162
+ text: str | None,
163
+ project: str,
164
+ run: str,
165
+ step: int | None,
166
+ timestamp: str | None = None,
167
+ ) -> None:
168
+ if _is_slack_url(url):
169
+ payload = _build_slack_payload(level, title, text, project, run, step)
170
+ elif _is_discord_url(url):
171
+ payload = _build_discord_payload(level, title, text, project, run, step)
172
+ else:
173
+ payload = _build_generic_payload(
174
+ level, title, text, project, run, step, timestamp
175
+ )
176
+
177
+ data = json.dumps(payload).encode("utf-8")
178
+ req = urllib.request.Request(
179
+ url, data=data, headers={"Content-Type": "application/json"}
180
+ )
181
+ try:
182
+ urllib.request.urlopen(req, timeout=10, context=_SSL_CONTEXT)
183
+ except Exception as e:
184
+ logger.warning(f"Failed to send webhook to {url}: {e}")
trackio/api.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Iterator
2
+
3
+ from trackio.sqlite_storage import SQLiteStorage
4
+
5
+
6
+ class Run:
7
+ def __init__(self, project: str, name: str):
8
+ self.project = project
9
+ self.name = name
10
+ self._config = None
11
+
12
+ @property
13
+ def id(self) -> str:
14
+ return self.name
15
+
16
+ @property
17
+ def config(self) -> dict | None:
18
+ if self._config is None:
19
+ self._config = SQLiteStorage.get_run_config(self.project, self.name)
20
+ return self._config
21
+
22
+ def alerts(self, level: str | None = None, since: str | None = None) -> list[dict]:
23
+ return SQLiteStorage.get_alerts(
24
+ self.project, run_name=self.name, level=level, since=since
25
+ )
26
+
27
+ def delete(self) -> bool:
28
+ return SQLiteStorage.delete_run(self.project, self.name)
29
+
30
+ def move(self, new_project: str) -> bool:
31
+ success = SQLiteStorage.move_run(self.project, self.name, new_project)
32
+ if success:
33
+ self.project = new_project
34
+ return success
35
+
36
+ def rename(self, new_name: str) -> "Run":
37
+ SQLiteStorage.rename_run(self.project, self.name, new_name)
38
+ self.name = new_name
39
+ return self
40
+
41
+ def __repr__(self) -> str:
42
+ return f"<Run {self.name} in project {self.project}>"
43
+
44
+
45
+ class Runs:
46
+ def __init__(self, project: str):
47
+ self.project = project
48
+ self._runs = None
49
+
50
+ def _load_runs(self):
51
+ if self._runs is None:
52
+ run_names = SQLiteStorage.get_runs(self.project)
53
+ self._runs = [Run(self.project, name) for name in run_names]
54
+
55
+ def __iter__(self) -> Iterator[Run]:
56
+ self._load_runs()
57
+ return iter(self._runs)
58
+
59
+ def __getitem__(self, index: int) -> Run:
60
+ self._load_runs()
61
+ return self._runs[index]
62
+
63
+ def __len__(self) -> int:
64
+ self._load_runs()
65
+ return len(self._runs)
66
+
67
+ def __repr__(self) -> str:
68
+ self._load_runs()
69
+ return f"<Runs project={self.project} count={len(self._runs)}>"
70
+
71
+
72
+ class Api:
73
+ def runs(self, project: str) -> Runs:
74
+ if not SQLiteStorage.get_project_db_path(project).exists():
75
+ raise ValueError(f"Project '{project}' does not exist")
76
+ return Runs(project)
77
+
78
+ def alerts(
79
+ self,
80
+ project: str,
81
+ run: str | None = None,
82
+ level: str | None = None,
83
+ since: str | None = None,
84
+ ) -> list[dict]:
85
+ if not SQLiteStorage.get_project_db_path(project).exists():
86
+ raise ValueError(f"Project '{project}' does not exist")
87
+ return SQLiteStorage.get_alerts(project, run_name=run, level=level, since=since)
trackio/apple_gpu.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import platform
2
+ import subprocess
3
+ import sys
4
+ import threading
5
+ import warnings
6
+ from typing import TYPE_CHECKING, Any
7
+
8
+ if TYPE_CHECKING:
9
+ from trackio.run import Run
10
+
11
+ psutil: Any = None
12
+ PSUTIL_AVAILABLE = False
13
+ _monitor_lock = threading.Lock()
14
+
15
+
16
+ def _ensure_psutil():
17
+ global PSUTIL_AVAILABLE, psutil
18
+ if PSUTIL_AVAILABLE:
19
+ return psutil
20
+ try:
21
+ import psutil as _psutil
22
+
23
+ psutil = _psutil
24
+ PSUTIL_AVAILABLE = True
25
+ return psutil
26
+ except ImportError:
27
+ raise ImportError(
28
+ "psutil is required for Apple Silicon monitoring. "
29
+ "Install it with: pip install psutil"
30
+ )
31
+
32
+
33
+ def is_apple_silicon() -> bool:
34
+ """Check if running on Apple Silicon (M1/M2/M3/M4)."""
35
+ if platform.system() != "Darwin":
36
+ return False
37
+
38
+ try:
39
+ result = subprocess.run(
40
+ ["sysctl", "-n", "machdep.cpu.brand_string"],
41
+ capture_output=True,
42
+ text=True,
43
+ timeout=1,
44
+ )
45
+ cpu_brand = result.stdout.strip()
46
+ return "Apple" in cpu_brand
47
+ except Exception:
48
+ return False
49
+
50
+
51
+ def get_gpu_info() -> dict[str, Any]:
52
+ """Get Apple GPU information using ioreg."""
53
+ try:
54
+ result = subprocess.run(
55
+ ["ioreg", "-r", "-d", "1", "-w", "0", "-c", "IOAccelerator"],
56
+ capture_output=True,
57
+ text=True,
58
+ timeout=2,
59
+ )
60
+
61
+ if result.returncode == 0 and result.stdout:
62
+ lines = result.stdout.strip().split("\n")
63
+ for line in lines:
64
+ if "IOAccelerator" in line and "class" in line:
65
+ return {"detected": True, "type": "Apple GPU"}
66
+ else:
67
+ print("Error collecting Apple GPU info. ioreg stdout was:", file=sys.stderr)
68
+ print(result.stdout, file=sys.stderr)
69
+ print("ioreg stderr was:", file=sys.stderr)
70
+ print(result.stderr, file=sys.stderr)
71
+
72
+ result = subprocess.run(
73
+ ["system_profiler", "SPDisplaysDataType"],
74
+ capture_output=True,
75
+ text=True,
76
+ timeout=3,
77
+ )
78
+
79
+ if result.returncode == 0 and "Apple" in result.stdout:
80
+ for line in result.stdout.split("\n"):
81
+ if "Chipset Model:" in line:
82
+ model = line.split(":")[-1].strip()
83
+ return {"detected": True, "type": model}
84
+
85
+ except Exception:
86
+ pass
87
+
88
+ return {"detected": False}
89
+
90
+
91
+ def apple_gpu_available() -> bool:
92
+ """
93
+ Check if Apple GPU monitoring is available.
94
+
95
+ Returns True if running on Apple Silicon (M-series chips) and psutil is installed.
96
+ """
97
+ try:
98
+ _ensure_psutil()
99
+ return is_apple_silicon()
100
+ except ImportError:
101
+ return False
102
+ except Exception:
103
+ return False
104
+
105
+
106
+ def collect_apple_metrics() -> dict:
107
+ """
108
+ Collect system metrics for Apple Silicon.
109
+
110
+ Returns:
111
+ Dictionary of system metrics including CPU, memory, and GPU info.
112
+ """
113
+ if not PSUTIL_AVAILABLE:
114
+ try:
115
+ _ensure_psutil()
116
+ except ImportError:
117
+ return {}
118
+
119
+ metrics = {}
120
+
121
+ try:
122
+ cpu_percent = psutil.cpu_percent(interval=0.1, percpu=False)
123
+ metrics["cpu/utilization"] = cpu_percent
124
+ except Exception:
125
+ pass
126
+
127
+ try:
128
+ cpu_percents = psutil.cpu_percent(interval=0.1, percpu=True)
129
+ for i, percent in enumerate(cpu_percents):
130
+ metrics[f"cpu/{i}/utilization"] = percent
131
+ except Exception:
132
+ pass
133
+
134
+ try:
135
+ cpu_freq = psutil.cpu_freq()
136
+ if cpu_freq:
137
+ metrics["cpu/frequency"] = cpu_freq.current
138
+ if cpu_freq.max > 0:
139
+ metrics["cpu/frequency_max"] = cpu_freq.max
140
+ except Exception:
141
+ pass
142
+
143
+ try:
144
+ mem = psutil.virtual_memory()
145
+ metrics["memory/used"] = mem.used / (1024**3)
146
+ metrics["memory/total"] = mem.total / (1024**3)
147
+ metrics["memory/available"] = mem.available / (1024**3)
148
+ metrics["memory/percent"] = mem.percent
149
+ except Exception:
150
+ pass
151
+
152
+ try:
153
+ swap = psutil.swap_memory()
154
+ metrics["swap/used"] = swap.used / (1024**3)
155
+ metrics["swap/total"] = swap.total / (1024**3)
156
+ metrics["swap/percent"] = swap.percent
157
+ except Exception:
158
+ pass
159
+
160
+ try:
161
+ sensors_temps = psutil.sensors_temperatures()
162
+ if sensors_temps:
163
+ for name, entries in sensors_temps.items():
164
+ for i, entry in enumerate(entries):
165
+ label = entry.label or f"{name}_{i}"
166
+ metrics[f"temp/{label}"] = entry.current
167
+ except Exception:
168
+ pass
169
+
170
+ gpu_info = get_gpu_info()
171
+ if gpu_info.get("detected"):
172
+ metrics["gpu/detected"] = 1
173
+ if "type" in gpu_info:
174
+ pass
175
+
176
+ return metrics
177
+
178
+
179
+ class AppleGpuMonitor:
180
+ def __init__(self, run: "Run", interval: float = 10.0):
181
+ self._run = run
182
+ self._interval = interval
183
+ self._stop_flag = threading.Event()
184
+ self._thread: "threading.Thread | None" = None
185
+
186
+ def start(self):
187
+ if not is_apple_silicon():
188
+ warnings.warn(
189
+ "auto_log_gpu=True but not running on Apple Silicon. "
190
+ "Apple GPU logging disabled."
191
+ )
192
+ return
193
+
194
+ if not PSUTIL_AVAILABLE:
195
+ try:
196
+ _ensure_psutil()
197
+ except ImportError:
198
+ warnings.warn(
199
+ "auto_log_gpu=True but psutil not installed. "
200
+ "Install with: pip install psutil"
201
+ )
202
+ return
203
+
204
+ self._thread = threading.Thread(target=self._monitor_loop, daemon=True)
205
+ self._thread.start()
206
+
207
+ def stop(self):
208
+ self._stop_flag.set()
209
+ if self._thread is not None:
210
+ self._thread.join(timeout=2.0)
211
+
212
+ def _monitor_loop(self):
213
+ while not self._stop_flag.is_set():
214
+ try:
215
+ metrics = collect_apple_metrics()
216
+ if metrics:
217
+ self._run.log_system(metrics)
218
+ except Exception:
219
+ pass
220
+
221
+ self._stop_flag.wait(timeout=self._interval)
222
+
223
+
224
+ def log_apple_gpu(run: "Run | None" = None) -> dict:
225
+ """
226
+ Log Apple Silicon system metrics to the current or specified run.
227
+
228
+ Args:
229
+ run: Optional Run instance. If None, uses current run from context.
230
+
231
+ Returns:
232
+ dict: The system metrics that were logged.
233
+
234
+ Example:
235
+ ```python
236
+ import trackio
237
+
238
+ run = trackio.init(project="my-project")
239
+ trackio.log({"loss": 0.5})
240
+ trackio.log_apple_gpu()
241
+ ```
242
+ """
243
+ from trackio import context_vars
244
+
245
+ if run is None:
246
+ run = context_vars.current_run.get()
247
+ if run is None:
248
+ raise RuntimeError("Call trackio.init() before trackio.log_apple_gpu().")
249
+
250
+ metrics = collect_apple_metrics()
251
+ if metrics:
252
+ run.log_system(metrics)
253
+ return metrics
trackio/assets/badge.png ADDED
trackio/assets/trackio_logo_dark.png ADDED
trackio/assets/trackio_logo_light.png ADDED
trackio/assets/trackio_logo_old.png ADDED

Git LFS Details

  • SHA256: 3922c4d1e465270ad4d8abb12023f3beed5d9f7f338528a4c0ac21dcf358a1c8
  • Pointer size: 131 Bytes
  • Size of remote file: 487 kB
trackio/assets/trackio_logo_type_dark.png ADDED
trackio/assets/trackio_logo_type_dark_transparent.png ADDED
trackio/assets/trackio_logo_type_light.png ADDED
trackio/assets/trackio_logo_type_light_transparent.png ADDED
trackio/bucket_storage.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import shutil
2
+ import tempfile
3
+ from pathlib import Path
4
+
5
+ import huggingface_hub
6
+ from huggingface_hub import sync_bucket
7
+
8
+ from trackio.sqlite_storage import SQLiteStorage
9
+ from trackio.utils import MEDIA_DIR, TRACKIO_DIR
10
+
11
+
12
+ def create_bucket_if_not_exists(bucket_id: str, private: bool | None = None) -> None:
13
+ huggingface_hub.create_bucket(bucket_id, private=private, exist_ok=True)
14
+
15
+
16
+ def download_bucket_to_trackio_dir(bucket_id: str) -> None:
17
+ TRACKIO_DIR.mkdir(parents=True, exist_ok=True)
18
+ sync_bucket(
19
+ source=f"hf://buckets/{bucket_id}",
20
+ dest=str(TRACKIO_DIR.parent),
21
+ quiet=True,
22
+ )
23
+
24
+
25
+ def upload_project_to_bucket(project: str, bucket_id: str) -> None:
26
+ db_path = SQLiteStorage.get_project_db_path(project)
27
+ if not db_path.exists():
28
+ raise FileNotFoundError(f"No database found for project '{project}'")
29
+
30
+ with SQLiteStorage._get_connection(
31
+ db_path, configure_pragmas=False, row_factory=None
32
+ ) as conn:
33
+ conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
34
+
35
+ files_to_add = [(str(db_path), f"trackio/{db_path.name}")]
36
+
37
+ media_dir = MEDIA_DIR / project
38
+ if media_dir.exists():
39
+ for media_file in media_dir.rglob("*"):
40
+ if media_file.is_file():
41
+ rel = media_file.relative_to(TRACKIO_DIR)
42
+ files_to_add.append((str(media_file), f"trackio/{rel}"))
43
+
44
+ huggingface_hub.batch_bucket_files(bucket_id, add=files_to_add)
45
+
46
+
47
+ def _download_db_from_bucket(project: str, bucket_id: str) -> bool:
48
+ db_filename = SQLiteStorage.get_project_db_filename(project)
49
+ remote_path = f"trackio/{db_filename}"
50
+ local_path = SQLiteStorage.get_project_db_path(project)
51
+ local_path.parent.mkdir(parents=True, exist_ok=True)
52
+ try:
53
+ huggingface_hub.download_bucket_files(
54
+ bucket_id,
55
+ files=[(remote_path, str(local_path))],
56
+ )
57
+ return local_path.exists()
58
+ except Exception:
59
+ return False
60
+
61
+
62
+ def _local_db_has_data(project: str) -> bool:
63
+ db_path = SQLiteStorage.get_project_db_path(project)
64
+ if not db_path.exists() or db_path.stat().st_size == 0:
65
+ return False
66
+ try:
67
+ with SQLiteStorage._get_connection(
68
+ db_path, configure_pragmas=False, row_factory=None
69
+ ) as conn:
70
+ count = conn.execute("SELECT COUNT(*) FROM metrics").fetchone()[0]
71
+ return count > 0
72
+ except Exception:
73
+ return False
74
+
75
+
76
+ def upload_project_to_bucket_for_static(project: str, bucket_id: str) -> None:
77
+ if not _local_db_has_data(project):
78
+ _download_db_from_bucket(project, bucket_id)
79
+
80
+ with tempfile.TemporaryDirectory() as tmp_dir:
81
+ output_dir = Path(tmp_dir)
82
+ SQLiteStorage.export_for_static_space(project, output_dir)
83
+
84
+ media_dir = MEDIA_DIR / project
85
+ if media_dir.exists():
86
+ shutil.copytree(media_dir, output_dir / "media")
87
+
88
+ files_to_add = []
89
+ for f in output_dir.rglob("*"):
90
+ if f.is_file():
91
+ rel = f.relative_to(output_dir)
92
+ files_to_add.append((str(f), str(rel)))
93
+
94
+ huggingface_hub.batch_bucket_files(bucket_id, add=files_to_add)
trackio/cli.py ADDED
@@ -0,0 +1,1238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+
4
+ from trackio import show, sync
5
+ from trackio.cli_helpers import (
6
+ error_exit,
7
+ format_alerts,
8
+ format_json,
9
+ format_list,
10
+ format_metric_values,
11
+ format_project_summary,
12
+ format_run_summary,
13
+ format_snapshot,
14
+ format_system_metric_names,
15
+ format_system_metrics,
16
+ )
17
+ from trackio.markdown import Markdown
18
+ from trackio.server import get_project_summary, get_run_summary
19
+ from trackio.sqlite_storage import SQLiteStorage
20
+
21
+
22
+ def _get_space(args):
23
+ return getattr(args, "space", None)
24
+
25
+
26
+ def _get_remote(args):
27
+ from trackio.remote_client import RemoteClient
28
+
29
+ space = _get_space(args)
30
+ if not space:
31
+ return None
32
+ hf_token = getattr(args, "hf_token", None)
33
+ return RemoteClient(space, hf_token=hf_token)
34
+
35
+
36
+ def _handle_status():
37
+ print("Reading local Trackio projects...\n")
38
+ projects = SQLiteStorage.get_projects()
39
+ if not projects:
40
+ print("No Trackio projects found.")
41
+ return
42
+
43
+ local_projects = []
44
+ synced_projects = []
45
+ unsynced_projects = []
46
+
47
+ for project in projects:
48
+ space_id = SQLiteStorage.get_space_id(project)
49
+ if space_id is None:
50
+ local_projects.append(project)
51
+ elif SQLiteStorage.has_pending_data(project):
52
+ unsynced_projects.append(project)
53
+ else:
54
+ synced_projects.append(project)
55
+
56
+ print("Finished reading Trackio projects")
57
+ if local_projects:
58
+ print(f" * {len(local_projects)} local trackio project(s) [OK]")
59
+ if synced_projects:
60
+ print(f" * {len(synced_projects)} trackio project(s) synced to Spaces [OK]")
61
+ if unsynced_projects:
62
+ print(
63
+ f" * {len(unsynced_projects)} trackio project(s) with unsynced changes [WARNING]:"
64
+ )
65
+ for p in unsynced_projects:
66
+ print(f" - {p}")
67
+
68
+ if unsynced_projects:
69
+ print(
70
+ f"\nRun `trackio sync --project {unsynced_projects[0]}` to sync. "
71
+ "Or run `trackio sync --all` to sync all unsynced changes."
72
+ )
73
+
74
+
75
+ def _handle_sync(args):
76
+ from trackio.deploy import sync_incremental
77
+
78
+ if args.sync_all and args.project:
79
+ error_exit("Cannot use --all and --project together.")
80
+ if not args.sync_all and not args.project:
81
+ error_exit("Must provide either --project or --all.")
82
+
83
+ if args.sync_all:
84
+ projects = SQLiteStorage.get_projects()
85
+ synced_any = False
86
+ for project in projects:
87
+ space_id = SQLiteStorage.get_space_id(project)
88
+ if space_id and SQLiteStorage.has_pending_data(project):
89
+ sync_incremental(
90
+ project, space_id, private=args.private, pending_only=True
91
+ )
92
+ synced_any = True
93
+ if not synced_any:
94
+ print("No projects with unsynced data found.")
95
+ else:
96
+ space_id = args.space_id
97
+ if space_id is None:
98
+ space_id = SQLiteStorage.get_space_id(args.project)
99
+ sync(
100
+ project=args.project,
101
+ space_id=space_id,
102
+ private=args.private,
103
+ force=args.force,
104
+ sdk=args.sdk,
105
+ )
106
+
107
+
108
+ def _extract_reports(
109
+ run: str, logs: list[dict], report_name: str | None = None
110
+ ) -> list[dict]:
111
+ reports = []
112
+ for log in logs:
113
+ timestamp = log.get("timestamp")
114
+ step = log.get("step")
115
+ for key, value in log.items():
116
+ if report_name is not None and key != report_name:
117
+ continue
118
+ if isinstance(value, dict) and value.get("_type") == Markdown.TYPE:
119
+ content = value.get("_value")
120
+ if isinstance(content, str):
121
+ reports.append(
122
+ {
123
+ "run": run,
124
+ "report": key,
125
+ "step": step,
126
+ "timestamp": timestamp,
127
+ "content": content,
128
+ }
129
+ )
130
+ return reports
131
+
132
+
133
+ def main():
134
+ parser = argparse.ArgumentParser(description="Trackio CLI")
135
+ parser.add_argument(
136
+ "--space",
137
+ required=False,
138
+ help="HF Space ID (e.g. 'user/space') or Space URL to query remotely.",
139
+ )
140
+ parser.add_argument(
141
+ "--hf-token",
142
+ required=False,
143
+ help="HF token for accessing private Spaces.",
144
+ )
145
+ subparsers = parser.add_subparsers(dest="command")
146
+
147
+ ui_parser = subparsers.add_parser(
148
+ "show", help="Show the Trackio dashboard UI for a project"
149
+ )
150
+ ui_parser.add_argument(
151
+ "--project", required=False, help="Project name to show in the dashboard"
152
+ )
153
+ ui_parser.add_argument(
154
+ "--theme",
155
+ required=False,
156
+ default="default",
157
+ 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').",
158
+ )
159
+ ui_parser.add_argument(
160
+ "--mcp-server",
161
+ action="store_true",
162
+ 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.",
163
+ )
164
+ ui_parser.add_argument(
165
+ "--footer",
166
+ action="store_true",
167
+ default=True,
168
+ help="Show the Gradio footer. Use --no-footer to hide it.",
169
+ )
170
+ ui_parser.add_argument(
171
+ "--no-footer",
172
+ dest="footer",
173
+ action="store_false",
174
+ help="Hide the Gradio footer.",
175
+ )
176
+ ui_parser.add_argument(
177
+ "--color-palette",
178
+ required=False,
179
+ help="Comma-separated list of hex color codes for plot lines (e.g. '#FF0000,#00FF00,#0000FF'). If not provided, the TRACKIO_COLOR_PALETTE environment variable will be used, or the default palette if not set.",
180
+ )
181
+ ui_parser.add_argument(
182
+ "--host",
183
+ required=False,
184
+ help="Host to bind the server to (e.g. '0.0.0.0' for remote access). If not provided, defaults to '127.0.0.1' (localhost only).",
185
+ )
186
+
187
+ subparsers.add_parser(
188
+ "status",
189
+ help="Show the status of all local Trackio projects, including sync status.",
190
+ )
191
+
192
+ sync_parser = subparsers.add_parser(
193
+ "sync",
194
+ help="Sync a local project's database to a Hugging Face Space. If the Space does not exist, it will be created.",
195
+ )
196
+ sync_parser.add_argument(
197
+ "--project",
198
+ required=False,
199
+ help="The name of the local project.",
200
+ )
201
+ sync_parser.add_argument(
202
+ "--space-id",
203
+ required=False,
204
+ help="The Hugging Face Space ID where the project will be synced (e.g. username/space_id). If not provided, uses the previously-configured Space.",
205
+ )
206
+ sync_parser.add_argument(
207
+ "--all",
208
+ action="store_true",
209
+ dest="sync_all",
210
+ help="Sync all projects that have unsynced data to their configured Spaces.",
211
+ )
212
+ sync_parser.add_argument(
213
+ "--private",
214
+ action="store_true",
215
+ help="Make the Hugging Face Space private if creating a new Space. By default, the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.",
216
+ )
217
+ sync_parser.add_argument(
218
+ "--force",
219
+ action="store_true",
220
+ help="Overwrite the existing database without prompting for confirmation.",
221
+ )
222
+ sync_parser.add_argument(
223
+ "--sdk",
224
+ choices=["gradio", "static"],
225
+ default="gradio",
226
+ help="The type of Space to deploy. 'gradio' (default) deploys a live Gradio server. 'static' deploys a static Space that reads from an HF Bucket.",
227
+ )
228
+
229
+ list_parser = subparsers.add_parser(
230
+ "list",
231
+ help="List projects, runs, or metrics",
232
+ )
233
+ list_subparsers = list_parser.add_subparsers(dest="list_type", required=True)
234
+
235
+ list_projects_parser = list_subparsers.add_parser(
236
+ "projects",
237
+ help="List all projects",
238
+ )
239
+ list_projects_parser.add_argument(
240
+ "--json",
241
+ action="store_true",
242
+ help="Output in JSON format",
243
+ )
244
+
245
+ list_runs_parser = list_subparsers.add_parser(
246
+ "runs",
247
+ help="List runs for a project",
248
+ )
249
+ list_runs_parser.add_argument(
250
+ "--project",
251
+ required=True,
252
+ help="Project name",
253
+ )
254
+ list_runs_parser.add_argument(
255
+ "--json",
256
+ action="store_true",
257
+ help="Output in JSON format",
258
+ )
259
+
260
+ list_metrics_parser = list_subparsers.add_parser(
261
+ "metrics",
262
+ help="List metrics for a run",
263
+ )
264
+ list_metrics_parser.add_argument(
265
+ "--project",
266
+ required=True,
267
+ help="Project name",
268
+ )
269
+ list_metrics_parser.add_argument(
270
+ "--run",
271
+ required=True,
272
+ help="Run name",
273
+ )
274
+ list_metrics_parser.add_argument(
275
+ "--json",
276
+ action="store_true",
277
+ help="Output in JSON format",
278
+ )
279
+
280
+ list_system_metrics_parser = list_subparsers.add_parser(
281
+ "system-metrics",
282
+ help="List system metrics for a run",
283
+ )
284
+ list_system_metrics_parser.add_argument(
285
+ "--project",
286
+ required=True,
287
+ help="Project name",
288
+ )
289
+ list_system_metrics_parser.add_argument(
290
+ "--run",
291
+ required=True,
292
+ help="Run name",
293
+ )
294
+ list_system_metrics_parser.add_argument(
295
+ "--json",
296
+ action="store_true",
297
+ help="Output in JSON format",
298
+ )
299
+
300
+ list_alerts_parser = list_subparsers.add_parser(
301
+ "alerts",
302
+ help="List alerts for a project or run",
303
+ )
304
+ list_alerts_parser.add_argument(
305
+ "--project",
306
+ required=True,
307
+ help="Project name",
308
+ )
309
+ list_alerts_parser.add_argument(
310
+ "--run",
311
+ required=False,
312
+ help="Run name (optional)",
313
+ )
314
+ list_alerts_parser.add_argument(
315
+ "--level",
316
+ required=False,
317
+ help="Filter by alert level (info, warn, error)",
318
+ )
319
+ list_alerts_parser.add_argument(
320
+ "--json",
321
+ action="store_true",
322
+ help="Output in JSON format",
323
+ )
324
+ list_alerts_parser.add_argument(
325
+ "--since",
326
+ required=False,
327
+ help="Only show alerts after this ISO 8601 timestamp",
328
+ )
329
+
330
+ list_reports_parser = list_subparsers.add_parser(
331
+ "reports",
332
+ help="List markdown reports for a project or run",
333
+ )
334
+ list_reports_parser.add_argument(
335
+ "--project",
336
+ required=True,
337
+ help="Project name",
338
+ )
339
+ list_reports_parser.add_argument(
340
+ "--run",
341
+ required=False,
342
+ help="Run name (optional)",
343
+ )
344
+ list_reports_parser.add_argument(
345
+ "--json",
346
+ action="store_true",
347
+ help="Output in JSON format",
348
+ )
349
+
350
+ get_parser = subparsers.add_parser(
351
+ "get",
352
+ help="Get project, run, or metric information",
353
+ )
354
+ get_subparsers = get_parser.add_subparsers(dest="get_type", required=True)
355
+
356
+ get_project_parser = get_subparsers.add_parser(
357
+ "project",
358
+ help="Get project summary",
359
+ )
360
+ get_project_parser.add_argument(
361
+ "--project",
362
+ required=True,
363
+ help="Project name",
364
+ )
365
+ get_project_parser.add_argument(
366
+ "--json",
367
+ action="store_true",
368
+ help="Output in JSON format",
369
+ )
370
+
371
+ get_run_parser = get_subparsers.add_parser(
372
+ "run",
373
+ help="Get run summary",
374
+ )
375
+ get_run_parser.add_argument(
376
+ "--project",
377
+ required=True,
378
+ help="Project name",
379
+ )
380
+ get_run_parser.add_argument(
381
+ "--run",
382
+ required=True,
383
+ help="Run name",
384
+ )
385
+ get_run_parser.add_argument(
386
+ "--json",
387
+ action="store_true",
388
+ help="Output in JSON format",
389
+ )
390
+
391
+ get_metric_parser = get_subparsers.add_parser(
392
+ "metric",
393
+ help="Get metric values for a run",
394
+ )
395
+ get_metric_parser.add_argument(
396
+ "--project",
397
+ required=True,
398
+ help="Project name",
399
+ )
400
+ get_metric_parser.add_argument(
401
+ "--run",
402
+ required=True,
403
+ help="Run name",
404
+ )
405
+ get_metric_parser.add_argument(
406
+ "--metric",
407
+ required=True,
408
+ help="Metric name",
409
+ )
410
+ get_metric_parser.add_argument(
411
+ "--step",
412
+ type=int,
413
+ required=False,
414
+ help="Get metric at exactly this step",
415
+ )
416
+ get_metric_parser.add_argument(
417
+ "--around",
418
+ type=int,
419
+ required=False,
420
+ help="Get metrics around this step (use with --window)",
421
+ )
422
+ get_metric_parser.add_argument(
423
+ "--at-time",
424
+ required=False,
425
+ help="Get metrics around this ISO 8601 timestamp (use with --window)",
426
+ )
427
+ get_metric_parser.add_argument(
428
+ "--window",
429
+ type=int,
430
+ required=False,
431
+ default=10,
432
+ help="Window size: ±steps for --around, ±seconds for --at-time (default: 10)",
433
+ )
434
+ get_metric_parser.add_argument(
435
+ "--json",
436
+ action="store_true",
437
+ help="Output in JSON format",
438
+ )
439
+
440
+ get_snapshot_parser = get_subparsers.add_parser(
441
+ "snapshot",
442
+ help="Get all metrics at/around a step or timestamp",
443
+ )
444
+ get_snapshot_parser.add_argument(
445
+ "--project",
446
+ required=True,
447
+ help="Project name",
448
+ )
449
+ get_snapshot_parser.add_argument(
450
+ "--run",
451
+ required=True,
452
+ help="Run name",
453
+ )
454
+ get_snapshot_parser.add_argument(
455
+ "--step",
456
+ type=int,
457
+ required=False,
458
+ help="Get all metrics at exactly this step",
459
+ )
460
+ get_snapshot_parser.add_argument(
461
+ "--around",
462
+ type=int,
463
+ required=False,
464
+ help="Get all metrics around this step (use with --window)",
465
+ )
466
+ get_snapshot_parser.add_argument(
467
+ "--at-time",
468
+ required=False,
469
+ help="Get all metrics around this ISO 8601 timestamp (use with --window)",
470
+ )
471
+ get_snapshot_parser.add_argument(
472
+ "--window",
473
+ type=int,
474
+ required=False,
475
+ default=10,
476
+ help="Window size: ±steps for --around, ±seconds for --at-time (default: 10)",
477
+ )
478
+ get_snapshot_parser.add_argument(
479
+ "--json",
480
+ action="store_true",
481
+ help="Output in JSON format",
482
+ )
483
+
484
+ get_system_metric_parser = get_subparsers.add_parser(
485
+ "system-metric",
486
+ help="Get system metric values for a run",
487
+ )
488
+ get_system_metric_parser.add_argument(
489
+ "--project",
490
+ required=True,
491
+ help="Project name",
492
+ )
493
+ get_system_metric_parser.add_argument(
494
+ "--run",
495
+ required=True,
496
+ help="Run name",
497
+ )
498
+ get_system_metric_parser.add_argument(
499
+ "--metric",
500
+ required=False,
501
+ help="System metric name (optional, if not provided returns all system metrics)",
502
+ )
503
+ get_system_metric_parser.add_argument(
504
+ "--json",
505
+ action="store_true",
506
+ help="Output in JSON format",
507
+ )
508
+
509
+ get_alerts_parser = get_subparsers.add_parser(
510
+ "alerts",
511
+ help="Get alerts for a project or run",
512
+ )
513
+ get_alerts_parser.add_argument(
514
+ "--project",
515
+ required=True,
516
+ help="Project name",
517
+ )
518
+ get_alerts_parser.add_argument(
519
+ "--run",
520
+ required=False,
521
+ help="Run name (optional)",
522
+ )
523
+ get_alerts_parser.add_argument(
524
+ "--level",
525
+ required=False,
526
+ help="Filter by alert level (info, warn, error)",
527
+ )
528
+ get_alerts_parser.add_argument(
529
+ "--json",
530
+ action="store_true",
531
+ help="Output in JSON format",
532
+ )
533
+ get_alerts_parser.add_argument(
534
+ "--since",
535
+ required=False,
536
+ help="Only show alerts after this ISO 8601 timestamp",
537
+ )
538
+
539
+ get_report_parser = get_subparsers.add_parser(
540
+ "report",
541
+ help="Get markdown report entries for a run",
542
+ )
543
+ get_report_parser.add_argument(
544
+ "--project",
545
+ required=True,
546
+ help="Project name",
547
+ )
548
+ get_report_parser.add_argument(
549
+ "--run",
550
+ required=True,
551
+ help="Run name",
552
+ )
553
+ get_report_parser.add_argument(
554
+ "--report",
555
+ required=True,
556
+ help="Report metric name",
557
+ )
558
+ get_report_parser.add_argument(
559
+ "--json",
560
+ action="store_true",
561
+ help="Output in JSON format",
562
+ )
563
+
564
+ skills_parser = subparsers.add_parser(
565
+ "skills",
566
+ help="Manage Trackio skills for AI coding assistants",
567
+ )
568
+ skills_subparsers = skills_parser.add_subparsers(
569
+ dest="skills_action", required=True
570
+ )
571
+ skills_add_parser = skills_subparsers.add_parser(
572
+ "add",
573
+ help="Download and install the Trackio skill for an AI assistant",
574
+ )
575
+ skills_add_parser.add_argument(
576
+ "--cursor",
577
+ action="store_true",
578
+ help="Install for Cursor",
579
+ )
580
+ skills_add_parser.add_argument(
581
+ "--claude",
582
+ action="store_true",
583
+ help="Install for Claude Code",
584
+ )
585
+ skills_add_parser.add_argument(
586
+ "--codex",
587
+ action="store_true",
588
+ help="Install for Codex",
589
+ )
590
+ skills_add_parser.add_argument(
591
+ "--opencode",
592
+ action="store_true",
593
+ help="Install for OpenCode",
594
+ )
595
+ skills_add_parser.add_argument(
596
+ "--global",
597
+ dest="global_",
598
+ action="store_true",
599
+ help="Install globally (user-level) instead of in the current project directory",
600
+ )
601
+ skills_add_parser.add_argument(
602
+ "--dest",
603
+ type=str,
604
+ required=False,
605
+ help="Install into a custom destination (path to skills directory)",
606
+ )
607
+ skills_add_parser.add_argument(
608
+ "--force",
609
+ action="store_true",
610
+ help="Overwrite existing skill if it already exists",
611
+ )
612
+
613
+ args, unknown_args = parser.parse_known_args()
614
+ if unknown_args:
615
+ trailing_global_parser = argparse.ArgumentParser(add_help=False)
616
+ trailing_global_parser.add_argument("--space", required=False)
617
+ trailing_global_parser.add_argument("--hf-token", required=False)
618
+ trailing_globals, remaining_unknown = trailing_global_parser.parse_known_args(
619
+ unknown_args
620
+ )
621
+ if remaining_unknown:
622
+ parser.error(f"unrecognized arguments: {' '.join(remaining_unknown)}")
623
+ if trailing_globals.space is not None:
624
+ args.space = trailing_globals.space
625
+ if trailing_globals.hf_token is not None:
626
+ args.hf_token = trailing_globals.hf_token
627
+
628
+ if args.command in ("show", "status", "sync", "skills") and _get_space(args):
629
+ error_exit(
630
+ f"The '{args.command}' command does not support --space (remote mode)."
631
+ )
632
+
633
+ if args.command == "show":
634
+ color_palette = None
635
+ if args.color_palette:
636
+ color_palette = [color.strip() for color in args.color_palette.split(",")]
637
+ show(
638
+ project=args.project,
639
+ theme=args.theme,
640
+ mcp_server=args.mcp_server,
641
+ footer=args.footer,
642
+ color_palette=color_palette,
643
+ host=args.host,
644
+ )
645
+ elif args.command == "status":
646
+ _handle_status()
647
+ elif args.command == "sync":
648
+ _handle_sync(args)
649
+ elif args.command == "list":
650
+ remote = _get_remote(args)
651
+ if args.list_type == "projects":
652
+ if remote:
653
+ projects = remote.predict(api_name="/get_all_projects")
654
+ else:
655
+ projects = SQLiteStorage.get_projects()
656
+ if args.json:
657
+ print(format_json({"projects": projects}))
658
+ else:
659
+ print(format_list(projects, "Projects"))
660
+ elif args.list_type == "runs":
661
+ if remote:
662
+ runs = remote.predict(args.project, api_name="/get_runs_for_project")
663
+ else:
664
+ db_path = SQLiteStorage.get_project_db_path(args.project)
665
+ if not db_path.exists():
666
+ error_exit(f"Project '{args.project}' not found.")
667
+ runs = SQLiteStorage.get_runs(args.project)
668
+ if args.json:
669
+ print(format_json({"project": args.project, "runs": runs}))
670
+ else:
671
+ print(format_list(runs, f"Runs in '{args.project}'"))
672
+ elif args.list_type == "metrics":
673
+ if remote:
674
+ metrics = remote.predict(
675
+ args.project, args.run, api_name="/get_metrics_for_run"
676
+ )
677
+ else:
678
+ db_path = SQLiteStorage.get_project_db_path(args.project)
679
+ if not db_path.exists():
680
+ error_exit(f"Project '{args.project}' not found.")
681
+ runs = SQLiteStorage.get_runs(args.project)
682
+ if args.run not in runs:
683
+ error_exit(
684
+ f"Run '{args.run}' not found in project '{args.project}'."
685
+ )
686
+ metrics = SQLiteStorage.get_all_metrics_for_run(args.project, args.run)
687
+ if args.json:
688
+ print(
689
+ format_json(
690
+ {"project": args.project, "run": args.run, "metrics": metrics}
691
+ )
692
+ )
693
+ else:
694
+ print(
695
+ format_list(
696
+ metrics, f"Metrics for '{args.run}' in '{args.project}'"
697
+ )
698
+ )
699
+ elif args.list_type == "system-metrics":
700
+ if remote:
701
+ system_metrics = remote.predict(
702
+ args.project, args.run, api_name="/get_system_metrics_for_run"
703
+ )
704
+ else:
705
+ db_path = SQLiteStorage.get_project_db_path(args.project)
706
+ if not db_path.exists():
707
+ error_exit(f"Project '{args.project}' not found.")
708
+ runs = SQLiteStorage.get_runs(args.project)
709
+ if args.run not in runs:
710
+ error_exit(
711
+ f"Run '{args.run}' not found in project '{args.project}'."
712
+ )
713
+ system_metrics = SQLiteStorage.get_all_system_metrics_for_run(
714
+ args.project, args.run
715
+ )
716
+ if args.json:
717
+ print(
718
+ format_json(
719
+ {
720
+ "project": args.project,
721
+ "run": args.run,
722
+ "system_metrics": system_metrics,
723
+ }
724
+ )
725
+ )
726
+ else:
727
+ print(format_system_metric_names(system_metrics))
728
+ elif args.list_type == "alerts":
729
+ if remote:
730
+ alerts = remote.predict(
731
+ args.project,
732
+ args.run,
733
+ args.level,
734
+ args.since,
735
+ api_name="/get_alerts",
736
+ )
737
+ else:
738
+ db_path = SQLiteStorage.get_project_db_path(args.project)
739
+ if not db_path.exists():
740
+ error_exit(f"Project '{args.project}' not found.")
741
+ alerts = SQLiteStorage.get_alerts(
742
+ args.project,
743
+ run_name=args.run,
744
+ level=args.level,
745
+ since=args.since,
746
+ )
747
+ if args.json:
748
+ print(
749
+ format_json(
750
+ {
751
+ "project": args.project,
752
+ "run": args.run,
753
+ "level": args.level,
754
+ "since": args.since,
755
+ "alerts": alerts,
756
+ }
757
+ )
758
+ )
759
+ else:
760
+ print(format_alerts(alerts))
761
+ elif args.list_type == "reports":
762
+ if remote:
763
+ runs = remote.predict(args.project, api_name="/get_runs_for_project")
764
+ else:
765
+ db_path = SQLiteStorage.get_project_db_path(args.project)
766
+ if not db_path.exists():
767
+ error_exit(f"Project '{args.project}' not found.")
768
+ runs = SQLiteStorage.get_runs(args.project)
769
+ if args.run and args.run not in runs:
770
+ error_exit(f"Run '{args.run}' not found in project '{args.project}'.")
771
+
772
+ target_runs = [args.run] if args.run else runs
773
+ all_reports = []
774
+ for run_name in target_runs:
775
+ if remote:
776
+ logs = remote.predict(args.project, run_name, api_name="/get_logs")
777
+ else:
778
+ logs = SQLiteStorage.get_logs(args.project, run_name)
779
+ all_reports.extend(_extract_reports(run_name, logs))
780
+
781
+ if args.json:
782
+ print(
783
+ format_json(
784
+ {
785
+ "project": args.project,
786
+ "run": args.run,
787
+ "reports": all_reports,
788
+ }
789
+ )
790
+ )
791
+ else:
792
+ report_lines = [
793
+ f"{entry['run']} | {entry['report']} | step={entry['step']} | {entry['timestamp']}"
794
+ for entry in all_reports
795
+ ]
796
+ if args.run:
797
+ print(
798
+ format_list(
799
+ report_lines,
800
+ f"Reports for '{args.run}' in '{args.project}'",
801
+ )
802
+ )
803
+ else:
804
+ print(format_list(report_lines, f"Reports in '{args.project}'"))
805
+ elif args.command == "get":
806
+ remote = _get_remote(args)
807
+ if args.get_type == "project":
808
+ if remote:
809
+ summary = remote.predict(args.project, api_name="/get_project_summary")
810
+ else:
811
+ db_path = SQLiteStorage.get_project_db_path(args.project)
812
+ if not db_path.exists():
813
+ error_exit(f"Project '{args.project}' not found.")
814
+ summary = get_project_summary(args.project)
815
+ if args.json:
816
+ print(format_json(summary))
817
+ else:
818
+ print(format_project_summary(summary))
819
+ elif args.get_type == "run":
820
+ if remote:
821
+ summary = remote.predict(
822
+ args.project, args.run, api_name="/get_run_summary"
823
+ )
824
+ else:
825
+ db_path = SQLiteStorage.get_project_db_path(args.project)
826
+ if not db_path.exists():
827
+ error_exit(f"Project '{args.project}' not found.")
828
+ runs = SQLiteStorage.get_runs(args.project)
829
+ if args.run not in runs:
830
+ error_exit(
831
+ f"Run '{args.run}' not found in project '{args.project}'."
832
+ )
833
+ summary = get_run_summary(args.project, args.run)
834
+ if args.json:
835
+ print(format_json(summary))
836
+ else:
837
+ print(format_run_summary(summary))
838
+ elif args.get_type == "metric":
839
+ at_time = getattr(args, "at_time", None)
840
+ if remote:
841
+ values = remote.predict(
842
+ args.project,
843
+ args.run,
844
+ args.metric,
845
+ args.step,
846
+ args.around,
847
+ at_time,
848
+ args.window,
849
+ api_name="/get_metric_values",
850
+ )
851
+ else:
852
+ db_path = SQLiteStorage.get_project_db_path(args.project)
853
+ if not db_path.exists():
854
+ error_exit(f"Project '{args.project}' not found.")
855
+ runs = SQLiteStorage.get_runs(args.project)
856
+ if args.run not in runs:
857
+ error_exit(
858
+ f"Run '{args.run}' not found in project '{args.project}'."
859
+ )
860
+ metrics = SQLiteStorage.get_all_metrics_for_run(args.project, args.run)
861
+ if args.metric not in metrics:
862
+ error_exit(
863
+ f"Metric '{args.metric}' not found in run '{args.run}' of project '{args.project}'."
864
+ )
865
+ values = SQLiteStorage.get_metric_values(
866
+ args.project,
867
+ args.run,
868
+ args.metric,
869
+ step=args.step,
870
+ around_step=args.around,
871
+ at_time=at_time,
872
+ window=args.window,
873
+ )
874
+ if args.json:
875
+ print(
876
+ format_json(
877
+ {
878
+ "project": args.project,
879
+ "run": args.run,
880
+ "metric": args.metric,
881
+ "values": values,
882
+ }
883
+ )
884
+ )
885
+ else:
886
+ print(format_metric_values(values))
887
+ elif args.get_type == "snapshot":
888
+ if not args.step and not args.around and not getattr(args, "at_time", None):
889
+ error_exit(
890
+ "Provide --step, --around (with --window), or --at-time (with --window)."
891
+ )
892
+ at_time = getattr(args, "at_time", None)
893
+ if remote:
894
+ snapshot = remote.predict(
895
+ args.project,
896
+ args.run,
897
+ args.step,
898
+ args.around,
899
+ at_time,
900
+ args.window,
901
+ api_name="/get_snapshot",
902
+ )
903
+ else:
904
+ db_path = SQLiteStorage.get_project_db_path(args.project)
905
+ if not db_path.exists():
906
+ error_exit(f"Project '{args.project}' not found.")
907
+ runs = SQLiteStorage.get_runs(args.project)
908
+ if args.run not in runs:
909
+ error_exit(
910
+ f"Run '{args.run}' not found in project '{args.project}'."
911
+ )
912
+ snapshot = SQLiteStorage.get_snapshot(
913
+ args.project,
914
+ args.run,
915
+ step=args.step,
916
+ around_step=args.around,
917
+ at_time=at_time,
918
+ window=args.window,
919
+ )
920
+ if args.json:
921
+ result = {
922
+ "project": args.project,
923
+ "run": args.run,
924
+ "metrics": snapshot,
925
+ }
926
+ if args.step is not None:
927
+ result["step"] = args.step
928
+ if args.around is not None:
929
+ result["around"] = args.around
930
+ result["window"] = args.window
931
+ if at_time is not None:
932
+ result["at_time"] = at_time
933
+ result["window"] = args.window
934
+ print(format_json(result))
935
+ else:
936
+ print(format_snapshot(snapshot))
937
+ elif args.get_type == "system-metric":
938
+ if remote:
939
+ system_metrics = remote.predict(
940
+ args.project, args.run, api_name="/get_system_logs"
941
+ )
942
+ if args.metric:
943
+ all_system_metric_names = remote.predict(
944
+ args.project,
945
+ args.run,
946
+ api_name="/get_system_metrics_for_run",
947
+ )
948
+ if args.metric not in all_system_metric_names:
949
+ error_exit(
950
+ f"System metric '{args.metric}' not found in run '{args.run}' of project '{args.project}'."
951
+ )
952
+ filtered_metrics = [
953
+ {
954
+ k: v
955
+ for k, v in entry.items()
956
+ if k == "timestamp" or k == args.metric
957
+ }
958
+ for entry in system_metrics
959
+ if args.metric in entry
960
+ ]
961
+ if args.json:
962
+ print(
963
+ format_json(
964
+ {
965
+ "project": args.project,
966
+ "run": args.run,
967
+ "metric": args.metric,
968
+ "values": filtered_metrics,
969
+ }
970
+ )
971
+ )
972
+ else:
973
+ print(format_system_metrics(filtered_metrics))
974
+ else:
975
+ if args.json:
976
+ print(
977
+ format_json(
978
+ {
979
+ "project": args.project,
980
+ "run": args.run,
981
+ "system_metrics": system_metrics,
982
+ }
983
+ )
984
+ )
985
+ else:
986
+ print(format_system_metrics(system_metrics))
987
+ else:
988
+ db_path = SQLiteStorage.get_project_db_path(args.project)
989
+ if not db_path.exists():
990
+ error_exit(f"Project '{args.project}' not found.")
991
+ runs = SQLiteStorage.get_runs(args.project)
992
+ if args.run not in runs:
993
+ error_exit(
994
+ f"Run '{args.run}' not found in project '{args.project}'."
995
+ )
996
+ if args.metric:
997
+ system_metrics = SQLiteStorage.get_system_logs(
998
+ args.project, args.run
999
+ )
1000
+ all_system_metric_names = (
1001
+ SQLiteStorage.get_all_system_metrics_for_run(
1002
+ args.project, args.run
1003
+ )
1004
+ )
1005
+ if args.metric not in all_system_metric_names:
1006
+ error_exit(
1007
+ f"System metric '{args.metric}' not found in run '{args.run}' of project '{args.project}'."
1008
+ )
1009
+ filtered_metrics = [
1010
+ {
1011
+ k: v
1012
+ for k, v in entry.items()
1013
+ if k == "timestamp" or k == args.metric
1014
+ }
1015
+ for entry in system_metrics
1016
+ if args.metric in entry
1017
+ ]
1018
+ if args.json:
1019
+ print(
1020
+ format_json(
1021
+ {
1022
+ "project": args.project,
1023
+ "run": args.run,
1024
+ "metric": args.metric,
1025
+ "values": filtered_metrics,
1026
+ }
1027
+ )
1028
+ )
1029
+ else:
1030
+ print(format_system_metrics(filtered_metrics))
1031
+ else:
1032
+ system_metrics = SQLiteStorage.get_system_logs(
1033
+ args.project, args.run
1034
+ )
1035
+ if args.json:
1036
+ print(
1037
+ format_json(
1038
+ {
1039
+ "project": args.project,
1040
+ "run": args.run,
1041
+ "system_metrics": system_metrics,
1042
+ }
1043
+ )
1044
+ )
1045
+ else:
1046
+ print(format_system_metrics(system_metrics))
1047
+ elif args.get_type == "alerts":
1048
+ if remote:
1049
+ alerts = remote.predict(
1050
+ args.project,
1051
+ args.run,
1052
+ args.level,
1053
+ args.since,
1054
+ api_name="/get_alerts",
1055
+ )
1056
+ else:
1057
+ db_path = SQLiteStorage.get_project_db_path(args.project)
1058
+ if not db_path.exists():
1059
+ error_exit(f"Project '{args.project}' not found.")
1060
+ alerts = SQLiteStorage.get_alerts(
1061
+ args.project,
1062
+ run_name=args.run,
1063
+ level=args.level,
1064
+ since=args.since,
1065
+ )
1066
+ if args.json:
1067
+ print(
1068
+ format_json(
1069
+ {
1070
+ "project": args.project,
1071
+ "run": args.run,
1072
+ "level": args.level,
1073
+ "since": args.since,
1074
+ "alerts": alerts,
1075
+ }
1076
+ )
1077
+ )
1078
+ else:
1079
+ print(format_alerts(alerts))
1080
+ elif args.get_type == "report":
1081
+ if remote:
1082
+ logs = remote.predict(args.project, args.run, api_name="/get_logs")
1083
+ else:
1084
+ db_path = SQLiteStorage.get_project_db_path(args.project)
1085
+ if not db_path.exists():
1086
+ error_exit(f"Project '{args.project}' not found.")
1087
+ runs = SQLiteStorage.get_runs(args.project)
1088
+ if args.run not in runs:
1089
+ error_exit(
1090
+ f"Run '{args.run}' not found in project '{args.project}'."
1091
+ )
1092
+ logs = SQLiteStorage.get_logs(args.project, args.run)
1093
+
1094
+ reports = _extract_reports(args.run, logs, report_name=args.report)
1095
+ if not reports:
1096
+ error_exit(
1097
+ f"Report '{args.report}' not found in run '{args.run}' of project '{args.project}'."
1098
+ )
1099
+
1100
+ if args.json:
1101
+ print(
1102
+ format_json(
1103
+ {
1104
+ "project": args.project,
1105
+ "run": args.run,
1106
+ "report": args.report,
1107
+ "values": reports,
1108
+ }
1109
+ )
1110
+ )
1111
+ else:
1112
+ output = []
1113
+ for idx, entry in enumerate(reports, start=1):
1114
+ output.append(
1115
+ f"Entry {idx} | step={entry['step']} | timestamp={entry['timestamp']}"
1116
+ )
1117
+ output.append(entry["content"])
1118
+ if idx < len(reports):
1119
+ output.append("-" * 80)
1120
+ print("\n".join(output))
1121
+ elif args.command == "skills":
1122
+ if args.skills_action == "add":
1123
+ _handle_skills_add(args)
1124
+ else:
1125
+ parser.print_help()
1126
+
1127
+
1128
+ def _handle_skills_add(args):
1129
+ import shutil
1130
+ from pathlib import Path
1131
+
1132
+ try:
1133
+ from huggingface_hub.cli.skills import (
1134
+ CENTRAL_GLOBAL,
1135
+ CENTRAL_LOCAL,
1136
+ GLOBAL_TARGETS,
1137
+ LOCAL_TARGETS,
1138
+ )
1139
+ except (ImportError, ModuleNotFoundError):
1140
+ error_exit(
1141
+ "The 'trackio skills' command requires huggingface_hub >= 1.4.0.\n"
1142
+ "Please upgrade: pip install --upgrade huggingface_hub"
1143
+ )
1144
+
1145
+ SKILL_ID = "trackio"
1146
+ GITHUB_RAW = "https://raw.githubusercontent.com/gradio-app/trackio/main"
1147
+ SKILL_PREFIX = ".agents/skills/trackio"
1148
+ SKILL_FILES = [
1149
+ "SKILL.md",
1150
+ "alerts.md",
1151
+ "logging_metrics.md",
1152
+ "retrieving_metrics.md",
1153
+ ]
1154
+
1155
+ if not (args.cursor or args.claude or args.codex or args.opencode or args.dest):
1156
+ error_exit(
1157
+ "Pick a destination via --cursor, --claude, --codex, --opencode, or --dest."
1158
+ )
1159
+
1160
+ def download(url: str) -> str:
1161
+ from huggingface_hub.utils import get_session
1162
+
1163
+ try:
1164
+ response = get_session().get(url)
1165
+ response.raise_for_status()
1166
+ except Exception as e:
1167
+ error_exit(
1168
+ f"Failed to download {url}\n{e}\n\n"
1169
+ "Make sure you have internet access. The skill files are fetched from "
1170
+ "the Trackio GitHub repository."
1171
+ )
1172
+ return response.text
1173
+
1174
+ def remove_existing(path: Path, force: bool):
1175
+ if not (path.exists() or path.is_symlink()):
1176
+ return
1177
+ if not force:
1178
+ error_exit(
1179
+ f"Skill already exists at {path}.\nRe-run with --force to overwrite."
1180
+ )
1181
+ if path.is_dir() and not path.is_symlink():
1182
+ shutil.rmtree(path)
1183
+ else:
1184
+ path.unlink()
1185
+
1186
+ def install_to(skills_dir: Path, force: bool) -> Path:
1187
+ skills_dir = skills_dir.expanduser().resolve()
1188
+ skills_dir.mkdir(parents=True, exist_ok=True)
1189
+ dest = skills_dir / SKILL_ID
1190
+ remove_existing(dest, force)
1191
+ dest.mkdir()
1192
+ for fname in SKILL_FILES:
1193
+ content = download(f"{GITHUB_RAW}/{SKILL_PREFIX}/{fname}")
1194
+ (dest / fname).write_text(content, encoding="utf-8")
1195
+ return dest
1196
+
1197
+ def create_symlink(
1198
+ agent_skills_dir: Path, central_skill_path: Path, force: bool
1199
+ ) -> Path:
1200
+ agent_skills_dir = agent_skills_dir.expanduser().resolve()
1201
+ agent_skills_dir.mkdir(parents=True, exist_ok=True)
1202
+ link_path = agent_skills_dir / SKILL_ID
1203
+ remove_existing(link_path, force)
1204
+ link_path.symlink_to(os.path.relpath(central_skill_path, agent_skills_dir))
1205
+ return link_path
1206
+
1207
+ global_targets = {**GLOBAL_TARGETS, "cursor": Path("~/.cursor/skills")}
1208
+ local_targets = {**LOCAL_TARGETS, "cursor": Path(".cursor/skills")}
1209
+ targets_dict = global_targets if args.global_ else local_targets
1210
+
1211
+ if args.dest:
1212
+ if args.cursor or args.claude or args.codex or args.opencode or args.global_:
1213
+ error_exit("--dest cannot be combined with agent flags or --global.")
1214
+ skill_dest = install_to(Path(args.dest), args.force)
1215
+ print(f"Installed '{SKILL_ID}' to {skill_dest}")
1216
+ return
1217
+
1218
+ agent_targets = []
1219
+ if args.cursor:
1220
+ agent_targets.append(targets_dict["cursor"])
1221
+ if args.claude:
1222
+ agent_targets.append(targets_dict["claude"])
1223
+ if args.codex:
1224
+ agent_targets.append(targets_dict["codex"])
1225
+ if args.opencode:
1226
+ agent_targets.append(targets_dict["opencode"])
1227
+
1228
+ central_path = CENTRAL_GLOBAL if args.global_ else CENTRAL_LOCAL
1229
+ central_skill_path = install_to(central_path, args.force)
1230
+ print(f"Installed '{SKILL_ID}' to central location: {central_skill_path}")
1231
+
1232
+ for agent_target in agent_targets:
1233
+ link_path = create_symlink(agent_target, central_skill_path, args.force)
1234
+ print(f"Created symlink: {link_path}")
1235
+
1236
+
1237
+ if __name__ == "__main__":
1238
+ main()
trackio/cli_helpers.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import sys
3
+ from typing import Any
4
+
5
+
6
+ def format_json(data: Any) -> str:
7
+ """Format data as JSON."""
8
+ return json.dumps(data, indent=2)
9
+
10
+
11
+ def format_list(items: list[str], title: str | None = None) -> str:
12
+ """Format a list of items in human-readable format."""
13
+ if not items:
14
+ return f"No {title.lower() if title else 'items'} found."
15
+
16
+ output = []
17
+ if title:
18
+ output.append(f"{title}:")
19
+
20
+ for item in items:
21
+ output.append(f" - {item}")
22
+
23
+ return "\n".join(output)
24
+
25
+
26
+ def format_project_summary(summary: dict) -> str:
27
+ """Format project summary in human-readable format."""
28
+ output = [f"Project: {summary['project']}"]
29
+ output.append(f"Number of runs: {summary['num_runs']}")
30
+
31
+ if summary["runs"]:
32
+ output.append("\nRuns:")
33
+ for run in summary["runs"]:
34
+ output.append(f" - {run}")
35
+ else:
36
+ output.append("\nNo runs found.")
37
+
38
+ if summary.get("last_activity"):
39
+ output.append(f"\nLast activity (max step): {summary['last_activity']}")
40
+
41
+ return "\n".join(output)
42
+
43
+
44
+ def format_run_summary(summary: dict) -> str:
45
+ """Format run summary in human-readable format."""
46
+ output = [f"Project: {summary['project']}"]
47
+ output.append(f"Run: {summary['run']}")
48
+ output.append(f"Number of logs: {summary['num_logs']}")
49
+
50
+ if summary.get("last_step") is not None:
51
+ output.append(f"Last step: {summary['last_step']}")
52
+
53
+ if summary.get("metrics"):
54
+ output.append("\nMetrics:")
55
+ for metric in summary["metrics"]:
56
+ output.append(f" - {metric}")
57
+ else:
58
+ output.append("\nNo metrics found.")
59
+
60
+ config = summary.get("config")
61
+ if config:
62
+ output.append("\nConfig:")
63
+ config_display = {k: v for k, v in config.items() if not k.startswith("_")}
64
+ if config_display:
65
+ for key, value in config_display.items():
66
+ output.append(f" {key}: {value}")
67
+ else:
68
+ output.append(" (no config)")
69
+ else:
70
+ output.append("\nConfig: (no config)")
71
+
72
+ return "\n".join(output)
73
+
74
+
75
+ def format_metric_values(values: list[dict]) -> str:
76
+ """Format metric values in human-readable format."""
77
+ if not values:
78
+ return "No metric values found."
79
+
80
+ output = [f"Found {len(values)} value(s):\n"]
81
+ output.append("Step | Timestamp | Value")
82
+ output.append("-" * 50)
83
+
84
+ for value in values:
85
+ step = value.get("step", "N/A")
86
+ timestamp = value.get("timestamp", "N/A")
87
+ val = value.get("value", "N/A")
88
+ output.append(f"{step} | {timestamp} | {val}")
89
+
90
+ return "\n".join(output)
91
+
92
+
93
+ def format_system_metrics(metrics: list[dict]) -> str:
94
+ """Format system metrics in human-readable format."""
95
+ if not metrics:
96
+ return "No system metrics found."
97
+
98
+ output = [f"Found {len(metrics)} system metric entry/entries:\n"]
99
+
100
+ for i, entry in enumerate(metrics):
101
+ timestamp = entry.get("timestamp", "N/A")
102
+ output.append(f"\nEntry {i + 1} (Timestamp: {timestamp}):")
103
+ for key, value in entry.items():
104
+ if key != "timestamp":
105
+ output.append(f" {key}: {value}")
106
+
107
+ return "\n".join(output)
108
+
109
+
110
+ def format_system_metric_names(names: list[str]) -> str:
111
+ """Format system metric names in human-readable format."""
112
+ return format_list(names, "System Metrics")
113
+
114
+
115
+ def format_snapshot(snapshot: dict[str, list[dict]]) -> str:
116
+ """Format a metrics snapshot in human-readable format."""
117
+ if not snapshot:
118
+ return "No metrics found in the specified range."
119
+
120
+ output = []
121
+ for metric_name, values in sorted(snapshot.items()):
122
+ output.append(f"\n{metric_name}:")
123
+ output.append(" Step | Timestamp | Value")
124
+ output.append(" " + "-" * 48)
125
+ for v in values:
126
+ step = v.get("step", "N/A")
127
+ ts = v.get("timestamp", "N/A")
128
+ val = v.get("value", "N/A")
129
+ output.append(f" {step} | {ts} | {val}")
130
+
131
+ return "\n".join(output)
132
+
133
+
134
+ def format_alerts(alerts: list[dict]) -> str:
135
+ """Format alerts in human-readable format."""
136
+ if not alerts:
137
+ return "No alerts found."
138
+
139
+ output = [f"Found {len(alerts)} alert(s):\n"]
140
+ output.append("Timestamp | Run | Level | Title | Text | Step")
141
+ output.append("-" * 80)
142
+
143
+ for a in alerts:
144
+ ts = a.get("timestamp", "N/A")
145
+ run = a.get("run", "N/A")
146
+ level = a.get("level", "N/A").upper()
147
+ title = a.get("title", "")
148
+ text = a.get("text", "") or ""
149
+ step = a.get("step", "N/A")
150
+ output.append(f"{ts} | {run} | {level} | {title} | {text} | {step}")
151
+
152
+ return "\n".join(output)
153
+
154
+
155
+ def error_exit(message: str, code: int = 1) -> None:
156
+ """Print error message and exit."""
157
+ print(f"Error: {message}", file=sys.stderr)
158
+ sys.exit(code)
trackio/commit_scheduler.py ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 time
6
+ from concurrent.futures import Future
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+ from threading import Lock, Thread
10
+ from typing import Callable, Dict, List, Union
11
+
12
+ from huggingface_hub.hf_api import (
13
+ DEFAULT_IGNORE_PATTERNS,
14
+ CommitInfo,
15
+ CommitOperationAdd,
16
+ HfApi,
17
+ )
18
+ from huggingface_hub.utils import filter_repo_objects
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class _FileToUpload:
25
+ """Temporary dataclass to store info about files to upload. Not meant to be used directly."""
26
+
27
+ local_path: Path
28
+ path_in_repo: str
29
+ size_limit: int
30
+ last_modified: float
31
+
32
+
33
+ class CommitScheduler:
34
+ """
35
+ Scheduler to upload a local folder to the Hub at regular intervals (e.g. push to hub every 5 minutes).
36
+
37
+ The recommended way to use the scheduler is to use it as a context manager. This ensures that the scheduler is
38
+ properly stopped and the last commit is triggered when the script ends. The scheduler can also be stopped manually
39
+ with the `stop` method. Checkout the [upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#scheduled-uploads)
40
+ to learn more about how to use it.
41
+
42
+ Args:
43
+ repo_id (`str`):
44
+ The id of the repo to commit to.
45
+ folder_path (`str` or `Path`):
46
+ Path to the local folder to upload regularly.
47
+ every (`int` or `float`, *optional*):
48
+ The number of minutes between each commit. Defaults to 5 minutes.
49
+ path_in_repo (`str`, *optional*):
50
+ Relative path of the directory in the repo, for example: `"checkpoints/"`. Defaults to the root folder
51
+ of the repository.
52
+ repo_type (`str`, *optional*):
53
+ The type of the repo to commit to. Defaults to `model`.
54
+ revision (`str`, *optional*):
55
+ The revision of the repo to commit to. Defaults to `main`.
56
+ private (`bool`, *optional*):
57
+ 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.
58
+ token (`str`, *optional*):
59
+ The token to use to commit to the repo. Defaults to the token saved on the machine.
60
+ allow_patterns (`List[str]` or `str`, *optional*):
61
+ If provided, only files matching at least one pattern are uploaded.
62
+ ignore_patterns (`List[str]` or `str`, *optional*):
63
+ If provided, files matching any of the patterns are not uploaded.
64
+ squash_history (`bool`, *optional*):
65
+ Whether to squash the history of the repo after each commit. Defaults to `False`. Squashing commits is
66
+ useful to avoid degraded performances on the repo when it grows too large.
67
+ hf_api (`HfApi`, *optional*):
68
+ The [`HfApi`] client to use to commit to the Hub. Can be set with custom settings (user agent, token,...).
69
+ on_before_commit (`Callable[[], None]`, *optional*):
70
+ If specified, a function that will be called before the CommitScheduler lists files to create a commit.
71
+
72
+ Example:
73
+ ```py
74
+ >>> from pathlib import Path
75
+ >>> from huggingface_hub import CommitScheduler
76
+
77
+ # Scheduler uploads every 10 minutes
78
+ >>> csv_path = Path("watched_folder/data.csv")
79
+ >>> CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path=csv_path.parent, every=10)
80
+
81
+ >>> with csv_path.open("a") as f:
82
+ ... f.write("first line")
83
+
84
+ # Some time later (...)
85
+ >>> with csv_path.open("a") as f:
86
+ ... f.write("second line")
87
+ ```
88
+
89
+ Example using a context manager:
90
+ ```py
91
+ >>> from pathlib import Path
92
+ >>> from huggingface_hub import CommitScheduler
93
+
94
+ >>> with CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path="watched_folder", every=10) as scheduler:
95
+ ... csv_path = Path("watched_folder/data.csv")
96
+ ... with csv_path.open("a") as f:
97
+ ... f.write("first line")
98
+ ... (...)
99
+ ... with csv_path.open("a") as f:
100
+ ... f.write("second line")
101
+
102
+ # Scheduler is now stopped and last commit have been triggered
103
+ ```
104
+ """
105
+
106
+ def __init__(
107
+ self,
108
+ *,
109
+ repo_id: str,
110
+ folder_path: Union[str, Path],
111
+ every: Union[int, float] = 5,
112
+ path_in_repo: str | None = None,
113
+ repo_type: str | None = None,
114
+ revision: str | None = None,
115
+ private: bool | None = None,
116
+ token: str | None = None,
117
+ allow_patterns: list[str] | str | None = None,
118
+ ignore_patterns: list[str] | str | None = None,
119
+ squash_history: bool = False,
120
+ hf_api: HfApi | None = None,
121
+ on_before_commit: Callable[[], None] | None = None,
122
+ ) -> None:
123
+ self.api = hf_api or HfApi(token=token)
124
+ self.on_before_commit = on_before_commit
125
+
126
+ # Folder
127
+ self.folder_path = Path(folder_path).expanduser().resolve()
128
+ self.path_in_repo = path_in_repo or ""
129
+ self.allow_patterns = allow_patterns
130
+
131
+ if ignore_patterns is None:
132
+ ignore_patterns = []
133
+ elif isinstance(ignore_patterns, str):
134
+ ignore_patterns = [ignore_patterns]
135
+ self.ignore_patterns = ignore_patterns + DEFAULT_IGNORE_PATTERNS
136
+
137
+ if self.folder_path.is_file():
138
+ raise ValueError(
139
+ f"'folder_path' must be a directory, not a file: '{self.folder_path}'."
140
+ )
141
+ self.folder_path.mkdir(parents=True, exist_ok=True)
142
+
143
+ # Repository
144
+ repo_url = self.api.create_repo(
145
+ repo_id=repo_id, private=private, repo_type=repo_type, exist_ok=True
146
+ )
147
+ self.repo_id = repo_url.repo_id
148
+ self.repo_type = repo_type
149
+ self.revision = revision
150
+ self.token = token
151
+
152
+ self.last_uploaded: Dict[Path, float] = {}
153
+ self.last_push_time: float | None = None
154
+
155
+ if not every > 0:
156
+ raise ValueError(f"'every' must be a positive integer, not '{every}'.")
157
+ self.lock = Lock()
158
+ self.every = every
159
+ self.squash_history = squash_history
160
+
161
+ logger.info(
162
+ f"Scheduled job to push '{self.folder_path}' to '{self.repo_id}' every {self.every} minutes."
163
+ )
164
+ self._scheduler_thread = Thread(target=self._run_scheduler, daemon=True)
165
+ self._scheduler_thread.start()
166
+ atexit.register(self._push_to_hub)
167
+
168
+ self.__stopped = False
169
+
170
+ def stop(self) -> None:
171
+ """Stop the scheduler.
172
+
173
+ A stopped scheduler cannot be restarted. Mostly for tests purposes.
174
+ """
175
+ self.__stopped = True
176
+
177
+ def __enter__(self) -> "CommitScheduler":
178
+ return self
179
+
180
+ def __exit__(self, exc_type, exc_value, traceback) -> None:
181
+ # Upload last changes before exiting
182
+ self.trigger().result()
183
+ self.stop()
184
+ return
185
+
186
+ def _run_scheduler(self) -> None:
187
+ """Dumb thread waiting between each scheduled push to Hub."""
188
+ while True:
189
+ self.last_future = self.trigger()
190
+ time.sleep(self.every * 60)
191
+ if self.__stopped:
192
+ break
193
+
194
+ def trigger(self) -> Future:
195
+ """Trigger a `push_to_hub` and return a future.
196
+
197
+ This method is automatically called every `every` minutes. You can also call it manually to trigger a commit
198
+ immediately, without waiting for the next scheduled commit.
199
+ """
200
+ return self.api.run_as_future(self._push_to_hub)
201
+
202
+ def _push_to_hub(self) -> CommitInfo | None:
203
+ if self.__stopped: # If stopped, already scheduled commits are ignored
204
+ return None
205
+
206
+ logger.info("(Background) scheduled commit triggered.")
207
+ try:
208
+ value = self.push_to_hub()
209
+ if self.squash_history:
210
+ logger.info("(Background) squashing repo history.")
211
+ self.api.super_squash_history(
212
+ repo_id=self.repo_id, repo_type=self.repo_type, branch=self.revision
213
+ )
214
+ return value
215
+ except Exception as e:
216
+ logger.error(
217
+ f"Error while pushing to Hub: {e}"
218
+ ) # Depending on the setup, error might be silenced
219
+ raise
220
+
221
+ def push_to_hub(self) -> CommitInfo | None:
222
+ """
223
+ Push folder to the Hub and return the commit info.
224
+
225
+ <Tip warning={true}>
226
+
227
+ This method is not meant to be called directly. It is run in the background by the scheduler, respecting a
228
+ queue mechanism to avoid concurrent commits. Making a direct call to the method might lead to concurrency
229
+ issues.
230
+
231
+ </Tip>
232
+
233
+ The default behavior of `push_to_hub` is to assume an append-only folder. It lists all files in the folder and
234
+ uploads only changed files. If no changes are found, the method returns without committing anything. If you want
235
+ to change this behavior, you can inherit from [`CommitScheduler`] and override this method. This can be useful
236
+ for example to compress data together in a single file before committing. For more details and examples, check
237
+ out our [integration guide](https://huggingface.co/docs/huggingface_hub/main/en/guides/upload#scheduled-uploads).
238
+ """
239
+ # Check files to upload (with lock)
240
+ with self.lock:
241
+ if self.on_before_commit is not None:
242
+ self.on_before_commit()
243
+
244
+ logger.debug("Listing files to upload for scheduled commit.")
245
+
246
+ # List files from folder (taken from `_prepare_upload_folder_additions`)
247
+ relpath_to_abspath = {
248
+ path.relative_to(self.folder_path).as_posix(): path
249
+ for path in sorted(
250
+ self.folder_path.glob("**/*")
251
+ ) # sorted to be deterministic
252
+ if path.is_file()
253
+ }
254
+ prefix = f"{self.path_in_repo.strip('/')}/" if self.path_in_repo else ""
255
+
256
+ # Filter with pattern + filter out unchanged files + retrieve current file size
257
+ files_to_upload: List[_FileToUpload] = []
258
+ for relpath in filter_repo_objects(
259
+ relpath_to_abspath.keys(),
260
+ allow_patterns=self.allow_patterns,
261
+ ignore_patterns=self.ignore_patterns,
262
+ ):
263
+ local_path = relpath_to_abspath[relpath]
264
+ stat = local_path.stat()
265
+ if (
266
+ self.last_uploaded.get(local_path) is None
267
+ or self.last_uploaded[local_path] != stat.st_mtime
268
+ ):
269
+ files_to_upload.append(
270
+ _FileToUpload(
271
+ local_path=local_path,
272
+ path_in_repo=prefix + relpath,
273
+ size_limit=stat.st_size,
274
+ last_modified=stat.st_mtime,
275
+ )
276
+ )
277
+
278
+ # Return if nothing to upload
279
+ if len(files_to_upload) == 0:
280
+ logger.debug("Dropping schedule commit: no changed file to upload.")
281
+ return None
282
+
283
+ # Convert `_FileToUpload` as `CommitOperationAdd` (=> compute file shas + limit to file size)
284
+ logger.debug("Removing unchanged files since previous scheduled commit.")
285
+ add_operations = [
286
+ CommitOperationAdd(
287
+ # TODO: Cap the file to its current size, even if the user append data to it while a scheduled commit is happening
288
+ # (requires an upstream fix for XET-535: `hf_xet` should support `BinaryIO` for upload)
289
+ path_or_fileobj=file_to_upload.local_path,
290
+ path_in_repo=file_to_upload.path_in_repo,
291
+ )
292
+ for file_to_upload in files_to_upload
293
+ ]
294
+
295
+ # Upload files (append mode expected - no need for lock)
296
+ logger.debug("Uploading files for scheduled commit.")
297
+ commit_info = self.api.create_commit(
298
+ repo_id=self.repo_id,
299
+ repo_type=self.repo_type,
300
+ operations=add_operations,
301
+ commit_message="Scheduled Commit",
302
+ revision=self.revision,
303
+ )
304
+
305
+ for file in files_to_upload:
306
+ self.last_uploaded[file.local_path] = file.last_modified
307
+
308
+ self.last_push_time = time.time()
309
+
310
+ return commit_info
trackio/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_space_id: contextvars.ContextVar[str | None] = contextvars.ContextVar(
17
+ "current_space_id", default=None
18
+ )
trackio/deploy.py ADDED
@@ -0,0 +1,806 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.metadata
2
+ import io
3
+ import json as json_mod
4
+ import os
5
+ import shutil
6
+ import sys
7
+ import tempfile
8
+ import threading
9
+ import time
10
+ from importlib.resources import files
11
+ from pathlib import Path
12
+ from typing import Literal
13
+
14
+ if sys.version_info >= (3, 11):
15
+ import tomllib
16
+ else:
17
+ import tomli as tomllib
18
+
19
+ import gradio
20
+ import httpx
21
+ import huggingface_hub
22
+ from gradio_client import Client, handle_file
23
+ from httpx import ReadTimeout
24
+ from huggingface_hub import Volume
25
+ from huggingface_hub.errors import HfHubHTTPError, RepositoryNotFoundError
26
+
27
+ import trackio
28
+ from trackio.bucket_storage import (
29
+ create_bucket_if_not_exists,
30
+ upload_project_to_bucket,
31
+ upload_project_to_bucket_for_static,
32
+ )
33
+ from trackio.sqlite_storage import SQLiteStorage
34
+ from trackio.utils import (
35
+ MEDIA_DIR,
36
+ get_or_create_project_hash,
37
+ preprocess_space_and_dataset_ids,
38
+ )
39
+
40
+ SPACE_HOST_URL = "https://{user_name}-{space_name}.hf.space/"
41
+ SPACE_URL = "https://huggingface.co/spaces/{space_id}"
42
+ _BOLD_ORANGE = "\033[1m\033[38;5;208m"
43
+ _RESET = "\033[0m"
44
+
45
+
46
+ def _readme_linked_hub_yaml(dataset_id: str | None) -> str:
47
+ if dataset_id is not None:
48
+ return f"datasets:\n - {dataset_id}\n"
49
+ return ""
50
+
51
+
52
+ _SPACE_APP_PY = "import trackio\ntrackio.show()\n"
53
+
54
+
55
+ def _retry_hf_write(op_name: str, fn, retries: int = 4, initial_delay: float = 1.5):
56
+ delay = initial_delay
57
+ for attempt in range(1, retries + 1):
58
+ try:
59
+ return fn()
60
+ except ReadTimeout:
61
+ if attempt == retries:
62
+ raise
63
+ print(
64
+ f"* {op_name} timed out (attempt {attempt}/{retries}). Retrying in {delay:.1f}s..."
65
+ )
66
+ time.sleep(delay)
67
+ delay = min(delay * 2, 12)
68
+ except HfHubHTTPError as e:
69
+ status = e.response.status_code if e.response is not None else None
70
+ if status is None or status < 500 or attempt == retries:
71
+ raise
72
+ print(
73
+ f"* {op_name} failed with HTTP {status} (attempt {attempt}/{retries}). Retrying in {delay:.1f}s..."
74
+ )
75
+ time.sleep(delay)
76
+ delay = min(delay * 2, 12)
77
+
78
+
79
+ def _get_source_install_dependencies() -> str:
80
+ """Get trackio dependencies from pyproject.toml for source installs."""
81
+ trackio_path = files("trackio")
82
+ pyproject_path = Path(trackio_path).parent / "pyproject.toml"
83
+ with open(pyproject_path, "rb") as f:
84
+ pyproject = tomllib.load(f)
85
+ deps = pyproject["project"]["dependencies"]
86
+ spaces_deps = (
87
+ pyproject["project"].get("optional-dependencies", {}).get("spaces", [])
88
+ )
89
+ return "\n".join(deps + spaces_deps)
90
+
91
+
92
+ def _is_trackio_installed_from_source() -> bool:
93
+ """Check if trackio is installed from source/editable install vs PyPI."""
94
+ try:
95
+ trackio_file = trackio.__file__
96
+ if "site-packages" not in trackio_file and "dist-packages" not in trackio_file:
97
+ return True
98
+
99
+ dist = importlib.metadata.distribution("trackio")
100
+ if dist.files:
101
+ files = list(dist.files)
102
+ has_pth = any(".pth" in str(f) for f in files)
103
+ if has_pth:
104
+ return True
105
+
106
+ return False
107
+ except (
108
+ AttributeError,
109
+ importlib.metadata.PackageNotFoundError,
110
+ importlib.metadata.MetadataError,
111
+ ValueError,
112
+ TypeError,
113
+ ):
114
+ return True
115
+
116
+
117
+ def deploy_as_space(
118
+ space_id: str,
119
+ space_storage: huggingface_hub.SpaceStorage | None = None,
120
+ dataset_id: str | None = None,
121
+ bucket_id: str | None = None,
122
+ private: bool | None = None,
123
+ ):
124
+ if (
125
+ os.getenv("SYSTEM") == "spaces"
126
+ ): # in case a repo with this function is uploaded to spaces
127
+ return
128
+
129
+ if dataset_id is not None and bucket_id is not None:
130
+ raise ValueError(
131
+ "Cannot use bucket volume options together with dataset_id; use one persistence mode."
132
+ )
133
+
134
+ trackio_path = files("trackio")
135
+
136
+ hf_api = huggingface_hub.HfApi()
137
+
138
+ try:
139
+ huggingface_hub.create_repo(
140
+ space_id,
141
+ private=private,
142
+ space_sdk="gradio",
143
+ space_storage=space_storage,
144
+ repo_type="space",
145
+ exist_ok=True,
146
+ )
147
+ except HfHubHTTPError as e:
148
+ if e.response.status_code in [401, 403]: # unauthorized or forbidden
149
+ print("Need 'write' access token to create a Spaces repo.")
150
+ huggingface_hub.login(add_to_git_credential=False)
151
+ huggingface_hub.create_repo(
152
+ space_id,
153
+ private=private,
154
+ space_sdk="gradio",
155
+ space_storage=space_storage,
156
+ repo_type="space",
157
+ exist_ok=True,
158
+ )
159
+ else:
160
+ raise ValueError(f"Failed to create Space: {e}")
161
+
162
+ # We can assume pandas, gradio, and huggingface-hub are already installed in a Gradio Space.
163
+ # Make sure necessary dependencies are installed by creating a requirements.txt.
164
+ is_source_install = _is_trackio_installed_from_source()
165
+
166
+ if bucket_id is not None:
167
+ create_bucket_if_not_exists(bucket_id, private=private)
168
+
169
+ with open(Path(trackio_path, "README.md"), "r") as f:
170
+ readme_content = f.read()
171
+ readme_content = readme_content.replace("{GRADIO_VERSION}", gradio.__version__)
172
+ readme_content = readme_content.replace("{APP_FILE}", "app.py")
173
+ readme_content = readme_content.replace(
174
+ "{LINKED_HUB_METADATA}", _readme_linked_hub_yaml(dataset_id)
175
+ )
176
+ readme_buffer = io.BytesIO(readme_content.encode("utf-8"))
177
+ hf_api.upload_file(
178
+ path_or_fileobj=readme_buffer,
179
+ path_in_repo="README.md",
180
+ repo_id=space_id,
181
+ repo_type="space",
182
+ )
183
+
184
+ if is_source_install:
185
+ requirements_content = _get_source_install_dependencies()
186
+ else:
187
+ requirements_content = f"trackio[spaces]=={trackio.__version__}"
188
+
189
+ requirements_buffer = io.BytesIO(requirements_content.encode("utf-8"))
190
+ hf_api.upload_file(
191
+ path_or_fileobj=requirements_buffer,
192
+ path_in_repo="requirements.txt",
193
+ repo_id=space_id,
194
+ repo_type="space",
195
+ )
196
+
197
+ huggingface_hub.utils.disable_progress_bars()
198
+
199
+ if is_source_install:
200
+ dist_index = (
201
+ Path(trackio.__file__).resolve().parent / "frontend" / "dist" / "index.html"
202
+ )
203
+ if not dist_index.is_file():
204
+ raise ValueError(
205
+ "The Trackio frontend build is missing. From the repository root run "
206
+ "`cd trackio/frontend && npm ci && npm run build`, then deploy again."
207
+ )
208
+ hf_api.upload_folder(
209
+ repo_id=space_id,
210
+ repo_type="space",
211
+ folder_path=trackio_path,
212
+ path_in_repo="trackio",
213
+ ignore_patterns=[
214
+ "README.md",
215
+ "frontend/node_modules/**",
216
+ "frontend/src/**",
217
+ "frontend/.gitignore",
218
+ "frontend/package.json",
219
+ "frontend/package-lock.json",
220
+ "frontend/vite.config.js",
221
+ "frontend/svelte.config.js",
222
+ "**/__pycache__/**",
223
+ "*.pyc",
224
+ ],
225
+ )
226
+
227
+ app_file_content = _SPACE_APP_PY
228
+ app_file_buffer = io.BytesIO(app_file_content.encode("utf-8"))
229
+ hf_api.upload_file(
230
+ path_or_fileobj=app_file_buffer,
231
+ path_in_repo="app.py",
232
+ repo_id=space_id,
233
+ repo_type="space",
234
+ )
235
+
236
+ if hf_token := huggingface_hub.utils.get_token():
237
+ huggingface_hub.add_space_secret(space_id, "HF_TOKEN", hf_token)
238
+ if bucket_id is not None:
239
+ runtime = hf_api.get_space_runtime(space_id)
240
+ existing = list(runtime.volumes) if runtime.volumes else []
241
+ already_mounted = any(
242
+ v.type == "bucket" and v.source == bucket_id and v.mount_path == "/data"
243
+ for v in existing
244
+ )
245
+ if not already_mounted:
246
+ non_bucket = [
247
+ v
248
+ for v in existing
249
+ if not (v.type == "bucket" and v.source == bucket_id)
250
+ ]
251
+ hf_api.set_space_volumes(
252
+ space_id,
253
+ non_bucket
254
+ + [Volume(type="bucket", source=bucket_id, mount_path="/data")],
255
+ )
256
+ print(f"* Attached bucket {bucket_id} at '/data'")
257
+ huggingface_hub.add_space_variable(space_id, "TRACKIO_DIR", "/data/trackio")
258
+ elif dataset_id is not None:
259
+ huggingface_hub.add_space_variable(space_id, "TRACKIO_DATASET_ID", dataset_id)
260
+ if logo_light_url := os.environ.get("TRACKIO_LOGO_LIGHT_URL"):
261
+ huggingface_hub.add_space_variable(
262
+ space_id, "TRACKIO_LOGO_LIGHT_URL", logo_light_url
263
+ )
264
+ if logo_dark_url := os.environ.get("TRACKIO_LOGO_DARK_URL"):
265
+ huggingface_hub.add_space_variable(
266
+ space_id, "TRACKIO_LOGO_DARK_URL", logo_dark_url
267
+ )
268
+ if plot_order := os.environ.get("TRACKIO_PLOT_ORDER"):
269
+ huggingface_hub.add_space_variable(space_id, "TRACKIO_PLOT_ORDER", plot_order)
270
+ if theme := os.environ.get("TRACKIO_THEME"):
271
+ huggingface_hub.add_space_variable(space_id, "TRACKIO_THEME", theme)
272
+ huggingface_hub.add_space_variable(space_id, "GRADIO_MCP_SERVER", "True")
273
+
274
+
275
+ def create_space_if_not_exists(
276
+ space_id: str,
277
+ space_storage: huggingface_hub.SpaceStorage | None = None,
278
+ dataset_id: str | None = None,
279
+ bucket_id: str | None = None,
280
+ private: bool | None = None,
281
+ ) -> None:
282
+ """
283
+ Creates a new Hugging Face Space if it does not exist.
284
+
285
+ Args:
286
+ space_id (`str`):
287
+ The ID of the Space to create.
288
+ space_storage ([`~huggingface_hub.SpaceStorage`], *optional*):
289
+ Choice of persistent storage tier for the Space.
290
+ dataset_id (`str`, *optional*):
291
+ Deprecated. Use `bucket_id` instead.
292
+ bucket_id (`str`, *optional*):
293
+ Full Hub bucket id (`namespace/name`) to attach via the Hub volumes API (platform mount).
294
+ Sets `TRACKIO_DIR` to the mount path.
295
+ private (`bool`, *optional*):
296
+ Whether to make the Space private. If `None` (default), the repo will be
297
+ public unless the organization's default is private. This value is ignored
298
+ if the repo already exists.
299
+ """
300
+ if "/" not in space_id:
301
+ raise ValueError(
302
+ f"Invalid space ID: {space_id}. Must be in the format: username/reponame or orgname/reponame."
303
+ )
304
+ if dataset_id is not None and "/" not in dataset_id:
305
+ raise ValueError(
306
+ f"Invalid dataset ID: {dataset_id}. Must be in the format: username/datasetname or orgname/datasetname."
307
+ )
308
+ if bucket_id is not None and "/" not in bucket_id:
309
+ raise ValueError(
310
+ f"Invalid bucket ID: {bucket_id}. Must be in the format: username/bucketname or orgname/bucketname."
311
+ )
312
+ try:
313
+ huggingface_hub.repo_info(space_id, repo_type="space")
314
+ print(
315
+ f"* Found existing space: {_BOLD_ORANGE}{SPACE_URL.format(space_id=space_id)}{_RESET}"
316
+ )
317
+ return
318
+ except RepositoryNotFoundError:
319
+ pass
320
+ except HfHubHTTPError as e:
321
+ if e.response.status_code in [401, 403]: # unauthorized or forbidden
322
+ print("Need 'write' access token to create a Spaces repo.")
323
+ huggingface_hub.login(add_to_git_credential=False)
324
+ else:
325
+ raise ValueError(f"Failed to create Space: {e}")
326
+
327
+ print(
328
+ f"* Creating new space: {_BOLD_ORANGE}{SPACE_URL.format(space_id=space_id)}{_RESET}"
329
+ )
330
+ deploy_as_space(
331
+ space_id,
332
+ space_storage,
333
+ dataset_id,
334
+ bucket_id,
335
+ private,
336
+ )
337
+ print("* Waiting for Space to be ready...")
338
+ _wait_until_space_running(space_id)
339
+
340
+
341
+ def _wait_until_space_running(space_id: str, timeout: int = 300) -> None:
342
+ hf_api = huggingface_hub.HfApi()
343
+ start = time.time()
344
+ delay = 2
345
+ request_timeout = 45.0
346
+ failure_stages = frozenset(
347
+ ("NO_APP_FILE", "CONFIG_ERROR", "BUILD_ERROR", "RUNTIME_ERROR")
348
+ )
349
+ while time.time() - start < timeout:
350
+ try:
351
+ info = hf_api.space_info(space_id, timeout=request_timeout)
352
+ if info.runtime:
353
+ stage = str(info.runtime.stage)
354
+ if stage in failure_stages:
355
+ raise RuntimeError(
356
+ f"Space {space_id} entered terminal stage {stage}. "
357
+ "Fix README.md or app files; see build logs on the Hub."
358
+ )
359
+ if stage == "RUNNING":
360
+ return
361
+ except RuntimeError:
362
+ raise
363
+ except (huggingface_hub.utils.HfHubHTTPError, httpx.RequestError):
364
+ pass
365
+ time.sleep(delay)
366
+ delay = min(delay * 1.5, 15)
367
+ raise TimeoutError(
368
+ f"Space {space_id} did not reach RUNNING within {timeout}s. "
369
+ "Check status and build logs on the Hub."
370
+ )
371
+
372
+
373
+ def wait_until_space_exists(
374
+ space_id: str,
375
+ ) -> None:
376
+ """
377
+ Blocks the current thread until the Space exists.
378
+
379
+ Args:
380
+ space_id (`str`):
381
+ The ID of the Space to wait for.
382
+
383
+ Raises:
384
+ `TimeoutError`: If waiting for the Space takes longer than expected.
385
+ """
386
+ hf_api = huggingface_hub.HfApi()
387
+ delay = 1
388
+ for _ in range(30):
389
+ try:
390
+ hf_api.space_info(space_id)
391
+ return
392
+ except (huggingface_hub.utils.HfHubHTTPError, httpx.RequestError):
393
+ time.sleep(delay)
394
+ delay = min(delay * 2, 60)
395
+ raise TimeoutError("Waiting for space to exist took longer than expected")
396
+
397
+
398
+ def upload_db_to_space(project: str, space_id: str, force: bool = False) -> None:
399
+ """
400
+ Uploads the database of a local Trackio project to a Hugging Face Space.
401
+
402
+ This uses the Gradio Client to upload since we do not want to trigger a new build of
403
+ the Space, which would happen if we used `huggingface_hub.upload_file`.
404
+
405
+ Args:
406
+ project (`str`):
407
+ The name of the project to upload.
408
+ space_id (`str`):
409
+ The ID of the Space to upload to.
410
+ force (`bool`, *optional*, defaults to `False`):
411
+ If `True`, overwrites the existing database without prompting. If `False`,
412
+ prompts for confirmation.
413
+ """
414
+ db_path = SQLiteStorage.get_project_db_path(project)
415
+ client = Client(space_id, verbose=False, httpx_kwargs={"timeout": 90})
416
+
417
+ if not force:
418
+ try:
419
+ existing_projects = client.predict(api_name="/get_all_projects")
420
+ if project in existing_projects:
421
+ response = input(
422
+ f"Database for project '{project}' already exists on Space '{space_id}'. "
423
+ f"Overwrite it? (y/N): "
424
+ )
425
+ if response.lower() not in ["y", "yes"]:
426
+ print("* Upload cancelled.")
427
+ return
428
+ except Exception as e:
429
+ print(f"* Warning: Could not check if project exists on Space: {e}")
430
+ print("* Proceeding with upload...")
431
+
432
+ client.predict(
433
+ api_name="/upload_db_to_space",
434
+ project=project,
435
+ uploaded_db=handle_file(db_path),
436
+ hf_token=huggingface_hub.utils.get_token(),
437
+ )
438
+
439
+
440
+ SYNC_BATCH_SIZE = 500
441
+
442
+
443
+ def sync_incremental(
444
+ project: str,
445
+ space_id: str,
446
+ private: bool | None = None,
447
+ pending_only: bool = False,
448
+ ) -> None:
449
+ """
450
+ Syncs a local Trackio project to a Space via the bulk_log API endpoints
451
+ instead of uploading the entire DB file. Supports incremental sync.
452
+
453
+ Args:
454
+ project: The name of the project to sync.
455
+ space_id: The HF Space ID to sync to.
456
+ private: Whether to make the Space private if creating.
457
+ pending_only: If True, only sync rows tagged with space_id (pending data).
458
+ """
459
+ print(
460
+ f"* Syncing project '{project}' to: {SPACE_URL.format(space_id=space_id)} (please wait...)"
461
+ )
462
+ create_space_if_not_exists(space_id, private=private)
463
+ wait_until_space_exists(space_id)
464
+
465
+ client = Client(space_id, verbose=False, httpx_kwargs={"timeout": 90})
466
+ hf_token = huggingface_hub.utils.get_token()
467
+
468
+ if pending_only:
469
+ pending_logs = SQLiteStorage.get_pending_logs(project)
470
+ if pending_logs:
471
+ logs = pending_logs["logs"]
472
+ for i in range(0, len(logs), SYNC_BATCH_SIZE):
473
+ batch = logs[i : i + SYNC_BATCH_SIZE]
474
+ print(
475
+ f" Syncing metrics: {min(i + SYNC_BATCH_SIZE, len(logs))}/{len(logs)}..."
476
+ )
477
+ client.predict(api_name="/bulk_log", logs=batch, hf_token=hf_token)
478
+ SQLiteStorage.clear_pending_logs(project, pending_logs["ids"])
479
+
480
+ pending_sys = SQLiteStorage.get_pending_system_logs(project)
481
+ if pending_sys:
482
+ logs = pending_sys["logs"]
483
+ for i in range(0, len(logs), SYNC_BATCH_SIZE):
484
+ batch = logs[i : i + SYNC_BATCH_SIZE]
485
+ print(
486
+ f" Syncing system metrics: {min(i + SYNC_BATCH_SIZE, len(logs))}/{len(logs)}..."
487
+ )
488
+ client.predict(
489
+ api_name="/bulk_log_system", logs=batch, hf_token=hf_token
490
+ )
491
+ SQLiteStorage.clear_pending_system_logs(project, pending_sys["ids"])
492
+
493
+ pending_uploads = SQLiteStorage.get_pending_uploads(project)
494
+ if pending_uploads:
495
+ upload_entries = []
496
+ for u in pending_uploads["uploads"]:
497
+ fp = u["file_path"]
498
+ if os.path.exists(fp):
499
+ upload_entries.append(
500
+ {
501
+ "project": u["project"],
502
+ "run": u["run"],
503
+ "step": u["step"],
504
+ "relative_path": u["relative_path"],
505
+ "uploaded_file": handle_file(fp),
506
+ }
507
+ )
508
+ if upload_entries:
509
+ print(f" Syncing {len(upload_entries)} media files...")
510
+ client.predict(
511
+ api_name="/bulk_upload_media",
512
+ uploads=upload_entries,
513
+ hf_token=hf_token,
514
+ )
515
+ SQLiteStorage.clear_pending_uploads(project, pending_uploads["ids"])
516
+ else:
517
+ all_logs = SQLiteStorage.get_all_logs_for_sync(project)
518
+ if all_logs:
519
+ for i in range(0, len(all_logs), SYNC_BATCH_SIZE):
520
+ batch = all_logs[i : i + SYNC_BATCH_SIZE]
521
+ print(
522
+ f" Syncing metrics: {min(i + SYNC_BATCH_SIZE, len(all_logs))}/{len(all_logs)}..."
523
+ )
524
+ client.predict(api_name="/bulk_log", logs=batch, hf_token=hf_token)
525
+
526
+ all_sys_logs = SQLiteStorage.get_all_system_logs_for_sync(project)
527
+ if all_sys_logs:
528
+ for i in range(0, len(all_sys_logs), SYNC_BATCH_SIZE):
529
+ batch = all_sys_logs[i : i + SYNC_BATCH_SIZE]
530
+ print(
531
+ f" Syncing system metrics: {min(i + SYNC_BATCH_SIZE, len(all_sys_logs))}/{len(all_sys_logs)}..."
532
+ )
533
+ client.predict(
534
+ api_name="/bulk_log_system", logs=batch, hf_token=hf_token
535
+ )
536
+
537
+ SQLiteStorage.set_project_metadata(project, "space_id", space_id)
538
+ print(
539
+ f"* Synced successfully to space: {_BOLD_ORANGE}{SPACE_URL.format(space_id=space_id)}{_RESET}"
540
+ )
541
+
542
+
543
+ def upload_dataset_for_static(
544
+ project: str,
545
+ dataset_id: str,
546
+ private: bool | None = None,
547
+ ) -> None:
548
+ hf_api = huggingface_hub.HfApi()
549
+
550
+ try:
551
+ huggingface_hub.create_repo(
552
+ dataset_id,
553
+ private=private,
554
+ repo_type="dataset",
555
+ exist_ok=True,
556
+ )
557
+ except HfHubHTTPError as e:
558
+ if e.response.status_code in [401, 403]:
559
+ print("Need 'write' access token to create a Dataset repo.")
560
+ huggingface_hub.login(add_to_git_credential=False)
561
+ huggingface_hub.create_repo(
562
+ dataset_id,
563
+ private=private,
564
+ repo_type="dataset",
565
+ exist_ok=True,
566
+ )
567
+ else:
568
+ raise ValueError(f"Failed to create Dataset: {e}")
569
+
570
+ with tempfile.TemporaryDirectory() as tmp_dir:
571
+ output_dir = Path(tmp_dir)
572
+ SQLiteStorage.export_for_static_space(project, output_dir)
573
+
574
+ media_dir = MEDIA_DIR / project
575
+ if media_dir.exists():
576
+ dest = output_dir / "media"
577
+ shutil.copytree(media_dir, dest)
578
+
579
+ _retry_hf_write(
580
+ "Dataset upload",
581
+ lambda: hf_api.upload_folder(
582
+ repo_id=dataset_id,
583
+ repo_type="dataset",
584
+ folder_path=str(output_dir),
585
+ ),
586
+ )
587
+
588
+ print(f"* Dataset uploaded: https://huggingface.co/datasets/{dataset_id}")
589
+
590
+
591
+ def deploy_as_static_space(
592
+ space_id: str,
593
+ dataset_id: str | None,
594
+ project: str,
595
+ bucket_id: str | None = None,
596
+ private: bool | None = None,
597
+ hf_token: str | None = None,
598
+ ) -> None:
599
+ if os.getenv("SYSTEM") == "spaces":
600
+ return
601
+
602
+ hf_api = huggingface_hub.HfApi()
603
+
604
+ try:
605
+ huggingface_hub.create_repo(
606
+ space_id,
607
+ private=private,
608
+ space_sdk="static",
609
+ repo_type="space",
610
+ exist_ok=True,
611
+ )
612
+ except HfHubHTTPError as e:
613
+ if e.response.status_code in [401, 403]:
614
+ print("Need 'write' access token to create a Spaces repo.")
615
+ huggingface_hub.login(add_to_git_credential=False)
616
+ huggingface_hub.create_repo(
617
+ space_id,
618
+ private=private,
619
+ space_sdk="static",
620
+ repo_type="space",
621
+ exist_ok=True,
622
+ )
623
+ else:
624
+ raise ValueError(f"Failed to create Space: {e}")
625
+
626
+ linked = _readme_linked_hub_yaml(dataset_id)
627
+ readme_content = (
628
+ f"---\nsdk: static\npinned: false\ntags:\n - trackio\n{linked}---\n"
629
+ )
630
+ _retry_hf_write(
631
+ "Static Space README upload",
632
+ lambda: hf_api.upload_file(
633
+ path_or_fileobj=io.BytesIO(readme_content.encode("utf-8")),
634
+ path_in_repo="README.md",
635
+ repo_id=space_id,
636
+ repo_type="space",
637
+ ),
638
+ )
639
+
640
+ trackio_path = files("trackio")
641
+ dist_dir = Path(trackio_path).parent / "trackio" / "frontend" / "dist"
642
+ if not dist_dir.is_dir():
643
+ dist_dir = Path(trackio.__file__).resolve().parent / "frontend" / "dist"
644
+ if not dist_dir.is_dir():
645
+ raise ValueError(
646
+ "The Trackio frontend build is missing. From the repository root run "
647
+ "`cd trackio/frontend && npm ci && npm run build`, then deploy again."
648
+ )
649
+
650
+ _retry_hf_write(
651
+ "Static Space frontend upload",
652
+ lambda: hf_api.upload_folder(
653
+ repo_id=space_id,
654
+ repo_type="space",
655
+ folder_path=str(dist_dir),
656
+ ),
657
+ )
658
+
659
+ config = {
660
+ "mode": "static",
661
+ "project": project,
662
+ "private": bool(private),
663
+ }
664
+ if bucket_id is not None:
665
+ config["bucket_id"] = bucket_id
666
+ if dataset_id is not None:
667
+ config["dataset_id"] = dataset_id
668
+ if hf_token and private:
669
+ config["hf_token"] = hf_token
670
+
671
+ _retry_hf_write(
672
+ "Static Space config upload",
673
+ lambda: hf_api.upload_file(
674
+ path_or_fileobj=io.BytesIO(json_mod.dumps(config).encode("utf-8")),
675
+ path_in_repo="config.json",
676
+ repo_id=space_id,
677
+ repo_type="space",
678
+ ),
679
+ )
680
+
681
+ assets_dir = Path(trackio.__file__).resolve().parent / "assets"
682
+ if assets_dir.is_dir():
683
+ _retry_hf_write(
684
+ "Static Space assets upload",
685
+ lambda: hf_api.upload_folder(
686
+ repo_id=space_id,
687
+ repo_type="space",
688
+ folder_path=str(assets_dir),
689
+ path_in_repo="assets",
690
+ ),
691
+ )
692
+
693
+ print(
694
+ f"* Static Space deployed: {_BOLD_ORANGE}{SPACE_URL.format(space_id=space_id)}{_RESET}"
695
+ )
696
+
697
+
698
+ def sync(
699
+ project: str,
700
+ space_id: str | None = None,
701
+ private: bool | None = None,
702
+ force: bool = False,
703
+ run_in_background: bool = False,
704
+ sdk: Literal["gradio", "static"] = "gradio",
705
+ dataset_id: str | None = None,
706
+ bucket_id: str | None = None,
707
+ ) -> str:
708
+ """
709
+ Syncs a local Trackio project's database to a Hugging Face Space.
710
+ If the Space does not exist, it will be created.
711
+
712
+ Args:
713
+ project (`str`): The name of the project to upload.
714
+ space_id (`str`, *optional*): The ID of the Space to upload to (e.g., `"username/space_id"`).
715
+ If not provided, checks project metadata first, then generates a random space_id.
716
+ private (`bool`, *optional*):
717
+ Whether to make the Space private. If None (default), the repo will be
718
+ public unless the organization's default is private. This value is ignored
719
+ if the repo already exists.
720
+ force (`bool`, *optional*, defaults to `False`):
721
+ If `True`, overwrite the existing database without prompting for confirmation.
722
+ If `False`, prompt the user before overwriting an existing database.
723
+ run_in_background (`bool`, *optional*, defaults to `False`):
724
+ If `True`, the Space creation and database upload will be run in a background thread.
725
+ If `False`, all the steps will be run synchronously.
726
+ sdk (`str`, *optional*, defaults to `"gradio"`):
727
+ The type of Space to deploy. `"gradio"` deploys a Gradio Space with a live
728
+ server. `"static"` deploys a static Space that reads from an HF Bucket
729
+ (no server needed).
730
+ dataset_id (`str`, *optional*):
731
+ Deprecated. Use `bucket_id` instead.
732
+ bucket_id (`str`, *optional*):
733
+ The ID of the HF Bucket to sync to. By default, a bucket is auto-generated
734
+ from the space_id.
735
+ Returns:
736
+ `str`: The Space ID of the synced project.
737
+ """
738
+ if sdk not in ("gradio", "static"):
739
+ raise ValueError(f"sdk must be 'gradio' or 'static', got '{sdk}'")
740
+ if space_id is None:
741
+ space_id = SQLiteStorage.get_space_id(project)
742
+ if space_id is None:
743
+ space_id = f"{project}-{get_or_create_project_hash(project)}"
744
+ space_id, dataset_id, bucket_id = preprocess_space_and_dataset_ids(
745
+ space_id, dataset_id, bucket_id
746
+ )
747
+
748
+ def _do_sync():
749
+ if sdk == "static":
750
+ try:
751
+ info = huggingface_hub.HfApi().space_info(space_id)
752
+ if info.sdk == "gradio":
753
+ if not force:
754
+ answer = input(
755
+ f"Space '{space_id}' is currently a Gradio Space. "
756
+ f"Convert to static? [y/N] "
757
+ )
758
+ if answer.lower() not in ("y", "yes"):
759
+ print("Aborted.")
760
+ return
761
+ except RepositoryNotFoundError:
762
+ pass
763
+
764
+ if dataset_id is not None:
765
+ upload_dataset_for_static(project, dataset_id, private=private)
766
+ hf_token = huggingface_hub.utils.get_token() if private else None
767
+ deploy_as_static_space(
768
+ space_id,
769
+ dataset_id,
770
+ project,
771
+ private=private,
772
+ hf_token=hf_token,
773
+ )
774
+ elif bucket_id is not None:
775
+ create_bucket_if_not_exists(bucket_id, private=private)
776
+ upload_project_to_bucket_for_static(project, bucket_id)
777
+ print(
778
+ f"* Project data uploaded to bucket: https://huggingface.co/buckets/{bucket_id}"
779
+ )
780
+ deploy_as_static_space(
781
+ space_id,
782
+ None,
783
+ project,
784
+ bucket_id=bucket_id,
785
+ private=private,
786
+ hf_token=huggingface_hub.utils.get_token() if private else None,
787
+ )
788
+ else:
789
+ if bucket_id is not None:
790
+ create_bucket_if_not_exists(bucket_id, private=private)
791
+ upload_project_to_bucket(project, bucket_id)
792
+ print(
793
+ f"* Project data uploaded to bucket: https://huggingface.co/buckets/{bucket_id}"
794
+ )
795
+ create_space_if_not_exists(
796
+ space_id, bucket_id=bucket_id, private=private
797
+ )
798
+ else:
799
+ sync_incremental(project, space_id, private=private, pending_only=False)
800
+ SQLiteStorage.set_project_metadata(project, "space_id", space_id)
801
+
802
+ if run_in_background:
803
+ threading.Thread(target=_do_sync).start()
804
+ else:
805
+ _do_sync()
806
+ return space_id
trackio/dummy_commit_scheduler.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from concurrent.futures import Future
2
+
3
+
4
+ class DummyCommitSchedulerLock:
5
+ def __enter__(self):
6
+ return None
7
+
8
+ def __exit__(self, exception_type, exception_value, exception_traceback):
9
+ pass
10
+
11
+
12
+ class DummyCommitScheduler:
13
+ def __init__(self):
14
+ self.lock = DummyCommitSchedulerLock()
15
+
16
+ def trigger(self) -> Future:
17
+ fut: Future = Future()
18
+ fut.set_result(None)
19
+ return fut
trackio/frontend/dist/assets/index-Cs1UkfOV.css ADDED
@@ -0,0 +1 @@
 
 
1
+ :root{--primary-50: #fff7ed;--primary-100: #ffedd5;--primary-200: #fed7aa;--primary-300: #fdba74;--primary-400: #fb923c;--primary-500: #f97316;--primary-600: #ea580c;--primary-700: #c2410c;--primary-800: #9a3412;--primary-900: #7c2d12;--primary-950: #6c2e12;--secondary-50: #eff6ff;--secondary-100: #dbeafe;--secondary-200: #bfdbfe;--secondary-300: #93c5fd;--secondary-400: #60a5fa;--secondary-500: #3b82f6;--secondary-600: #2563eb;--secondary-700: #1d4ed8;--secondary-800: #1e40af;--secondary-900: #1e3a8a;--secondary-950: #1d3660;--neutral-50: #f9fafb;--neutral-100: #f3f4f6;--neutral-200: #e5e7eb;--neutral-300: #d1d5db;--neutral-400: #9ca3af;--neutral-500: #6b7280;--neutral-600: #4b5563;--neutral-700: #374151;--neutral-800: #1f2937;--neutral-900: #111827;--neutral-950: #0b0f19;--size-0-5: 2px;--size-1: 4px;--size-2: 8px;--size-3: 12px;--size-4: 16px;--size-5: 20px;--size-6: 24px;--size-8: 32px;--size-14: 56px;--size-16: 64px;--size-28: 112px;--size-full: 100%;--spacing-xxs: 1px;--spacing-xs: 2px;--spacing-sm: 4px;--spacing-md: 6px;--spacing-lg: 8px;--spacing-xl: 10px;--spacing-xxl: 16px;--radius-xxs: 1px;--radius-xs: 2px;--radius-sm: 3px;--radius-md: 4px;--radius-lg: 5px;--radius-xl: 8px;--radius-xxl: 12px;--text-xxs: 9px;--text-xs: 10px;--text-sm: 12px;--text-md: 14px;--text-lg: 16px;--text-xl: 22px;--text-xxl: 26px;--line-sm: 1.4;--background-fill-primary: white;--background-fill-secondary: var(--neutral-50);--body-text-color: var(--neutral-900);--body-text-color-subdued: var(--neutral-600);--border-color-primary: var(--neutral-200);--color-accent: var(--primary-500);--color-accent-soft: var(--primary-50);--shadow-drop: rgba(0, 0, 0, .05) 0px 1px 2px 0px;--shadow-drop-lg: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--shadow-inset: rgba(0, 0, 0, .05) 0px 2px 4px 0px inset;--shadow-spread: 3px;--block-title-text-color: var(--neutral-500);--block-title-text-size: var(--text-md);--block-title-text-weight: 400;--block-info-text-color: var(--body-text-color-subdued);--block-info-text-size: var(--text-sm);--input-background-fill: white;--input-background-fill-focus: var(--primary-500);--input-border-color: var(--border-color-primary);--input-border-color-focus: var(--primary-300);--input-border-width: 1px;--input-padding: var(--spacing-xl);--input-placeholder-color: var(--neutral-400);--input-radius: var(--radius-lg);--input-shadow: 0 0 0 var(--shadow-spread) transparent, var(--shadow-inset);--input-shadow-focus: 0 0 0 var(--shadow-spread) var(--primary-50), var(--shadow-inset);--input-text-size: var(--text-md);--checkbox-background-color: var(--background-fill-primary);--checkbox-background-color-focus: var(--checkbox-background-color);--checkbox-background-color-hover: var(--checkbox-background-color);--checkbox-background-color-selected: var(--primary-600);--checkbox-border-color: var(--neutral-300);--checkbox-border-color-focus: var(--primary-500);--checkbox-border-color-hover: var(--neutral-300);--checkbox-border-color-selected: var(--primary-600);--checkbox-border-radius: var(--radius-sm);--checkbox-border-width: var(--input-border-width);--checkbox-label-gap: var(--spacing-lg);--checkbox-label-padding: var(--spacing-md) calc(2 * var(--spacing-md));--checkbox-label-text-size: var(--text-md);--checkbox-shadow: var(--input-shadow);--checkbox-check: url("data:image/svg+xml,%3csvg viewBox='0 0 16 16' fill='white' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M12.207 4.793a1 1 0 010 1.414l-5 5a1 1 0 01-1.414 0l-2-2a1 1 0 011.414-1.414L6.5 9.086l4.293-4.293a1 1 0 011.414 0z'/%3e%3c/svg%3e");--slider-color: var(--primary-500);--container-radius: var(--radius-lg);--layer-top: 9999}.navbar.svelte-d8j1hi{display:flex;align-items:stretch;border-bottom:1px solid var(--border-color-primary, #e5e7eb);background:var(--background-fill-primary, white);padding:0;flex-shrink:0;min-height:44px}.nav-spacer.svelte-d8j1hi{flex:1}.nav-tabs.svelte-d8j1hi{display:flex;gap:0;padding-right:16px}.nav-link.svelte-d8j1hi{padding:10px 16px;border:none;background:none;color:var(--body-text-color-subdued, #6b7280);font-size:var(--text-md, 14px);cursor:pointer;white-space:nowrap;border-bottom:2px solid transparent;transition:color .15s;font-weight:400}.nav-link.svelte-d8j1hi:hover{color:var(--body-text-color, #1f2937)}.nav-link.active.svelte-d8j1hi{color:var(--body-text-color, #1f2937);border-bottom-color:var(--body-text-color, #1f2937);font-weight:500}.checkbox-group.svelte-17gmtkf{display:flex;flex-direction:column}.checkbox-item.svelte-17gmtkf{display:flex;align-items:center;gap:8px;padding:3px 0;cursor:pointer;font-size:13px}.checkbox-item.svelte-17gmtkf input[type=checkbox]:where(.svelte-17gmtkf){-moz-appearance:none;appearance:none;-webkit-appearance:none;width:16px;height:16px;margin:0;border:1px solid var(--checkbox-border-color, #d1d5db);border-radius:var(--checkbox-border-radius, 4px);background-color:var(--checkbox-background-color, white);box-shadow:var(--checkbox-shadow);cursor:pointer;flex-shrink:0;transition:background-color .15s,border-color .15s}.checkbox-item.svelte-17gmtkf input[type=checkbox]:where(.svelte-17gmtkf):checked{background-image:var(--checkbox-check);background-color:var(--checkbox-background-color-selected, #f97316);border-color:var(--checkbox-border-color-selected, #f97316)}.checkbox-item.svelte-17gmtkf input[type=checkbox]:where(.svelte-17gmtkf):hover{border-color:var(--checkbox-border-color-hover, #d1d5db)}.color-dot.svelte-17gmtkf{width:10px;height:10px;border-radius:50%;flex-shrink:0}.run-name.svelte-17gmtkf{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--body-text-color, #1f2937)}.dropdown-container.svelte-kgylqb{width:100%}.label.svelte-kgylqb{display:block;font-size:13px;font-weight:500;color:var(--body-text-color-subdued, #6b7280);margin-bottom:6px}.info.svelte-kgylqb{display:block;font-size:12px;color:var(--body-text-color-subdued, #9ca3af);margin-bottom:4px}.wrap.svelte-kgylqb{position:relative;border-radius:var(--input-radius, 8px);background:var(--input-background-fill, white);border:1px solid var(--border-color-primary, #e5e7eb);transition:border-color .15s,box-shadow .15s}.wrap.focused.svelte-kgylqb{border-color:var(--input-border-color-focus, #fdba74);box-shadow:0 0 0 2px var(--primary-50, #fff7ed)}.wrap-inner.svelte-kgylqb{display:flex;position:relative;align-items:center;padding:0 10px}.secondary-wrap.svelte-kgylqb{display:flex;flex:1;align-items:center}input.svelte-kgylqb{margin:0;outline:none;border:none;background:inherit;width:100%;color:var(--body-text-color, #1f2937);font-size:13px;font-family:inherit;padding:7px 0}input.svelte-kgylqb::placeholder{color:var(--input-placeholder-color, #9ca3af)}input[readonly].svelte-kgylqb{cursor:pointer}.icon-wrap.svelte-kgylqb{color:var(--body-text-color-subdued, #9ca3af);width:16px;flex-shrink:0;pointer-events:none}.options.svelte-kgylqb{position:fixed;z-index:var(--layer-top, 9999);margin:0;padding:4px 0;box-shadow:0 4px 12px #0000001f;border-radius:var(--input-radius, 8px);border:1px solid var(--border-color-primary, #e5e7eb);background:var(--background-fill-primary, white);min-width:fit-content;overflow:auto;color:var(--body-text-color, #1f2937);list-style:none}.item.svelte-kgylqb{display:flex;cursor:pointer;padding:6px 10px;font-size:13px;word-break:break-word}.item.svelte-kgylqb:hover,.item.active.svelte-kgylqb{background:var(--background-fill-secondary, #f9fafb)}.item.selected.svelte-kgylqb{font-weight:500}.check-mark.svelte-kgylqb{padding-right:6px;min-width:16px;font-size:12px}.check-mark.hide.svelte-kgylqb{visibility:hidden}.checkbox-container.svelte-oj84db{display:flex;align-items:center;gap:8px;cursor:pointer;margin:8px 0}.label-text.svelte-oj84db{color:var(--body-text-color, #1f2937);font-size:13px;line-height:1.4}input[type=checkbox].svelte-oj84db{--ring-color: transparent;position:relative;-moz-appearance:none;appearance:none;-webkit-appearance:none;width:16px;height:16px;box-shadow:var(--checkbox-shadow);border:1px solid var(--checkbox-border-color, #d1d5db);border-radius:var(--checkbox-border-radius, 4px);background-color:var(--checkbox-background-color, white);flex-shrink:0;cursor:pointer;transition:background-color .15s,border-color .15s}input[type=checkbox].svelte-oj84db:checked,input[type=checkbox].svelte-oj84db:checked:hover,input[type=checkbox].svelte-oj84db:checked:focus{background-image:var(--checkbox-check);background-color:var(--checkbox-background-color-selected, #f97316);border-color:var(--checkbox-border-color-selected, #f97316)}input[type=checkbox].svelte-oj84db:hover{border-color:var(--checkbox-border-color-hover, #d1d5db);background-color:var(--checkbox-background-color-hover, white)}input[type=checkbox].svelte-oj84db:focus{border-color:var(--checkbox-border-color-focus, #f97316);background-color:var(--checkbox-background-color-focus, white);outline:none}.slider-wrap.svelte-wei6ev{display:flex;flex-direction:column;width:100%}.head.svelte-wei6ev{margin-bottom:4px;display:flex;justify-content:space-between;align-items:center;width:100%}.label.svelte-wei6ev{flex:1;font-size:13px;font-weight:500;color:var(--body-text-color-subdued, #6b7280)}.info.svelte-wei6ev{display:block;font-size:12px;color:var(--body-text-color-subdued, #9ca3af);margin-bottom:4px}.slider-input-container.svelte-wei6ev{display:flex;align-items:center;gap:6px}input[type=range].svelte-wei6ev{-webkit-appearance:none;-moz-appearance:none;appearance:none;width:100%;cursor:pointer;outline:none;border-radius:var(--radius-xl, 12px);min-width:var(--size-28, 112px);background:transparent}input[type=range].svelte-wei6ev::-webkit-slider-runnable-track{height:6px;border-radius:var(--radius-xl, 12px);background:linear-gradient(to right,var(--slider-color, #f97316) var(--range_progress, 50%),var(--neutral-200, #e5e7eb) var(--range_progress, 50%))}input[type=range].svelte-wei6ev::-webkit-slider-thumb{-webkit-appearance:none;-moz-appearance:none;appearance:none;height:16px;width:16px;background-color:var(--slider-color, #f97316);border:2px solid var(--background-fill-primary, white);border-radius:50%;margin-top:-5px;box-shadow:0 0 0 1px var(--border-color-primary, rgba(0, 0, 0, .08)),0 1px 3px #0003}input[type=range].svelte-wei6ev::-moz-range-track{height:6px;background:var(--neutral-200, #e5e7eb);border-radius:var(--radius-xl, 12px)}input[type=range].svelte-wei6ev::-moz-range-thumb{-webkit-appearance:none;-moz-appearance:none;appearance:none;height:16px;width:16px;background-color:var(--slider-color, #f97316);border:2px solid var(--background-fill-primary, white);border-radius:50%;box-shadow:0 0 0 1px var(--border-color-primary, rgba(0, 0, 0, .08)),0 1px 3px #0003}input[type=range].svelte-wei6ev::-moz-range-progress{height:6px;background-color:var(--slider-color, #f97316);border-radius:var(--radius-xl, 12px)}.bound.svelte-wei6ev{font-size:11px;color:var(--body-text-color-subdued, #9ca3af);min-width:12px;text-align:center}.textbox-container.svelte-6yncpg{width:100%}.label.svelte-6yncpg{display:block;font-size:13px;font-weight:500;color:var(--body-text-color-subdued, #6b7280);margin-bottom:6px}.info.svelte-6yncpg{display:block;font-size:12px;color:var(--body-text-color-subdued, #9ca3af);margin-bottom:4px}.input-wrap.svelte-6yncpg{border-radius:var(--input-radius, 8px);background:var(--input-background-fill, white);border:1px solid var(--border-color-primary, #e5e7eb);transition:border-color .15s,box-shadow .15s}.input-wrap.svelte-6yncpg:focus-within{border-color:var(--input-border-color-focus, #fdba74);box-shadow:0 0 0 2px var(--primary-50, #fff7ed)}input.svelte-6yncpg{width:100%;padding:7px 10px;outline:none;border:none;background:transparent;color:var(--body-text-color, #1f2937);font-size:13px;font-family:inherit;border-radius:var(--input-radius, 8px)}input.svelte-6yncpg::placeholder{color:var(--input-placeholder-color, #9ca3af)}.sidebar.svelte-181dlmc{width:290px;min-width:290px;background:var(--background-fill-primary, white);border-right:1px solid var(--border-color-primary, #e5e7eb);display:flex;flex-direction:column;position:relative;overflow:hidden;transition:width .2s,min-width .2s}.sidebar.collapsed.svelte-181dlmc{width:40px;min-width:40px}.toggle-btn.svelte-181dlmc{position:absolute;top:12px;right:8px;z-index:10;border:none;background:none;color:var(--body-text-color-subdued, #9ca3af);cursor:pointer;padding:4px;display:flex;align-items:center;justify-content:center;border-radius:var(--radius-sm, 4px);transition:color .15s,background-color .15s}.toggle-btn.svelte-181dlmc:hover{color:var(--body-text-color, #1f2937);background-color:var(--background-fill-secondary, #f9fafb)}.sidebar-content.svelte-181dlmc{padding:16px;flex:1;min-height:0;display:flex;flex-direction:column}.sidebar-scroll.svelte-181dlmc{overflow-y:auto;flex:1;min-height:0}.oauth-footer.svelte-181dlmc{flex-shrink:0;margin-top:12px;padding-top:12px;border-top:1px solid var(--border-color-primary, #e5e7eb)}.readonly-footer.svelte-181dlmc{flex-shrink:0;margin-top:12px;padding-top:12px;border-top:1px solid var(--border-color-primary, #e5e7eb);display:flex;align-items:center;gap:8px;flex-wrap:wrap}.readonly-badge.svelte-181dlmc{display:inline-flex;align-items:center;border:1px solid var(--border-color-primary, #e5e7eb);border-radius:999px;padding:2px 8px;font-size:10px;letter-spacing:.06em;font-weight:600;color:var(--body-text-color-subdued, #6b7280);background:var(--background-fill-secondary, #f9fafb)}.readonly-link.svelte-181dlmc{font-size:12px;color:var(--body-text-color-subdued, #6b7280);text-decoration:none;max-width:100%;overflow-wrap:anywhere}.readonly-link.svelte-181dlmc:hover{color:var(--body-text-color, #1f2937);text-decoration:underline}.oauth-line.svelte-181dlmc{margin:0;font-size:12px;line-height:1.4;color:var(--body-text-color-subdued, #6b7280)}.oauth-warn.svelte-181dlmc{color:var(--body-text-color, #92400e)}.hf-login-btn.svelte-181dlmc{display:inline-flex;align-items:center;justify-content:center;gap:8px;width:100%;padding:8px 12px;font-size:13px;font-weight:600;color:#fff;background:#141c2e;border-radius:var(--radius-lg, 8px);text-decoration:none;border:none;cursor:pointer;box-sizing:border-box}.hf-login-btn.svelte-181dlmc:hover{background:#283042}.hf-logo.svelte-181dlmc{width:20px;height:20px;flex-shrink:0}.oauth-hint.svelte-181dlmc{margin:8px 0 0;font-size:11px;line-height:1.35;color:var(--body-text-color-subdued, #9ca3af)}.oauth-signed-in.svelte-181dlmc{margin:0;font-size:12px;color:var(--body-text-color-subdued, #6b7280)}.oauth-logout.svelte-181dlmc{font-size:12px;color:var(--body-text-color-subdued, #9ca3af);text-decoration:none;cursor:pointer}.oauth-logout.svelte-181dlmc:hover{text-decoration:underline;color:var(--body-text-color, #1f2937)}.logo-section.svelte-181dlmc{margin-bottom:20px}.logo.svelte-181dlmc{width:80%;max-width:200px}.section.svelte-181dlmc{margin-bottom:18px}.section-label.svelte-181dlmc{font-size:13px;font-weight:500;color:var(--body-text-color-subdued, #6b7280)}.locked-project.svelte-181dlmc{margin-top:4px;font-size:13px;font-weight:500;color:var(--body-text-color, #1f2937);padding:8px 10px;border:1px solid var(--border-color-primary, #e5e7eb);border-radius:var(--radius-md, 6px);background:var(--background-fill-secondary, #f9fafb)}.runs-header.svelte-181dlmc{display:flex;align-items:center;justify-content:space-between;margin-bottom:6px}.select-all-label.svelte-181dlmc{display:flex;align-items:center;gap:6px;cursor:pointer}.select-all-cb.svelte-181dlmc{-moz-appearance:none;appearance:none;-webkit-appearance:none;width:16px;height:16px;border:1px solid var(--checkbox-border-color, #d1d5db);border-radius:var(--checkbox-border-radius, 4px);background-color:var(--checkbox-background-color, white);cursor:pointer;flex-shrink:0;position:relative;transition:background-color .15s,border-color .15s}.select-all-cb.svelte-181dlmc:checked{background-color:var(--checkbox-background-color-selected, var(--color-accent, #f97316));border-color:var(--checkbox-background-color-selected, var(--color-accent, #f97316));background-image:var(--checkbox-check)}.select-all-cb.svelte-181dlmc:indeterminate{background-color:var(--checkbox-background-color-selected, var(--color-accent, #f97316));border-color:var(--checkbox-background-color-selected, var(--color-accent, #f97316));background-image:url("data:image/svg+xml,%3Csvg viewBox='0 0 16 16' fill='white' xmlns='http://www.w3.org/2000/svg'%3E%3Crect x='3' y='7' width='10' height='2' rx='1'/%3E%3C/svg%3E");background-size:12px;background-position:center;background-repeat:no-repeat}.latest-toggle.svelte-181dlmc{display:flex;align-items:center;gap:6px;font-size:12px;color:var(--body-text-color-subdued, #6b7280);cursor:pointer}.latest-toggle.svelte-181dlmc input[type=checkbox]:where(.svelte-181dlmc){-moz-appearance:none;appearance:none;-webkit-appearance:none;width:16px;height:16px;margin:0;border:1px solid var(--checkbox-border-color, #d1d5db);border-radius:var(--checkbox-border-radius, 4px);background-color:var(--checkbox-background-color, white);box-shadow:var(--checkbox-shadow);cursor:pointer;flex-shrink:0;transition:background-color .15s,border-color .15s}.latest-toggle.svelte-181dlmc input[type=checkbox]:where(.svelte-181dlmc):checked{background-image:var(--checkbox-check);background-color:var(--checkbox-background-color-selected, #f97316);border-color:var(--checkbox-border-color-selected, #f97316)}.checkbox-list.svelte-181dlmc{max-height:300px;overflow-y:auto;margin-top:8px}.alert-panel.svelte-x5aqew{position:fixed;bottom:16px;right:16px;width:380px;max-height:400px;background:var(--background-fill-primary, white);border:1px solid var(--border-color-primary, #e5e7eb);border-radius:var(--radius-lg, 8px);box-shadow:var(--shadow-drop-lg);z-index:1000;overflow:hidden;display:flex;flex-direction:column}.alert-panel.collapsed.svelte-x5aqew{max-height:none}.alert-header.svelte-x5aqew{padding:10px 12px;border:none;border-bottom:1px solid var(--border-color-primary, #e5e7eb);background:none;width:100%;display:flex;align-items:center;justify-content:space-between;cursor:pointer;gap:8px}.alert-panel.collapsed.svelte-x5aqew .alert-header:where(.svelte-x5aqew){border-bottom:none}.collapse-icon.svelte-x5aqew{color:var(--body-text-color-subdued, #9ca3af);flex-shrink:0;transition:transform .15s}.collapse-icon.rotated.svelte-x5aqew{transform:rotate(-90deg)}.alert-title.svelte-x5aqew{font-size:13px;font-weight:600;color:var(--body-text-color, #1f2937)}.filter-pills.svelte-x5aqew{display:flex;gap:4px}.pill.svelte-x5aqew{border:1px solid var(--border-color-primary, #e5e7eb);border-radius:var(--radius-xxl, 22px);padding:2px 8px;font-size:11px;background:var(--background-fill-secondary, #f9fafb);color:var(--body-text-color-subdued, #6b7280);cursor:pointer}.pill.active.svelte-x5aqew{background:var(--color-accent, #f97316);color:#fff;border-color:var(--color-accent, #f97316)}.alert-list.svelte-x5aqew{overflow-y:auto;flex:1}.alert-item.svelte-x5aqew{border-bottom:1px solid var(--neutral-100, #f3f4f6)}.alert-row.svelte-x5aqew{display:flex;align-items:center;gap:8px;width:100%;padding:8px 12px;border:none;background:none;text-align:left;cursor:pointer;font-size:var(--text-sm, 12px)}.alert-row.svelte-x5aqew:hover{background:var(--background-fill-secondary, #f9fafb)}.alert-text.svelte-x5aqew{flex:1;color:var(--body-text-color, #1f2937)}.alert-meta.svelte-x5aqew{font-size:var(--text-xs, 10px);color:var(--body-text-color-subdued, #9ca3af);white-space:nowrap}.alert-detail.svelte-x5aqew{padding:4px 12px 8px 32px;font-size:var(--text-sm, 12px);color:var(--body-text-color-subdued, #6b7280)}.plot-container.svelte-9thu1j{min-width:350px;flex:1;background:var(--background-fill-primary, white);border:1px solid var(--border-color-primary, #e5e7eb);border-radius:var(--radius-lg, 8px);padding:12px;overflow:hidden;position:relative}.plot-container[draggable=true].svelte-9thu1j{cursor:grab}.plot-container[draggable=true].svelte-9thu1j:active{cursor:grabbing}.hidden-plot.svelte-9thu1j{visibility:hidden;height:0;padding:0;margin:0;border:none;overflow:hidden;pointer-events:none}.drag-handle.svelte-9thu1j{position:absolute;top:8px;left:8px;color:var(--body-text-color-subdued, #9ca3af);opacity:0;transition:opacity .15s;z-index:5}.plot-container.svelte-9thu1j:hover .drag-handle:where(.svelte-9thu1j){opacity:.5}.drag-handle.svelte-9thu1j:hover{opacity:1!important}.plot-toolbar.svelte-9thu1j{position:absolute;top:8px;right:8px;display:flex;gap:4px;z-index:5;opacity:0;transition:opacity .15s}.plot-container.svelte-9thu1j:hover .plot-toolbar:where(.svelte-9thu1j){opacity:1}.toolbar-btn.svelte-9thu1j{border:1px solid var(--border-color-primary, #e5e7eb);background:var(--background-fill-primary, white);color:var(--body-text-color-subdued, #6b7280);cursor:pointer;padding:4px 6px;border-radius:var(--radius-sm, 4px);display:flex;align-items:center;justify-content:center}.toolbar-btn.svelte-9thu1j:hover{background:var(--neutral-100, #f3f4f6);color:var(--body-text-color, #1f2937)}.plot-chart-wrap.svelte-9thu1j{position:relative;width:100%}.plot-chart-wrap--fs.svelte-9thu1j{flex:1;min-height:0;display:flex;flex-direction:column}.reset-zoom-btn.svelte-9thu1j{position:absolute;bottom:1px;right:1px;z-index:6;display:inline-flex;align-items:center;justify-content:center;margin:0;min-width:52px;padding:5px 12px 5px 10px;border:none;border-radius:4px;background:transparent;color:var(--body-text-color-subdued, #334155);cursor:pointer;opacity:.92;transform:translateY(6px);transition:opacity .15s ease,color .15s ease,background .15s ease;box-shadow:none}.reset-zoom-btn.svelte-9thu1j:hover{opacity:1;color:var(--body-text-color, #0f172a);background:var(--background-fill-secondary, rgba(226, 232, 240, .85));transform:translateY(6px)}.reset-zoom-btn.svelte-9thu1j svg:where(.svelte-9thu1j){display:block;flex-shrink:0;filter:drop-shadow(0 0 .5px rgba(255,255,255,.95))}.plot.svelte-9thu1j{width:100%}.plot.svelte-9thu1j .vega-embed{width:100%!important}.plot.svelte-9thu1j .vega-embed summary{display:none}.fullscreen-host.svelte-9thu1j{position:fixed;top:0;right:0;bottom:0;left:0;z-index:10000;box-sizing:border-box;display:flex;flex-direction:column;background:var(--background-fill-primary, white);padding:12px;gap:8px;pointer-events:auto}.fullscreen-host.svelte-9thu1j:fullscreen{width:100%;height:100%}.fullscreen-host.svelte-9thu1j:-webkit-full-screen{width:100%;height:100%}.fullscreen-toolbar.svelte-9thu1j{flex-shrink:0;display:flex;justify-content:flex-end;gap:4px;z-index:5}.fullscreen-chart-wrap.svelte-9thu1j{flex:1;min-height:0;display:flex;flex-direction:column}.fullscreen-legend.svelte-9thu1j{flex-shrink:0}.fullscreen-plot.svelte-9thu1j{flex:1;min-height:0;width:100%;overflow:hidden}.fullscreen-plot.svelte-9thu1j .vega-embed{width:100%!important;height:100%!important;min-height:0;display:flex;flex-direction:column}.fullscreen-plot.svelte-9thu1j .vega-embed .vega-view{flex:1;min-height:0}.fullscreen-plot.svelte-9thu1j .vega-embed summary{display:none}.custom-legend.svelte-9thu1j{display:flex;align-items:center;justify-content:center;gap:12px;padding:6px 0 0;flex-wrap:wrap}.legend-title.svelte-9thu1j{font-size:11px;color:var(--body-text-color-subdued, #6b7280);font-weight:600}.legend-item.svelte-9thu1j{display:flex;align-items:center;gap:4px}.legend-dot.svelte-9thu1j{width:10px;height:10px;border-radius:50%;flex-shrink:0}.legend-label.svelte-9thu1j{font-size:11px;color:var(--body-text-color-subdued, #6b7280)}.plot-container.svelte-1swghqy{min-width:350px;flex:1;background:var(--background-fill-primary, white);border:1px solid var(--border-color-primary, #e5e7eb);border-radius:var(--radius-lg, 8px);padding:12px;overflow:hidden;position:relative}.plot-container[draggable=true].svelte-1swghqy{cursor:grab}.plot-container[draggable=true].svelte-1swghqy:active{cursor:grabbing}.hidden-plot.svelte-1swghqy{visibility:hidden;height:0;padding:0;margin:0;border:none;overflow:hidden;pointer-events:none}.drag-handle.svelte-1swghqy{position:absolute;top:8px;left:8px;color:var(--body-text-color-subdued, #9ca3af);opacity:0;transition:opacity .15s;z-index:5}.plot-container.svelte-1swghqy:hover .drag-handle:where(.svelte-1swghqy){opacity:.5}.drag-handle.svelte-1swghqy:hover{opacity:1!important}.plot-toolbar.svelte-1swghqy{position:absolute;top:8px;right:8px;display:flex;gap:4px;z-index:5;opacity:0;transition:opacity .15s}.plot-container.svelte-1swghqy:hover .plot-toolbar:where(.svelte-1swghqy){opacity:1}.toolbar-btn.svelte-1swghqy{border:1px solid var(--border-color-primary, #e5e7eb);background:var(--background-fill-primary, white);color:var(--body-text-color-subdued, #6b7280);cursor:pointer;padding:4px 6px;border-radius:var(--radius-sm, 4px);display:flex;align-items:center;justify-content:center}.toolbar-btn.svelte-1swghqy:hover{background:var(--neutral-100, #f3f4f6);color:var(--body-text-color, #1f2937)}.plot-chart-wrap.svelte-1swghqy{position:relative;width:100%}.plot-chart-wrap--fs.svelte-1swghqy{flex:1;min-height:0;display:flex;flex-direction:column}.plot.svelte-1swghqy{width:100%}.plot.svelte-1swghqy .vega-embed{width:100%!important}.plot.svelte-1swghqy .vega-embed summary{display:none}.fullscreen-host.svelte-1swghqy{position:fixed;top:0;right:0;bottom:0;left:0;z-index:10000;box-sizing:border-box;display:flex;flex-direction:column;background:var(--background-fill-primary, white);padding:12px;gap:8px;pointer-events:auto}.fullscreen-host.svelte-1swghqy:fullscreen{width:100%;height:100%}.fullscreen-host.svelte-1swghqy:-webkit-full-screen{width:100%;height:100%}.fullscreen-toolbar.svelte-1swghqy{flex-shrink:0;display:flex;justify-content:flex-end;gap:4px;z-index:5}.fullscreen-chart-wrap.svelte-1swghqy{flex:1;min-height:0;display:flex;flex-direction:column}.fullscreen-legend.svelte-1swghqy{flex-shrink:0}.fullscreen-plot.svelte-1swghqy{flex:1;min-height:0;width:100%;overflow:hidden}.fullscreen-plot.svelte-1swghqy .vega-embed{width:100%!important;height:100%!important;min-height:0;display:flex;flex-direction:column}.fullscreen-plot.svelte-1swghqy .vega-embed .vega-view{flex:1;min-height:0}.fullscreen-plot.svelte-1swghqy .vega-embed summary{display:none}.custom-legend.svelte-1swghqy{display:flex;align-items:center;justify-content:center;gap:12px;padding:6px 0 0;flex-wrap:wrap}.legend-title.svelte-1swghqy{font-size:11px;color:var(--body-text-color-subdued, #6b7280);font-weight:600}.legend-item.svelte-1swghqy{display:flex;align-items:center;gap:4px}.legend-dot.svelte-1swghqy{width:10px;height:10px;border-radius:50%;flex-shrink:0}.legend-label.svelte-1swghqy{font-size:11px;color:var(--body-text-color-subdued, #6b7280)}.accordion.svelte-1jep0a{margin-bottom:12px;border:1px solid var(--border-color-primary, #e5e7eb);border-radius:var(--radius-lg, 8px);background:var(--background-fill-primary, white);overflow:hidden}.accordion-hidden.svelte-1jep0a{margin-bottom:8px}.accordion-header.svelte-1jep0a{display:flex;align-items:center;gap:8px;width:100%;padding:10px 14px;border:none;background:var(--background-fill-primary, white);color:var(--body-text-color, #1f2937);font-size:var(--text-md, 14px);font-weight:600;cursor:pointer;text-align:left}.accordion-header.svelte-1jep0a:hover{background:var(--background-fill-secondary, #f9fafb)}.arrow.svelte-1jep0a{font-size:14px;transition:transform .15s;color:var(--body-text-color, #1f2937);display:inline-block}.arrow.svelte-1jep0a:not(.rotated){transform:rotate(-90deg)}.accordion-body.svelte-1jep0a{padding:0 14px 14px}.trackio-loading.svelte-1kc6b2l{display:flex;align-items:center;justify-content:center;width:100%;min-height:min(70vh,640px);padding:32px 24px;box-sizing:border-box;background:transparent}.logo-stack.svelte-1kc6b2l{position:relative;width:min(100%,200px);max-width:min(92vw,200px);line-height:0;background:transparent;isolation:isolate}.logo-base.svelte-1kc6b2l{display:block;background:transparent}.logo-img.svelte-1kc6b2l{width:100%;height:auto;display:block;background:transparent}.logo-overlay.svelte-1kc6b2l{position:absolute;left:0;top:0;width:100%;animation:svelte-1kc6b2l-trackio-logo-sweep 4s linear infinite;pointer-events:none;background:transparent}.logo-overlay.svelte-1kc6b2l .logo-img:where(.svelte-1kc6b2l){width:100%;height:auto;object-position:left center}.logo-img--gray.svelte-1kc6b2l{filter:grayscale(1)}@keyframes svelte-1kc6b2l-trackio-logo-sweep{0%{clip-path:inset(0 0 0 0)}50%{clip-path:inset(0 0 0 100%)}to{clip-path:inset(0 0 0 0)}}@media(prefers-reduced-motion:reduce){.logo-overlay.svelte-1kc6b2l{display:none}}.sr-only.svelte-1kc6b2l{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}.metrics-page.svelte-2bul55{padding:20px 24px;overflow-y:auto;flex:1;min-height:0}.plot-grid.svelte-2bul55{display:flex;flex-wrap:wrap;gap:16px}.subgroup-list.svelte-2bul55{margin-top:16px}.empty-state.svelte-2bul55{max-width:640px;padding:40px 24px;color:var(--body-text-color, #1f2937)}.empty-state.svelte-2bul55 h2:where(.svelte-2bul55){margin:0 0 8px;font-size:20px;font-weight:700}.empty-state.svelte-2bul55 p:where(.svelte-2bul55){margin:12px 0 8px;color:var(--body-text-color-subdued, #6b7280)}.empty-state.svelte-2bul55 pre:where(.svelte-2bul55){background:var(--background-fill-secondary, #f9fafb);padding:16px;border-radius:var(--radius-lg, 8px);border:1px solid var(--border-color-primary, #e5e7eb);font-size:13px;overflow-x:auto}.empty-state.svelte-2bul55 code:where(.svelte-2bul55){background:var(--background-fill-secondary, #f0f0f0);padding:1px 5px;border-radius:var(--radius-sm, 4px);font-size:13px}.empty-state.svelte-2bul55 pre:where(.svelte-2bul55) code:where(.svelte-2bul55){background:none;padding:0}.system-page.svelte-nv5os4{padding:20px 24px;overflow-y:auto;flex:1;min-height:0}.plot-grid.svelte-nv5os4{display:flex;flex-wrap:wrap;gap:12px}.empty-state.svelte-nv5os4{max-width:640px;padding:40px 24px;color:var(--body-text-color, #1f2937)}.empty-state.svelte-nv5os4 h2:where(.svelte-nv5os4){margin:0 0 8px;font-size:20px;font-weight:700}.empty-state.svelte-nv5os4 p:where(.svelte-nv5os4){margin:12px 0 8px;color:var(--body-text-color-subdued, #6b7280)}.empty-state.svelte-nv5os4 pre:where(.svelte-nv5os4){background:var(--background-fill-secondary, #f9fafb);padding:16px;border-radius:var(--radius-lg, 8px);border:1px solid var(--border-color-primary, #e5e7eb);font-size:13px;overflow-x:auto}.empty-state.svelte-nv5os4 ul:where(.svelte-nv5os4){list-style:disc;padding-left:20px;margin:4px 0 0}.empty-state.svelte-nv5os4 li:where(.svelte-nv5os4){margin:4px 0;color:var(--body-text-color, #1f2937)}.empty-state.svelte-nv5os4 code:where(.svelte-nv5os4){background:var(--background-fill-secondary, #f0f0f0);padding:1px 5px;border-radius:var(--radius-sm, 4px);font-size:13px}.empty-state.svelte-nv5os4 pre:where(.svelte-nv5os4) code:where(.svelte-nv5os4){background:none;padding:0}.table-container.svelte-1cp60rw{display:flex;flex-direction:column;gap:var(--size-2, 8px);position:relative}.header-row.svelte-1cp60rw{display:flex;justify-content:flex-end;align-items:center;min-height:var(--size-6, 24px);width:100%}.header-row.svelte-1cp60rw .label:where(.svelte-1cp60rw){flex:1;margin:0;color:var(--block-label-text-color, var(--neutral-500, #6b7280));font-size:var(--block-label-text-size, 12px);line-height:var(--line-sm, 1.4)}.table-wrap.svelte-1cp60rw{position:relative;overflow:auto;border:1px solid var(--border-color-primary, #e5e7eb);border-radius:var(--table-radius, var(--radius-lg, 8px))}table.svelte-1cp60rw{width:100%;table-layout:auto;color:var(--body-text-color, #1f2937);font-size:var(--input-text-size, 14px);line-height:var(--line-sm, 1.4);border-spacing:0;border-collapse:separate}thead.svelte-1cp60rw{position:sticky;top:0;z-index:5;box-shadow:var(--shadow-drop, rgba(0,0,0,.05) 0px 1px 2px 0px)}th.svelte-1cp60rw{padding:0;background:var(--table-even-background-fill, white);border-right-width:0px;border-left-width:1px;border-bottom-width:1px;border-style:solid;border-color:var(--border-color-primary, #e5e7eb);text-align:left;cursor:pointer;-webkit-user-select:none;user-select:none}th.first.svelte-1cp60rw{border-left-width:0;border-top-left-radius:var(--table-radius, var(--radius-lg, 8px))}th.last.svelte-1cp60rw{border-top-right-radius:var(--table-radius, var(--radius-lg, 8px))}.th-inner.svelte-1cp60rw{padding:var(--size-2, 8px);display:flex;align-items:center;gap:4px;font-weight:600;font-size:var(--text-sm, 12px);white-space:nowrap}.sort-arrow.svelte-1cp60rw{font-size:10px;color:var(--body-text-color-subdued, #9ca3af);visibility:hidden}.sort-arrow.visible.svelte-1cp60rw{visibility:visible}td.svelte-1cp60rw{padding:var(--size-2, 8px);border-right-width:0px;border-left-width:1px;border-bottom-width:1px;border-style:solid;border-color:var(--border-color-primary, #e5e7eb);font-size:var(--text-sm, 12px)}td.first.svelte-1cp60rw{border-left-width:0}tr.svelte-1cp60rw{background:var(--table-even-background-fill, white);border-bottom:1px solid var(--border-color-primary, #e5e7eb);text-align:left}tr.row-odd.svelte-1cp60rw{background:var(--table-odd-background-fill, var(--neutral-50, #f9fafb))}tr.selected.svelte-1cp60rw{background:var(--color-accent-soft, var(--primary-50, #fff7ed))}tr.svelte-1cp60rw:last-child td.first:where(.svelte-1cp60rw){border-bottom-left-radius:var(--table-radius, var(--radius-lg, 8px))}tr.svelte-1cp60rw:last-child td.last:where(.svelte-1cp60rw){border-bottom-right-radius:var(--table-radius, var(--radius-lg, 8px))}.check-col.svelte-1cp60rw{width:40px;text-align:center;padding:var(--size-2, 8px);border-left-width:0}.check-col.svelte-1cp60rw input[type=checkbox]:where(.svelte-1cp60rw){-moz-appearance:none;appearance:none;-webkit-appearance:none;width:16px;height:16px;border:1px solid var(--checkbox-border-color, #d1d5db);border-radius:var(--checkbox-border-radius, 4px);background-color:var(--checkbox-background-color, white);cursor:pointer;flex-shrink:0;transition:background-color .15s,border-color .15s}.check-col.svelte-1cp60rw input[type=checkbox]:where(.svelte-1cp60rw):checked{background-image:var(--checkbox-check);background-color:var(--checkbox-background-color-selected, #2563eb);border-color:var(--checkbox-border-color-selected, #2563eb)}.media-page.svelte-outb32{padding:20px 24px;overflow-y:auto;flex:1}.section-title.svelte-outb32{font-size:var(--text-lg, 16px);font-weight:600;color:var(--body-text-color, #1f2937);margin:16px 0 8px}.gallery.svelte-outb32{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:12px}.gallery-item.svelte-outb32{border:1px solid var(--border-color-primary, #e5e7eb);border-radius:var(--radius-lg, 8px);overflow:hidden;background:var(--background-fill-secondary, #f9fafb)}.gallery-item.svelte-outb32 img:where(.svelte-outb32),.gallery-item.svelte-outb32 video:where(.svelte-outb32){width:100%;display:block}.caption.svelte-outb32{padding:4px 8px;font-size:var(--text-sm, 12px);color:var(--body-text-color-subdued, #9ca3af)}.step-label.svelte-outb32{padding:4px 8px;font-size:var(--text-xs, 10px);color:var(--body-text-color-subdued, #9ca3af)}.audio-list.svelte-outb32{display:flex;flex-direction:column;gap:8px}.audio-item.svelte-outb32{display:flex;align-items:center;gap:12px;padding:8px;border:1px solid var(--border-color-primary, #e5e7eb);border-radius:var(--radius-lg, 8px)}.audio-label.svelte-outb32{font-size:var(--text-sm, 12px);color:var(--body-text-color-subdued, #9ca3af);min-width:120px}.table-section.svelte-outb32{margin-bottom:16px}.empty-state.svelte-outb32{max-width:640px;padding:40px 24px;color:var(--body-text-color, #1f2937)}.empty-state.svelte-outb32 h2:where(.svelte-outb32){margin:0 0 8px;font-size:20px;font-weight:700}.empty-state.svelte-outb32 p:where(.svelte-outb32){margin:12px 0 8px;color:var(--body-text-color-subdued, #6b7280)}.empty-state.svelte-outb32 pre:where(.svelte-outb32){background:var(--background-fill-secondary, #f9fafb);padding:16px;border-radius:var(--radius-lg, 8px);border:1px solid var(--border-color-primary, #e5e7eb);font-size:13px;overflow-x:auto}.empty-state.svelte-outb32 code:where(.svelte-outb32){background:var(--background-fill-secondary, #f0f0f0);padding:1px 5px;border-radius:var(--radius-sm, 4px);font-size:13px}.empty-state.svelte-outb32 pre:where(.svelte-outb32) code:where(.svelte-outb32){background:none;padding:0}.reports-page.svelte-iufsej{padding:20px 24px;overflow-y:auto;flex:1}.controls.svelte-iufsej{display:flex;gap:16px;margin-bottom:16px;flex-wrap:wrap;align-items:flex-end}.control.svelte-iufsej{min-width:200px}.filter-pills.svelte-iufsej{display:flex;gap:4px}.pill.svelte-iufsej{border:1px solid var(--border-color-primary, #e5e7eb);border-radius:var(--radius-xxl, 22px);padding:4px 12px;font-size:var(--text-sm, 12px);background:var(--background-fill-secondary, #f9fafb);color:var(--body-text-color-subdued, #6b7280);cursor:pointer;transition:background-color .15s,color .15s}.pill.svelte-iufsej:hover{background:var(--neutral-100, #f3f4f6)}.pill.active.svelte-iufsej{background:var(--color-accent, #f97316);color:#fff;border-color:var(--color-accent, #f97316)}.empty-state.svelte-iufsej{max-width:640px;padding:40px 24px;color:var(--body-text-color, #1f2937)}.empty-state.svelte-iufsej h2:where(.svelte-iufsej){margin:0 0 8px;font-size:20px;font-weight:700}.empty-state.svelte-iufsej p:where(.svelte-iufsej){margin:12px 0 8px;color:var(--body-text-color-subdued, #6b7280)}.empty-state.svelte-iufsej pre:where(.svelte-iufsej){background:var(--background-fill-secondary, #f9fafb);padding:16px;border-radius:var(--radius-lg, 8px);border:1px solid var(--border-color-primary, #e5e7eb);font-size:13px;overflow-x:auto}.empty-state.svelte-iufsej code:where(.svelte-iufsej){background:var(--background-fill-secondary, #f0f0f0);padding:1px 5px;border-radius:var(--radius-sm, 4px);font-size:13px}.empty-state.svelte-iufsej pre:where(.svelte-iufsej) code:where(.svelte-iufsej){background:none;padding:0}.alerts-table.svelte-iufsej{width:100%;border-collapse:collapse;font-size:var(--text-md, 14px)}.alerts-table.svelte-iufsej th:where(.svelte-iufsej){text-align:left;padding:8px 12px;border-bottom:2px solid var(--border-color-primary, #e5e7eb);color:var(--body-text-color-subdued, #6b7280);font-weight:600;font-size:var(--text-sm, 12px);text-transform:uppercase;letter-spacing:.05em}.alerts-table.svelte-iufsej td:where(.svelte-iufsej){padding:8px 12px;border-bottom:1px solid var(--border-color-primary, #e5e7eb);color:var(--body-text-color, #1f2937)}.alerts-table.svelte-iufsej tbody:where(.svelte-iufsej) tr:where(.svelte-iufsej):nth-child(odd){background:var(--table-odd-background-fill, var(--background-fill-primary, white))}.alerts-table.svelte-iufsej tbody:where(.svelte-iufsej) tr:where(.svelte-iufsej):nth-child(2n){background:var(--table-even-background-fill, var(--background-fill-secondary, #f9fafb))}.alerts-table.svelte-iufsej tr:where(.svelte-iufsej):hover{background:var(--background-fill-secondary, #f3f4f6)}.section-title.svelte-iufsej{font-size:16px;font-weight:700;margin:0 0 12px;color:var(--body-text-color, #1f2937)}.reports-section.svelte-iufsej,.alerts-section.svelte-iufsej{margin-bottom:32px}.report-card.svelte-iufsej{border:1px solid var(--border-color-primary, #e5e7eb);border-radius:var(--radius-lg, 8px);padding:16px 20px;margin-bottom:12px;background:var(--background-fill-primary, white)}.report-meta.svelte-iufsej{font-size:var(--text-sm, 12px);color:var(--body-text-color-subdued, #6b7280);margin-bottom:8px}.report-content.svelte-iufsej{font-size:var(--text-md, 14px);color:var(--body-text-color, #1f2937);line-height:1.6}.report-content.svelte-iufsej h2{font-size:18px;font-weight:700;margin:0 0 8px}.report-content.svelte-iufsej h3{font-size:16px;font-weight:600;margin:12px 0 6px}.report-content.svelte-iufsej h4{font-size:14px;font-weight:600;margin:10px 0 4px}.report-content.svelte-iufsej code{background:var(--background-fill-secondary, #f0f0f0);padding:1px 5px;border-radius:var(--radius-sm, 4px);font-size:13px}.report-content.svelte-iufsej ul{margin:4px 0;padding-left:20px}.report-content.svelte-iufsej li{margin:2px 0}.report-content.svelte-iufsej p{margin:6px 0}.filter-empty.svelte-iufsej{color:var(--body-text-color-subdued, #6b7280);font-size:var(--text-md, 14px)}.runs-page.svelte-1yb6d54{padding:20px 24px;overflow-y:auto;flex:1}.empty-state.svelte-1yb6d54{max-width:640px;padding:40px 24px;color:var(--body-text-color, #1f2937)}.empty-state.svelte-1yb6d54 h2:where(.svelte-1yb6d54){margin:0 0 8px;font-size:20px;font-weight:700}.empty-state.svelte-1yb6d54 p:where(.svelte-1yb6d54){margin:12px 0 8px;color:var(--body-text-color-subdued, #6b7280)}.empty-state.svelte-1yb6d54 pre:where(.svelte-1yb6d54){background:var(--background-fill-secondary, #f9fafb);padding:16px;border-radius:var(--radius-lg, 8px);border:1px solid var(--border-color-primary, #e5e7eb);font-size:13px;overflow-x:auto}.empty-state.svelte-1yb6d54 code:where(.svelte-1yb6d54){background:var(--background-fill-secondary, #f0f0f0);padding:1px 5px;border-radius:var(--radius-sm, 4px);font-size:13px}.empty-state.svelte-1yb6d54 pre:where(.svelte-1yb6d54) code:where(.svelte-1yb6d54){background:none;padding:0}.runs-table.svelte-1yb6d54{width:100%;border-collapse:collapse;font-size:var(--text-md, 14px)}.runs-table.svelte-1yb6d54 th:where(.svelte-1yb6d54){text-align:left;padding:8px 12px;border-bottom:2px solid var(--border-color-primary, #e5e7eb);color:var(--body-text-color-subdued, #6b7280);font-weight:600;font-size:var(--text-sm, 12px);text-transform:uppercase;letter-spacing:.05em}.runs-table.svelte-1yb6d54 td:where(.svelte-1yb6d54){padding:8px 12px;border-bottom:1px solid var(--border-color-primary, #e5e7eb);color:var(--body-text-color, #1f2937)}.runs-table.svelte-1yb6d54 tbody:where(.svelte-1yb6d54) tr:where(.svelte-1yb6d54):nth-child(odd){background:var(--table-odd-background-fill, var(--background-fill-primary, white))}.runs-table.svelte-1yb6d54 tbody:where(.svelte-1yb6d54) tr:where(.svelte-1yb6d54):nth-child(2n){background:var(--table-even-background-fill, var(--background-fill-secondary, #f9fafb))}.runs-table.svelte-1yb6d54 tr:where(.svelte-1yb6d54):hover{background:var(--background-fill-secondary, #f3f4f6)}.run-name-cell.svelte-1yb6d54{font-weight:500}.run-name-with-dot.svelte-1yb6d54{display:inline-flex;align-items:center;gap:8px;max-width:100%}.run-dot.svelte-1yb6d54{width:10px;height:10px;border-radius:50%;flex-shrink:0}.link-btn.svelte-1yb6d54{background:none;border:none;color:var(--color-accent, #f97316);cursor:pointer;font:inherit;font-weight:500;padding:0;text-align:left}.link-btn.svelte-1yb6d54:hover{text-decoration:underline}.rename-input.svelte-1yb6d54{font:inherit;padding:2px 6px;border:1px solid var(--color-accent, #f97316);border-radius:var(--radius-sm, 4px);outline:none;width:100%}.actions-cell.svelte-1yb6d54{display:flex;gap:4px}.action-btn.svelte-1yb6d54{background:none;border:1px solid transparent;color:var(--body-text-color-subdued, #6b7280);cursor:pointer;padding:4px;border-radius:var(--radius-sm, 4px);display:flex;align-items:center}.action-btn.svelte-1yb6d54:hover{background:var(--background-fill-secondary, #f9fafb);border-color:var(--border-color-primary, #e5e7eb);color:var(--body-text-color, #1f2937)}.delete-btn.svelte-1yb6d54:hover{color:#dc2626;border-color:#fecaca;background:#fef2f2}.action-btn.svelte-1yb6d54:disabled{opacity:.45;cursor:not-allowed;pointer-events:none}.run-detail-page.svelte-1bpgsx2{padding:20px 24px;overflow-y:auto;flex:1}.detail-card.svelte-1bpgsx2{background:var(--background-fill-primary, white);border:1px solid var(--border-color-primary, #e5e7eb);border-radius:var(--radius-lg, 8px);padding:24px;max-width:800px}.detail-card.svelte-1bpgsx2 h2:where(.svelte-1bpgsx2){color:var(--body-text-color, #1f2937);margin:0 0 16px;font-size:var(--text-xl, 22px)}.detail-card.svelte-1bpgsx2 h3:where(.svelte-1bpgsx2){color:var(--body-text-color, #1f2937);margin:20px 0 8px;font-size:var(--text-lg, 16px)}.detail-grid.svelte-1bpgsx2{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:12px}.detail-item.svelte-1bpgsx2{display:flex;flex-direction:column;gap:2px}.detail-label.svelte-1bpgsx2{font-size:var(--text-xs, 10px);font-weight:600;color:var(--body-text-color-subdued, #9ca3af);text-transform:uppercase}.detail-value.svelte-1bpgsx2{font-size:var(--text-md, 14px);color:var(--body-text-color, #1f2937)}.config-block.svelte-1bpgsx2{background:var(--background-fill-secondary, #f9fafb);padding:12px;border-radius:var(--radius-lg, 8px);border:1px solid var(--border-color-primary, #e5e7eb);font-size:var(--text-sm, 12px);color:var(--body-text-color, #1f2937);overflow-x:auto}.empty-state.svelte-1bpgsx2{max-width:640px;padding:40px 24px;color:var(--body-text-color, #1f2937)}.empty-state.svelte-1bpgsx2 h2:where(.svelte-1bpgsx2){margin:0 0 8px;font-size:20px;font-weight:700}.empty-state.svelte-1bpgsx2 p:where(.svelte-1bpgsx2){margin:12px 0 8px;color:var(--body-text-color-subdued, #6b7280)}.empty-state.svelte-1bpgsx2 pre:where(.svelte-1bpgsx2){background:var(--background-fill-secondary, #f9fafb);padding:16px;border-radius:var(--radius-lg, 8px);border:1px solid var(--border-color-primary, #e5e7eb);font-size:13px;overflow-x:auto}.empty-state.svelte-1bpgsx2 code:where(.svelte-1bpgsx2){background:var(--background-fill-secondary, #f0f0f0);padding:1px 5px;border-radius:var(--radius-sm, 4px);font-size:13px}.empty-state.svelte-1bpgsx2 pre:where(.svelte-1bpgsx2) code:where(.svelte-1bpgsx2){background:none;padding:0}.files-page.svelte-1xvfk9n{padding:20px 24px;overflow-y:auto;flex:1}.page-title.svelte-1xvfk9n{color:var(--body-text-color, #1f2937);font-size:16px;font-weight:700;margin:0 0 4px}.page-subtitle.svelte-1xvfk9n{color:var(--body-text-color-subdued, #6b7280);font-size:var(--text-sm, 12px);margin:0 0 16px}.file-list.svelte-1xvfk9n{display:flex;flex-direction:column;gap:4px}.file-item.svelte-1xvfk9n{border:1px solid var(--border-color-primary, #e5e7eb);border-radius:var(--radius-lg, 8px);background:var(--background-fill-primary, white);overflow:hidden}.file-item.expanded.svelte-1xvfk9n{border-color:var(--color-accent, #f97316)}.file-row.svelte-1xvfk9n{display:flex;align-items:center;justify-content:space-between;padding:10px 14px;gap:12px}.file-name.svelte-1xvfk9n{display:flex;align-items:center;gap:8px;background:none;border:none;padding:0;font-size:var(--text-md, 14px);color:var(--body-text-color, #1f2937);cursor:pointer;text-align:left}.file-name.svelte-1xvfk9n:hover{color:var(--color-accent, #f97316)}.file-icon.svelte-1xvfk9n{font-size:14px;flex-shrink:0}.file-actions.svelte-1xvfk9n{display:flex;align-items:center;gap:12px;flex-shrink:0}.file-size.svelte-1xvfk9n{font-size:var(--text-sm, 12px);color:var(--body-text-color-subdued, #6b7280);white-space:nowrap}.download-btn.svelte-1xvfk9n{display:flex;align-items:center;justify-content:center;width:28px;height:28px;border-radius:var(--radius-md, 6px);color:var(--body-text-color-subdued, #6b7280);transition:background-color .15s,color .15s}.download-btn.svelte-1xvfk9n:hover{background:var(--background-fill-secondary, #f3f4f6);color:var(--body-text-color, #1f2937)}.file-preview.svelte-1xvfk9n{border-top:1px solid var(--border-color-primary, #e5e7eb);padding:12px 14px;background:var(--background-fill-secondary, #f9fafb)}.preview-code.svelte-1xvfk9n{margin:0;font-size:12px;line-height:1.5;max-height:400px;overflow:auto;white-space:pre-wrap;word-break:break-all;color:var(--body-text-color, #1f2937)}.preview-loading.svelte-1xvfk9n,.preview-unavailable.svelte-1xvfk9n{color:var(--body-text-color-subdued, #6b7280);font-size:var(--text-sm, 12px);padding:8px 0}.preview-unavailable.svelte-1xvfk9n a:where(.svelte-1xvfk9n){color:var(--color-accent, #f97316);text-decoration:none}.preview-unavailable.svelte-1xvfk9n a:where(.svelte-1xvfk9n):hover{text-decoration:underline}.empty-state.svelte-1xvfk9n{max-width:640px;padding:40px 24px;color:var(--body-text-color, #1f2937)}.empty-state.svelte-1xvfk9n h2:where(.svelte-1xvfk9n){margin:0 0 8px;font-size:20px;font-weight:700}.empty-state.svelte-1xvfk9n p:where(.svelte-1xvfk9n){margin:12px 0 8px;color:var(--body-text-color-subdued, #6b7280)}.empty-state.svelte-1xvfk9n pre:where(.svelte-1xvfk9n){background:var(--background-fill-secondary, #f9fafb);padding:16px;border-radius:var(--radius-lg, 8px);border:1px solid var(--border-color-primary, #e5e7eb);font-size:13px;overflow-x:auto}.empty-state.svelte-1xvfk9n code:where(.svelte-1xvfk9n){background:var(--background-fill-secondary, #f0f0f0);padding:1px 5px;border-radius:var(--radius-sm, 4px);font-size:13px}.empty-state.svelte-1xvfk9n pre:where(.svelte-1xvfk9n) code:where(.svelte-1xvfk9n){background:none;padding:0}*{margin:0;padding:0;box-sizing:border-box}body{font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,sans-serif;background:var(--background-fill-primary, #fff);color:var(--body-text-color, #1f2937);font-size:var(--text-md, 14px);-webkit-font-smoothing:antialiased}.app.svelte-1n46o8q{display:flex;height:100vh;overflow:hidden}.main.svelte-1n46o8q{flex:1;display:flex;flex-direction:column;overflow:hidden;min-width:0}.page-content.svelte-1n46o8q{flex:1;overflow:hidden;display:flex;background:var(--bg-primary)}
trackio/frontend/dist/assets/index-UYQ1xITV.js ADDED
The diff for this file is too large to render. See raw diff
 
trackio/frontend/dist/index.html ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>Trackio Dashboard</title>
7
+ <link rel="icon" type="image/png" href="/static/trackio/trackio_logo_light.png" />
8
+ <script type="module" crossorigin src="/assets/index-UYQ1xITV.js"></script>
9
+ <link rel="stylesheet" crossorigin href="/assets/index-Cs1UkfOV.css">
10
+ </head>
11
+ <body>
12
+ <div id="app"></div>
13
+ </body>
14
+ </html>
trackio/frontend/eslint.config.js ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import js from "@eslint/js";
2
+ import svelte from "eslint-plugin-svelte";
3
+ import svelteParser from "svelte-eslint-parser";
4
+ import globals from "globals";
5
+
6
+ export default [
7
+ { ignores: ["dist/**", "node_modules/**"] },
8
+ {
9
+ files: ["**/*.js"],
10
+ languageOptions: {
11
+ globals: {
12
+ ...globals.browser,
13
+ ...globals.es2021,
14
+ $state: "readonly",
15
+ $derived: "readonly",
16
+ $effect: "readonly",
17
+ $props: "readonly",
18
+ $bindable: "readonly",
19
+ $inspect: "readonly",
20
+ },
21
+ },
22
+ rules: {
23
+ ...js.configs.recommended.rules,
24
+ "no-unused-vars": ["error", { argsIgnorePattern: "^_" }],
25
+ "no-empty": "off",
26
+ },
27
+ },
28
+ {
29
+ files: ["**/*.svelte"],
30
+ languageOptions: {
31
+ parser: svelteParser,
32
+ globals: { ...globals.browser, ...globals.es2021 },
33
+ },
34
+ plugins: { svelte },
35
+ rules: {
36
+ ...js.configs.recommended.rules,
37
+ ...svelte.configs.recommended.rules,
38
+ "no-unused-vars": ["error", { argsIgnorePattern: "^_", varsIgnorePattern: "^\\$" }],
39
+ "no-empty": "off",
40
+ },
41
+ },
42
+ ];
trackio/frontend/index.html ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>Trackio Dashboard</title>
7
+ <link rel="icon" type="image/png" href="/static/trackio/trackio_logo_light.png" />
8
+ </head>
9
+ <body>
10
+ <div id="app"></div>
11
+ <script type="module" src="/src/main.js"></script>
12
+ </body>
13
+ </html>
trackio/frontend_server.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Serves the built Svelte frontend alongside the Gradio API."""
2
+
3
+ import logging
4
+ import re
5
+ from pathlib import Path
6
+
7
+ from starlette.responses import HTMLResponse
8
+ from starlette.routing import Mount, Route
9
+ from starlette.staticfiles import StaticFiles
10
+
11
+ FRONTEND_DIR = Path(__file__).parent / "frontend" / "dist"
12
+ ASSETS_DIR = Path(__file__).parent / "assets"
13
+
14
+ _logger = logging.getLogger(__name__)
15
+
16
+ _SPA_SEGMENTS = (
17
+ "metrics",
18
+ "system",
19
+ "media",
20
+ "reports",
21
+ "runs",
22
+ "run",
23
+ "files",
24
+ )
25
+
26
+
27
+ def mount_frontend(app):
28
+ if not FRONTEND_DIR.exists():
29
+ _logger.warning(
30
+ "Trackio dashboard UI was not mounted: %s is missing. "
31
+ "Build the frontend with `npm ci && npm run build` in trackio/frontend.",
32
+ FRONTEND_DIR,
33
+ )
34
+ return
35
+
36
+ index_html_path = FRONTEND_DIR / "index.html"
37
+ if not index_html_path.exists():
38
+ _logger.warning(
39
+ "Trackio dashboard UI was not mounted: %s is missing.",
40
+ index_html_path,
41
+ )
42
+ return
43
+
44
+ index_html_content = index_html_path.read_text()
45
+ patched_html = re.sub(
46
+ r'/assets/(index-[^"]+)',
47
+ r"/assets/app/\1",
48
+ index_html_content,
49
+ )
50
+
51
+ async def serve_frontend(request):
52
+ return HTMLResponse(patched_html)
53
+
54
+ vite_assets = StaticFiles(directory=str(FRONTEND_DIR / "assets"))
55
+ static_assets = StaticFiles(directory=str(ASSETS_DIR))
56
+
57
+ app.routes.insert(0, Mount("/static/trackio", app=static_assets))
58
+ app.routes.insert(0, Mount("/assets/app", app=vite_assets))
59
+
60
+ for seg in reversed(_SPA_SEGMENTS):
61
+ app.routes.insert(0, Route(f"/{seg}/", serve_frontend, methods=["GET"]))
62
+ app.routes.insert(0, Route(f"/{seg}", serve_frontend, methods=["GET"]))
63
+ app.routes.insert(0, Route("/", serve_frontend, methods=["GET"]))
trackio/gpu.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import threading
3
+ import warnings
4
+ from typing import TYPE_CHECKING, Any
5
+
6
+ if TYPE_CHECKING:
7
+ from trackio.run import Run
8
+
9
+ pynvml: Any = None
10
+ PYNVML_AVAILABLE = False
11
+ _nvml_initialized = False
12
+ _nvml_lock = threading.Lock()
13
+ _energy_baseline: dict[int, float] = {}
14
+
15
+
16
+ def _ensure_pynvml():
17
+ global PYNVML_AVAILABLE, pynvml
18
+ if PYNVML_AVAILABLE:
19
+ return pynvml
20
+ try:
21
+ import pynvml as _pynvml
22
+
23
+ pynvml = _pynvml
24
+ PYNVML_AVAILABLE = True
25
+ return pynvml
26
+ except ImportError:
27
+ raise ImportError(
28
+ "nvidia-ml-py is required for GPU monitoring. "
29
+ "Install it with: pip install nvidia-ml-py"
30
+ )
31
+
32
+
33
+ def _init_nvml() -> bool:
34
+ global _nvml_initialized
35
+ with _nvml_lock:
36
+ if _nvml_initialized:
37
+ return True
38
+ try:
39
+ nvml = _ensure_pynvml()
40
+ nvml.nvmlInit()
41
+ _nvml_initialized = True
42
+ return True
43
+ except Exception:
44
+ return False
45
+
46
+
47
+ def get_gpu_count() -> tuple[int, list[int]]:
48
+ """
49
+ Get the number of GPUs visible to this process and their physical indices.
50
+ Respects CUDA_VISIBLE_DEVICES environment variable.
51
+
52
+ Returns:
53
+ Tuple of (count, physical_indices) where:
54
+ - count: Number of visible GPUs
55
+ - physical_indices: List mapping logical index to physical GPU index.
56
+ e.g., if CUDA_VISIBLE_DEVICES=2,3 returns (2, [2, 3])
57
+ meaning logical GPU 0 = physical GPU 2, logical GPU 1 = physical GPU 3
58
+ """
59
+ if not _init_nvml():
60
+ return 0, []
61
+
62
+ cuda_visible = os.environ.get("CUDA_VISIBLE_DEVICES")
63
+ if cuda_visible is not None and cuda_visible.strip():
64
+ try:
65
+ indices = [int(x.strip()) for x in cuda_visible.split(",") if x.strip()]
66
+ return len(indices), indices
67
+ except ValueError:
68
+ pass
69
+
70
+ try:
71
+ total = pynvml.nvmlDeviceGetCount()
72
+ return total, list(range(total))
73
+ except Exception:
74
+ return 0, []
75
+
76
+
77
+ def gpu_available() -> bool:
78
+ """
79
+ Check if GPU monitoring is available.
80
+
81
+ Returns True if nvidia-ml-py is installed and at least one NVIDIA GPU is detected.
82
+ This is used for auto-detection of GPU logging.
83
+ """
84
+ try:
85
+ _ensure_pynvml()
86
+ count, _ = get_gpu_count()
87
+ return count > 0
88
+ except ImportError:
89
+ return False
90
+ except Exception:
91
+ return False
92
+
93
+
94
+ def reset_energy_baseline():
95
+ """Reset the energy baseline for all GPUs. Called when a new run starts."""
96
+ global _energy_baseline
97
+ _energy_baseline = {}
98
+
99
+
100
+ def collect_gpu_metrics(device: int | None = None) -> dict:
101
+ """
102
+ Collect GPU metrics for visible GPUs.
103
+
104
+ Args:
105
+ device: CUDA device index to collect metrics from. If None, collects
106
+ from all GPUs visible to this process (respects CUDA_VISIBLE_DEVICES).
107
+ The device index is the logical CUDA index (0, 1, 2...), not the
108
+ physical GPU index.
109
+
110
+ Returns:
111
+ Dictionary of GPU metrics. Keys use logical device indices (gpu/0/, gpu/1/, etc.)
112
+ which correspond to CUDA device indices, not physical GPU indices.
113
+ """
114
+ if not _init_nvml():
115
+ return {}
116
+
117
+ gpu_count, visible_gpus = get_gpu_count()
118
+ if gpu_count == 0:
119
+ return {}
120
+
121
+ if device is not None:
122
+ if device < 0 or device >= gpu_count:
123
+ return {}
124
+ gpu_indices = [(device, visible_gpus[device])]
125
+ else:
126
+ gpu_indices = list(enumerate(visible_gpus))
127
+
128
+ metrics = {}
129
+ total_util = 0.0
130
+ total_mem_used_gib = 0.0
131
+ total_power = 0.0
132
+ max_temp = 0.0
133
+ valid_util_count = 0
134
+
135
+ for logical_idx, physical_idx in gpu_indices:
136
+ prefix = f"gpu/{logical_idx}"
137
+ try:
138
+ handle = pynvml.nvmlDeviceGetHandleByIndex(physical_idx)
139
+
140
+ try:
141
+ util = pynvml.nvmlDeviceGetUtilizationRates(handle)
142
+ metrics[f"{prefix}/utilization"] = util.gpu
143
+ metrics[f"{prefix}/memory_utilization"] = util.memory
144
+ total_util += util.gpu
145
+ valid_util_count += 1
146
+ except Exception:
147
+ pass
148
+
149
+ try:
150
+ mem = pynvml.nvmlDeviceGetMemoryInfo(handle)
151
+ mem_used_gib = mem.used / (1024**3)
152
+ mem_total_gib = mem.total / (1024**3)
153
+ metrics[f"{prefix}/allocated_memory"] = mem_used_gib
154
+ metrics[f"{prefix}/total_memory"] = mem_total_gib
155
+ if mem.total > 0:
156
+ metrics[f"{prefix}/memory_usage"] = mem.used / mem.total
157
+ total_mem_used_gib += mem_used_gib
158
+ except Exception:
159
+ pass
160
+
161
+ try:
162
+ power_mw = pynvml.nvmlDeviceGetPowerUsage(handle)
163
+ power_w = power_mw / 1000.0
164
+ metrics[f"{prefix}/power"] = power_w
165
+ total_power += power_w
166
+ except Exception:
167
+ pass
168
+
169
+ try:
170
+ power_limit_mw = pynvml.nvmlDeviceGetPowerManagementLimit(handle)
171
+ power_limit_w = power_limit_mw / 1000.0
172
+ metrics[f"{prefix}/power_limit"] = power_limit_w
173
+ if power_limit_w > 0 and f"{prefix}/power" in metrics:
174
+ metrics[f"{prefix}/power_percent"] = (
175
+ metrics[f"{prefix}/power"] / power_limit_w
176
+ ) * 100
177
+ except Exception:
178
+ pass
179
+
180
+ try:
181
+ temp = pynvml.nvmlDeviceGetTemperature(
182
+ handle, pynvml.NVML_TEMPERATURE_GPU
183
+ )
184
+ metrics[f"{prefix}/temp"] = temp
185
+ max_temp = max(max_temp, temp)
186
+ except Exception:
187
+ pass
188
+
189
+ try:
190
+ sm_clock = pynvml.nvmlDeviceGetClockInfo(handle, pynvml.NVML_CLOCK_SM)
191
+ metrics[f"{prefix}/sm_clock"] = sm_clock
192
+ except Exception:
193
+ pass
194
+
195
+ try:
196
+ mem_clock = pynvml.nvmlDeviceGetClockInfo(handle, pynvml.NVML_CLOCK_MEM)
197
+ metrics[f"{prefix}/memory_clock"] = mem_clock
198
+ except Exception:
199
+ pass
200
+
201
+ try:
202
+ fan_speed = pynvml.nvmlDeviceGetFanSpeed(handle)
203
+ metrics[f"{prefix}/fan_speed"] = fan_speed
204
+ except Exception:
205
+ pass
206
+
207
+ try:
208
+ pstate = pynvml.nvmlDeviceGetPerformanceState(handle)
209
+ metrics[f"{prefix}/performance_state"] = pstate
210
+ except Exception:
211
+ pass
212
+
213
+ try:
214
+ energy_mj = pynvml.nvmlDeviceGetTotalEnergyConsumption(handle)
215
+ if logical_idx not in _energy_baseline:
216
+ _energy_baseline[logical_idx] = energy_mj
217
+ energy_consumed_mj = energy_mj - _energy_baseline[logical_idx]
218
+ metrics[f"{prefix}/energy_consumed"] = energy_consumed_mj / 1000.0
219
+ except Exception:
220
+ pass
221
+
222
+ try:
223
+ pcie_tx = pynvml.nvmlDeviceGetPcieThroughput(
224
+ handle, pynvml.NVML_PCIE_UTIL_TX_BYTES
225
+ )
226
+ pcie_rx = pynvml.nvmlDeviceGetPcieThroughput(
227
+ handle, pynvml.NVML_PCIE_UTIL_RX_BYTES
228
+ )
229
+ metrics[f"{prefix}/pcie_tx"] = pcie_tx / 1024.0
230
+ metrics[f"{prefix}/pcie_rx"] = pcie_rx / 1024.0
231
+ except Exception:
232
+ pass
233
+
234
+ try:
235
+ throttle = pynvml.nvmlDeviceGetCurrentClocksThrottleReasons(handle)
236
+ metrics[f"{prefix}/throttle_thermal"] = int(
237
+ bool(throttle & pynvml.nvmlClocksThrottleReasonSwThermalSlowdown)
238
+ )
239
+ metrics[f"{prefix}/throttle_power"] = int(
240
+ bool(throttle & pynvml.nvmlClocksThrottleReasonSwPowerCap)
241
+ )
242
+ metrics[f"{prefix}/throttle_hw_slowdown"] = int(
243
+ bool(throttle & pynvml.nvmlClocksThrottleReasonHwSlowdown)
244
+ )
245
+ metrics[f"{prefix}/throttle_apps"] = int(
246
+ bool(
247
+ throttle
248
+ & pynvml.nvmlClocksThrottleReasonApplicationsClocksSetting
249
+ )
250
+ )
251
+ except Exception:
252
+ pass
253
+
254
+ try:
255
+ ecc_corrected = pynvml.nvmlDeviceGetTotalEccErrors(
256
+ handle,
257
+ pynvml.NVML_MEMORY_ERROR_TYPE_CORRECTED,
258
+ pynvml.NVML_VOLATILE_ECC,
259
+ )
260
+ metrics[f"{prefix}/corrected_memory_errors"] = ecc_corrected
261
+ except Exception:
262
+ pass
263
+
264
+ try:
265
+ ecc_uncorrected = pynvml.nvmlDeviceGetTotalEccErrors(
266
+ handle,
267
+ pynvml.NVML_MEMORY_ERROR_TYPE_UNCORRECTED,
268
+ pynvml.NVML_VOLATILE_ECC,
269
+ )
270
+ metrics[f"{prefix}/uncorrected_memory_errors"] = ecc_uncorrected
271
+ except Exception:
272
+ pass
273
+
274
+ except Exception:
275
+ continue
276
+
277
+ if valid_util_count > 0:
278
+ metrics["gpu/mean_utilization"] = total_util / valid_util_count
279
+ if total_mem_used_gib > 0:
280
+ metrics["gpu/total_allocated_memory"] = total_mem_used_gib
281
+ if total_power > 0:
282
+ metrics["gpu/total_power"] = total_power
283
+ if max_temp > 0:
284
+ metrics["gpu/max_temp"] = max_temp
285
+
286
+ return metrics
287
+
288
+
289
+ class GpuMonitor:
290
+ def __init__(self, run: "Run", interval: float = 10.0):
291
+ self._run = run
292
+ self._interval = interval
293
+ self._stop_flag = threading.Event()
294
+ self._thread: "threading.Thread | None" = None
295
+
296
+ def start(self):
297
+ count, _ = get_gpu_count()
298
+ if count == 0:
299
+ warnings.warn(
300
+ "auto_log_gpu=True but no NVIDIA GPUs detected. GPU logging disabled."
301
+ )
302
+ return
303
+
304
+ reset_energy_baseline()
305
+ self._thread = threading.Thread(target=self._monitor_loop, daemon=True)
306
+ self._thread.start()
307
+
308
+ def stop(self):
309
+ self._stop_flag.set()
310
+ if self._thread is not None:
311
+ self._thread.join(timeout=2.0)
312
+
313
+ def _monitor_loop(self):
314
+ while not self._stop_flag.is_set():
315
+ try:
316
+ metrics = collect_gpu_metrics()
317
+ if metrics:
318
+ self._run.log_system(metrics)
319
+ except Exception:
320
+ pass
321
+
322
+ self._stop_flag.wait(timeout=self._interval)
323
+
324
+
325
+ def log_gpu(run: "Run | None" = None, device: int | None = None) -> dict:
326
+ """
327
+ Log GPU metrics to the current or specified run as system metrics.
328
+
329
+ Args:
330
+ run: Optional Run instance. If None, uses current run from context.
331
+ device: CUDA device index to collect metrics from. If None, collects
332
+ from all GPUs visible to this process (respects CUDA_VISIBLE_DEVICES).
333
+
334
+ Returns:
335
+ dict: The GPU metrics that were logged.
336
+
337
+ Example:
338
+ ```python
339
+ import trackio
340
+
341
+ run = trackio.init(project="my-project")
342
+ trackio.log({"loss": 0.5})
343
+ trackio.log_gpu() # logs all visible GPUs
344
+ trackio.log_gpu(device=0) # logs only CUDA device 0
345
+ ```
346
+ """
347
+ from trackio import context_vars
348
+
349
+ if run is None:
350
+ run = context_vars.current_run.get()
351
+ if run is None:
352
+ raise RuntimeError("Call trackio.init() before trackio.log_gpu().")
353
+
354
+ metrics = collect_gpu_metrics(device=device)
355
+ if metrics:
356
+ run.log_system(metrics)
357
+ return metrics
trackio/histogram.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Sequence
2
+
3
+ import numpy as np
4
+
5
+
6
+ class Histogram:
7
+ """
8
+ Histogram data type for Trackio, compatible with wandb.Histogram.
9
+
10
+ Args:
11
+ sequence (`np.ndarray` or `Sequence[float]` or `Sequence[int]`, *optional*):
12
+ Sequence of values to create the histogram from.
13
+ np_histogram (`tuple`, *optional*):
14
+ Pre-computed NumPy histogram as a `(hist, bins)` tuple.
15
+ num_bins (`int`, *optional*, defaults to `64`):
16
+ Number of bins for the histogram (maximum `512`).
17
+
18
+ Example:
19
+ ```python
20
+ import trackio
21
+ import numpy as np
22
+
23
+ # Create histogram from sequence
24
+ data = np.random.randn(1000)
25
+ trackio.log({"distribution": trackio.Histogram(data)})
26
+
27
+ # Create histogram from numpy histogram
28
+ hist, bins = np.histogram(data, bins=30)
29
+ trackio.log({"distribution": trackio.Histogram(np_histogram=(hist, bins))})
30
+
31
+ # Specify custom number of bins
32
+ trackio.log({"distribution": trackio.Histogram(data, num_bins=50)})
33
+ ```
34
+ """
35
+
36
+ TYPE = "trackio.histogram"
37
+
38
+ def __init__(
39
+ self,
40
+ sequence: np.ndarray | Sequence[float] | Sequence[int] | None = None,
41
+ np_histogram: tuple | None = None,
42
+ num_bins: int = 64,
43
+ ):
44
+ if sequence is None and np_histogram is None:
45
+ raise ValueError("Must provide either sequence or np_histogram")
46
+
47
+ if sequence is not None and np_histogram is not None:
48
+ raise ValueError("Cannot provide both sequence and np_histogram")
49
+
50
+ num_bins = min(num_bins, 512)
51
+
52
+ if np_histogram is not None:
53
+ self.histogram, self.bins = np_histogram
54
+ self.histogram = np.asarray(self.histogram)
55
+ self.bins = np.asarray(self.bins)
56
+ else:
57
+ data = np.asarray(sequence).flatten()
58
+ data = data[np.isfinite(data)]
59
+ if len(data) == 0:
60
+ self.histogram = np.array([])
61
+ self.bins = np.array([])
62
+ else:
63
+ self.histogram, self.bins = np.histogram(data, bins=num_bins)
64
+
65
+ def _to_dict(self) -> dict:
66
+ """Convert histogram to dictionary for storage."""
67
+ return {
68
+ "_type": self.TYPE,
69
+ "bins": self.bins.tolist(),
70
+ "values": self.histogram.tolist(),
71
+ }
trackio/imports.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ force: bool = False,
18
+ ) -> None:
19
+ """
20
+ Imports a CSV file into a Trackio project. The CSV file must contain a `"step"`
21
+ column, may optionally contain a `"timestamp"` column, and any other columns will be
22
+ treated as metrics. It should also include a header row with the column names.
23
+
24
+ TODO: call init() and return a Run object so that the user can continue to log metrics to it.
25
+
26
+ Args:
27
+ csv_path (`str` or `Path`):
28
+ The str or Path to the CSV file to import.
29
+ project (`str`):
30
+ The name of the project to import the CSV file into. Must not be an existing
31
+ project.
32
+ name (`str`, *optional*):
33
+ The name of the Run to import the CSV file into. If not provided, a default
34
+ name will be generated.
35
+ name (`str`, *optional*):
36
+ The name of the run (if not provided, a default name will be generated).
37
+ space_id (`str`, *optional*):
38
+ If provided, the project will be logged to a Hugging Face Space instead of a
39
+ local directory. Should be a complete Space name like `"username/reponame"`
40
+ or `"orgname/reponame"`, or just `"reponame"` in which case the Space will
41
+ be created in the currently-logged-in Hugging Face user's namespace. If the
42
+ Space does not exist, it will be created. If the Space already exists, the
43
+ project will be logged to it.
44
+ dataset_id (`str`, *optional*):
45
+ Deprecated. Use `bucket_id` instead.
46
+ private (`bool`, *optional*):
47
+ Whether to make the Space private. If None (default), the repo will be
48
+ public unless the organization's default is private. This value is ignored
49
+ if the repo already exists.
50
+ """
51
+ if SQLiteStorage.get_runs(project):
52
+ raise ValueError(
53
+ f"Project '{project}' already exists. Cannot import CSV into existing project."
54
+ )
55
+
56
+ csv_path = Path(csv_path)
57
+ if not csv_path.exists():
58
+ raise FileNotFoundError(f"CSV file not found: {csv_path}")
59
+
60
+ df = pd.read_csv(csv_path)
61
+ if df.empty:
62
+ raise ValueError("CSV file is empty")
63
+
64
+ column_mapping = utils.simplify_column_names(df.columns.tolist())
65
+ df = df.rename(columns=column_mapping)
66
+
67
+ step_column = None
68
+ for col in df.columns:
69
+ if col.lower() == "step":
70
+ step_column = col
71
+ break
72
+
73
+ if step_column is None:
74
+ raise ValueError("CSV file must contain a 'step' or 'Step' column")
75
+
76
+ if name is None:
77
+ name = csv_path.stem
78
+
79
+ metrics_list = []
80
+ steps = []
81
+ timestamps = []
82
+
83
+ numeric_columns = []
84
+ for column in df.columns:
85
+ if column == step_column:
86
+ continue
87
+ if column == "timestamp":
88
+ continue
89
+
90
+ try:
91
+ pd.to_numeric(df[column], errors="raise")
92
+ numeric_columns.append(column)
93
+ except (ValueError, TypeError):
94
+ continue
95
+
96
+ for _, row in df.iterrows():
97
+ metrics = {}
98
+ for column in numeric_columns:
99
+ value = row[column]
100
+ if bool(pd.notna(value)):
101
+ metrics[column] = float(value)
102
+
103
+ if metrics:
104
+ metrics_list.append(metrics)
105
+ steps.append(int(row[step_column]))
106
+
107
+ if "timestamp" in df.columns and bool(pd.notna(row["timestamp"])):
108
+ timestamps.append(str(row["timestamp"]))
109
+ else:
110
+ timestamps.append("")
111
+
112
+ if metrics_list:
113
+ SQLiteStorage.bulk_log(
114
+ project=project,
115
+ run=name,
116
+ metrics_list=metrics_list,
117
+ steps=steps,
118
+ timestamps=timestamps,
119
+ )
120
+
121
+ print(
122
+ f"* Imported {len(metrics_list)} rows from {csv_path} into project '{project}' as run '{name}'"
123
+ )
124
+ print(f"* Metrics found: {', '.join(metrics_list[0].keys())}")
125
+
126
+ space_id, dataset_id, _ = utils.preprocess_space_and_dataset_ids(
127
+ space_id, dataset_id
128
+ )
129
+ if dataset_id is not None:
130
+ os.environ["TRACKIO_DATASET_ID"] = dataset_id
131
+ print(f"* Trackio metrics will be synced to Hugging Face Dataset: {dataset_id}")
132
+
133
+ if space_id is None:
134
+ utils.print_dashboard_instructions(project)
135
+ else:
136
+ deploy.create_space_if_not_exists(
137
+ space_id=space_id, dataset_id=dataset_id, private=private
138
+ )
139
+ deploy.wait_until_space_exists(space_id=space_id)
140
+ deploy.upload_db_to_space(project=project, space_id=space_id, force=force)
141
+ print(
142
+ f"* View dashboard by going to: {deploy.SPACE_URL.format(space_id=space_id)}"
143
+ )
144
+
145
+
146
+ def import_tf_events(
147
+ log_dir: str | Path,
148
+ project: str,
149
+ name: str | None = None,
150
+ space_id: str | None = None,
151
+ dataset_id: str | None = None,
152
+ private: bool | None = None,
153
+ force: bool = False,
154
+ ) -> None:
155
+ """
156
+ Imports TensorFlow Events files from a directory into a Trackio project. Each
157
+ subdirectory in the log directory will be imported as a separate run.
158
+
159
+ Args:
160
+ log_dir (`str` or `Path`):
161
+ The str or Path to the directory containing TensorFlow Events files.
162
+ project (`str`):
163
+ The name of the project to import the TensorFlow Events files into. Must not
164
+ be an existing project.
165
+ name (`str`, *optional*):
166
+ The name prefix for runs (if not provided, will use directory names). Each
167
+ subdirectory will create a separate run.
168
+ space_id (`str`, *optional*):
169
+ If provided, the project will be logged to a Hugging Face Space instead of a
170
+ local directory. Should be a complete Space name like `"username/reponame"`
171
+ or `"orgname/reponame"`, or just `"reponame"` in which case the Space will
172
+ be created in the currently-logged-in Hugging Face user's namespace. If the
173
+ Space does not exist, it will be created. If the Space already exists, the
174
+ project will be logged to it.
175
+ dataset_id (`str`, *optional*):
176
+ Deprecated. Use `bucket_id` instead.
177
+ private (`bool`, *optional*):
178
+ Whether to make the Space private. If None (default), the repo will be
179
+ public unless the organization's default is private. This value is ignored
180
+ if the repo already exists.
181
+ """
182
+ try:
183
+ from tbparse import SummaryReader
184
+ except ImportError:
185
+ raise ImportError(
186
+ "The `tbparse` package is not installed but is required for `import_tf_events`. Please install trackio with the `tensorboard` extra: `pip install trackio[tensorboard]`."
187
+ )
188
+
189
+ if SQLiteStorage.get_runs(project):
190
+ raise ValueError(
191
+ f"Project '{project}' already exists. Cannot import TF events into existing project."
192
+ )
193
+
194
+ path = Path(log_dir)
195
+ if not path.exists():
196
+ raise FileNotFoundError(f"TF events directory not found: {path}")
197
+
198
+ # Use tbparse to read all tfevents files in the directory structure
199
+ reader = SummaryReader(str(path), extra_columns={"dir_name"})
200
+ df = reader.scalars
201
+
202
+ if df.empty:
203
+ raise ValueError(f"No TensorFlow events data found in {path}")
204
+
205
+ total_imported = 0
206
+ imported_runs = []
207
+
208
+ # Group by dir_name to create separate runs
209
+ for dir_name, group_df in df.groupby("dir_name"):
210
+ try:
211
+ # Determine run name based on directory name
212
+ if dir_name == "":
213
+ run_name = "main" # For files in the root directory
214
+ else:
215
+ run_name = dir_name # Use directory name
216
+
217
+ if name:
218
+ run_name = f"{name}_{run_name}"
219
+
220
+ if group_df.empty:
221
+ print(f"* Skipping directory {dir_name}: no scalar data found")
222
+ continue
223
+
224
+ metrics_list = []
225
+ steps = []
226
+ timestamps = []
227
+
228
+ for _, row in group_df.iterrows():
229
+ # Convert row values to appropriate types
230
+ tag = str(row["tag"])
231
+ value = float(row["value"])
232
+ step = int(row["step"])
233
+
234
+ metrics = {tag: value}
235
+ metrics_list.append(metrics)
236
+ steps.append(step)
237
+
238
+ # Use wall_time if present, else fallback
239
+ if "wall_time" in group_df.columns and not bool(
240
+ pd.isna(row["wall_time"])
241
+ ):
242
+ timestamps.append(str(row["wall_time"]))
243
+ else:
244
+ timestamps.append("")
245
+
246
+ if metrics_list:
247
+ SQLiteStorage.bulk_log(
248
+ project=project,
249
+ run=str(run_name),
250
+ metrics_list=metrics_list,
251
+ steps=steps,
252
+ timestamps=timestamps,
253
+ )
254
+
255
+ total_imported += len(metrics_list)
256
+ imported_runs.append(run_name)
257
+
258
+ print(
259
+ f"* Imported {len(metrics_list)} scalar events from directory '{dir_name}' as run '{run_name}'"
260
+ )
261
+ print(f"* Metrics in this run: {', '.join(set(group_df['tag']))}")
262
+
263
+ except Exception as e:
264
+ print(f"* Error processing directory {dir_name}: {e}")
265
+ continue
266
+
267
+ if not imported_runs:
268
+ raise ValueError("No valid TensorFlow events data could be imported")
269
+
270
+ print(f"* Total imported events: {total_imported}")
271
+ print(f"* Created runs: {', '.join(imported_runs)}")
272
+
273
+ space_id, dataset_id, _ = utils.preprocess_space_and_dataset_ids(
274
+ space_id, dataset_id
275
+ )
276
+ if dataset_id is not None:
277
+ os.environ["TRACKIO_DATASET_ID"] = dataset_id
278
+ print(f"* Trackio metrics will be synced to Hugging Face Dataset: {dataset_id}")
279
+
280
+ if space_id is None:
281
+ utils.print_dashboard_instructions(project)
282
+ else:
283
+ deploy.create_space_if_not_exists(
284
+ space_id, dataset_id=dataset_id, private=private
285
+ )
286
+ deploy.wait_until_space_exists(space_id)
287
+ deploy.upload_db_to_space(project, space_id, force=force)
288
+ print(
289
+ f"* View dashboard by going to: {deploy.SPACE_URL.format(space_id=space_id)}"
290
+ )
trackio/markdown.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class Markdown:
2
+ """
3
+ Markdown report data type for Trackio.
4
+
5
+ Args:
6
+ text (`str`):
7
+ Markdown content to log.
8
+ """
9
+
10
+ TYPE = "trackio.markdown"
11
+
12
+ def __init__(self, text: str = ""):
13
+ if not isinstance(text, str):
14
+ raise ValueError("Markdown text must be a string")
15
+ self.text = text
16
+
17
+ def _to_dict(self) -> dict:
18
+ return {
19
+ "_type": self.TYPE,
20
+ "_value": self.text,
21
+ }
trackio/media/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from trackio.media.audio import TrackioAudio
11
+ from trackio.media.image import TrackioImage
12
+ from trackio.media.media import TrackioMedia
13
+ from trackio.media.utils import get_project_media_path
14
+ from trackio.media.video import TrackioVideo
15
+
16
+ write_audio = TrackioAudio.write_audio
17
+ write_video = TrackioVideo.write_video
18
+
19
+ __all__ = [
20
+ "TrackioMedia",
21
+ "TrackioImage",
22
+ "TrackioVideo",
23
+ "TrackioAudio",
24
+ "get_project_media_path",
25
+ "write_video",
26
+ "write_audio",
27
+ ]
trackio/media/audio.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import warnings
4
+ from pathlib import Path
5
+ from typing import Literal
6
+
7
+ import numpy as np
8
+ from pydub import AudioSegment
9
+
10
+ from trackio.media.media import TrackioMedia
11
+ from trackio.media.utils import check_ffmpeg_installed, check_path
12
+
13
+ SUPPORTED_FORMATS = ["wav", "mp3"]
14
+ AudioFormatType = Literal["wav", "mp3"]
15
+ TrackioAudioSourceType = str | Path | np.ndarray
16
+
17
+
18
+ class TrackioAudio(TrackioMedia):
19
+ """
20
+ Initializes an Audio object.
21
+
22
+ Example:
23
+ ```python
24
+ import trackio
25
+ import numpy as np
26
+
27
+ # Generate a 1-second 440 Hz sine wave (mono)
28
+ sr = 16000
29
+ t = np.linspace(0, 1, sr, endpoint=False)
30
+ wave = 0.2 * np.sin(2 * np.pi * 440 * t)
31
+ audio = trackio.Audio(wave, caption="A4 sine", sample_rate=sr, format="wav")
32
+ trackio.log({"tone": audio})
33
+
34
+ # Stereo from numpy array (shape: samples, 2)
35
+ stereo = np.stack([wave, wave], axis=1)
36
+ audio = trackio.Audio(stereo, caption="Stereo", sample_rate=sr, format="mp3")
37
+ trackio.log({"stereo": audio})
38
+
39
+ # From an existing file
40
+ audio = trackio.Audio("path/to/audio.wav", caption="From file")
41
+ trackio.log({"file_audio": audio})
42
+ ```
43
+
44
+ Args:
45
+ value (`str`, `Path`, or `numpy.ndarray`, *optional*):
46
+ A path to an audio file, or a numpy array.
47
+ The array should be shaped `(samples,)` for mono or `(samples, 2)` for stereo.
48
+ Float arrays will be peak-normalized and converted to 16-bit PCM; integer arrays will be converted to 16-bit PCM as needed.
49
+ caption (`str`, *optional*):
50
+ A string caption for the audio.
51
+ sample_rate (`int`, *optional*):
52
+ Sample rate in Hz. Required when `value` is a numpy array.
53
+ format (`Literal["wav", "mp3"]`, *optional*):
54
+ Audio format used when `value` is a numpy array. Default is "wav".
55
+ """
56
+
57
+ TYPE = "trackio.audio"
58
+
59
+ def __init__(
60
+ self,
61
+ value: TrackioAudioSourceType,
62
+ caption: str | None = None,
63
+ sample_rate: int | None = None,
64
+ format: AudioFormatType | None = None,
65
+ ):
66
+ super().__init__(value, caption)
67
+ if isinstance(value, np.ndarray):
68
+ if sample_rate is None:
69
+ raise ValueError("Sample rate is required when value is an ndarray")
70
+ if format is None:
71
+ format = "wav"
72
+ self._format = format
73
+ self._sample_rate = sample_rate
74
+
75
+ def _save_media(self, file_path: Path):
76
+ if isinstance(self._value, np.ndarray):
77
+ TrackioAudio.write_audio(
78
+ data=self._value,
79
+ sample_rate=self._sample_rate,
80
+ filename=file_path,
81
+ format=self._format,
82
+ )
83
+ elif isinstance(self._value, str | Path):
84
+ if os.path.isfile(self._value):
85
+ shutil.copy(self._value, file_path)
86
+ else:
87
+ raise ValueError(f"File not found: {self._value}")
88
+
89
+ @staticmethod
90
+ def ensure_int16_pcm(data: np.ndarray) -> np.ndarray:
91
+ """
92
+ Convert input audio array to contiguous int16 PCM.
93
+ Peak normalization is applied to floating inputs.
94
+ """
95
+ arr = np.asarray(data)
96
+ if arr.ndim not in (1, 2):
97
+ raise ValueError("Audio data must be 1D (mono) or 2D ([samples, channels])")
98
+
99
+ if arr.dtype != np.int16:
100
+ warnings.warn(
101
+ f"Converting {arr.dtype} audio to int16 PCM; pass int16 to avoid conversion.",
102
+ stacklevel=2,
103
+ )
104
+
105
+ arr = np.nan_to_num(arr, copy=False)
106
+
107
+ # Floating types: normalize to peak 1.0, then scale to int16
108
+ if np.issubdtype(arr.dtype, np.floating):
109
+ max_abs = float(np.max(np.abs(arr))) if arr.size else 0.0
110
+ if max_abs > 0.0:
111
+ arr = arr / max_abs
112
+ out = (arr * 32767.0).clip(-32768, 32767).astype(np.int16, copy=False)
113
+ return np.ascontiguousarray(out)
114
+
115
+ converters: dict[np.dtype, callable] = {
116
+ np.dtype(np.int16): lambda a: a,
117
+ np.dtype(np.int32): lambda a: (a.astype(np.int32) // 65536).astype(
118
+ np.int16, copy=False
119
+ ),
120
+ np.dtype(np.uint16): lambda a: (a.astype(np.int32) - 32768).astype(
121
+ np.int16, copy=False
122
+ ),
123
+ np.dtype(np.uint8): lambda a: (a.astype(np.int32) * 257 - 32768).astype(
124
+ np.int16, copy=False
125
+ ),
126
+ np.dtype(np.int8): lambda a: (a.astype(np.int32) * 256).astype(
127
+ np.int16, copy=False
128
+ ),
129
+ }
130
+
131
+ conv = converters.get(arr.dtype)
132
+ if conv is not None:
133
+ out = conv(arr)
134
+ return np.ascontiguousarray(out)
135
+ raise TypeError(f"Unsupported audio dtype: {arr.dtype}")
136
+
137
+ @staticmethod
138
+ def write_audio(
139
+ data: np.ndarray,
140
+ sample_rate: int,
141
+ filename: str | Path,
142
+ format: AudioFormatType = "wav",
143
+ ) -> None:
144
+ if not isinstance(sample_rate, int) or sample_rate <= 0:
145
+ raise ValueError(f"Invalid sample_rate: {sample_rate}")
146
+ if format not in SUPPORTED_FORMATS:
147
+ raise ValueError(
148
+ f"Unsupported format: {format}. Supported: {SUPPORTED_FORMATS}"
149
+ )
150
+
151
+ check_path(filename)
152
+
153
+ pcm = TrackioAudio.ensure_int16_pcm(data)
154
+
155
+ if format != "wav":
156
+ check_ffmpeg_installed()
157
+
158
+ channels = 1 if pcm.ndim == 1 else pcm.shape[1]
159
+ audio = AudioSegment(
160
+ pcm.tobytes(),
161
+ frame_rate=sample_rate,
162
+ sample_width=2, # int16
163
+ channels=channels,
164
+ )
165
+
166
+ file = audio.export(str(filename), format=format)
167
+ file.close()
trackio/media/image.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ from pathlib import Path
4
+
5
+ import numpy as np
6
+ from PIL import Image as PILImage
7
+
8
+ from trackio.media.media import TrackioMedia
9
+
10
+ TrackioImageSourceType = str | Path | np.ndarray | PILImage.Image
11
+
12
+
13
+ class TrackioImage(TrackioMedia):
14
+ """
15
+ Initializes an Image object.
16
+
17
+ Example:
18
+ ```python
19
+ import trackio
20
+ import numpy as np
21
+ from PIL import Image
22
+
23
+ # Create an image from numpy array
24
+ image_data = np.random.randint(0, 255, (64, 64, 3), dtype=np.uint8)
25
+ image = trackio.Image(image_data, caption="Random image")
26
+ trackio.log({"my_image": image})
27
+
28
+ # Create an image from PIL Image
29
+ pil_image = Image.new('RGB', (100, 100), color='red')
30
+ image = trackio.Image(pil_image, caption="Red square")
31
+ trackio.log({"red_image": image})
32
+
33
+ # Create an image from file path
34
+ image = trackio.Image("path/to/image.jpg", caption="Photo from file")
35
+ trackio.log({"file_image": image})
36
+ ```
37
+
38
+ Args:
39
+ value (`str`, `Path`, `numpy.ndarray`, or `PIL.Image`, *optional*):
40
+ A path to an image, a PIL Image, or a numpy array of shape (height, width, channels).
41
+ If numpy array, should be of type `np.uint8` with RGB values in the range `[0, 255]`.
42
+ caption (`str`, *optional*):
43
+ A string caption for the image.
44
+ """
45
+
46
+ TYPE = "trackio.image"
47
+
48
+ def __init__(self, value: TrackioImageSourceType, caption: str | None = None):
49
+ super().__init__(value, caption)
50
+ self._format: str | None = None
51
+
52
+ if not isinstance(self._value, TrackioImageSourceType):
53
+ raise ValueError(
54
+ f"Invalid value type, expected {TrackioImageSourceType}, got {type(self._value)}"
55
+ )
56
+ if isinstance(self._value, np.ndarray) and self._value.dtype != np.uint8:
57
+ raise ValueError(
58
+ f"Invalid value dtype, expected np.uint8, got {self._value.dtype}"
59
+ )
60
+ if (
61
+ isinstance(self._value, np.ndarray | PILImage.Image)
62
+ and self._format is None
63
+ ):
64
+ self._format = "png"
65
+
66
+ def _as_pil(self) -> PILImage.Image | None:
67
+ try:
68
+ if isinstance(self._value, np.ndarray):
69
+ arr = np.asarray(self._value).astype("uint8")
70
+ return PILImage.fromarray(arr).convert("RGBA")
71
+ if isinstance(self._value, PILImage.Image):
72
+ return self._value.convert("RGBA")
73
+ except Exception as e:
74
+ raise ValueError(f"Failed to process image data: {self._value}") from e
75
+ return None
76
+
77
+ def _save_media(self, file_path: Path):
78
+ if pil := self._as_pil():
79
+ pil.save(file_path, format=self._format)
80
+ elif isinstance(self._value, str | Path):
81
+ if os.path.isfile(self._value):
82
+ shutil.copy(self._value, file_path)
83
+ else:
84
+ raise ValueError(f"File not found: {self._value}")
trackio/media/media.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import uuid
3
+ from abc import ABC, abstractmethod
4
+ from pathlib import Path
5
+
6
+ from trackio.media.utils import get_project_media_path
7
+ from trackio.utils import MEDIA_DIR
8
+
9
+
10
+ class TrackioMedia(ABC):
11
+ """
12
+ Abstract base class for Trackio media objects
13
+ Provides shared functionality for file handling and serialization.
14
+ """
15
+
16
+ TYPE: str
17
+
18
+ def __init_subclass__(cls, **kwargs):
19
+ """Ensure subclasses define the TYPE attribute."""
20
+ super().__init_subclass__(**kwargs)
21
+ if not hasattr(cls, "TYPE") or cls.TYPE is None:
22
+ raise TypeError(f"Class {cls.__name__} must define TYPE attribute")
23
+
24
+ def __init__(self, value, caption: str | None = None):
25
+ """
26
+ Saves the value and caption, and if the value is a file path, checks if the file exists.
27
+ """
28
+ self.caption = caption
29
+ self._value = value
30
+ self._file_path: Path | None = None
31
+
32
+ if isinstance(self._value, str | Path):
33
+ if not os.path.isfile(self._value):
34
+ raise ValueError(f"File not found: {self._value}")
35
+
36
+ def _file_extension(self) -> str:
37
+ if self._file_path:
38
+ return self._file_path.suffix[1:].lower()
39
+ if isinstance(self._value, str | Path):
40
+ path = Path(self._value)
41
+ return path.suffix[1:].lower()
42
+ if hasattr(self, "_format") and self._format:
43
+ return self._format
44
+ return "unknown"
45
+
46
+ def _get_relative_file_path(self) -> Path | None:
47
+ return self._file_path
48
+
49
+ def _get_absolute_file_path(self) -> Path | None:
50
+ if self._file_path:
51
+ return MEDIA_DIR / self._file_path
52
+ return None
53
+
54
+ def _save(self, project: str, run: str, step: int = 0):
55
+ if self._file_path:
56
+ return
57
+
58
+ media_dir = get_project_media_path(project=project, run=run, step=step)
59
+ filename = f"{uuid.uuid4()}.{self._file_extension()}"
60
+ file_path = media_dir / filename
61
+
62
+ self._save_media(file_path)
63
+ self._file_path = file_path.relative_to(MEDIA_DIR)
64
+
65
+ @abstractmethod
66
+ def _save_media(self, file_path: Path):
67
+ """
68
+ Performs the actual media saving logic.
69
+ """
70
+ pass
71
+
72
+ def _to_dict(self) -> dict:
73
+ if not self._file_path:
74
+ raise ValueError("Media must be saved to file before serialization")
75
+ return {
76
+ "_type": self.TYPE,
77
+ "file_path": str(self._get_relative_file_path()),
78
+ "caption": self.caption,
79
+ }
trackio/media/utils.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import shutil
2
+ from pathlib import Path
3
+
4
+ from trackio.utils import MEDIA_DIR
5
+
6
+
7
+ def check_path(file_path: str | Path) -> None:
8
+ """Raise an error if the parent directory does not exist."""
9
+ file_path = Path(file_path)
10
+ if not file_path.parent.exists():
11
+ try:
12
+ file_path.parent.mkdir(parents=True, exist_ok=True)
13
+ except OSError as e:
14
+ raise ValueError(
15
+ f"Failed to create parent directory {file_path.parent}: {e}"
16
+ )
17
+
18
+
19
+ def check_ffmpeg_installed() -> None:
20
+ """Raise an error if ffmpeg is not available on the system PATH."""
21
+ if shutil.which("ffmpeg") is None:
22
+ raise RuntimeError(
23
+ "ffmpeg is required to write video but was not found on your system. "
24
+ "Please install ffmpeg and ensure it is available on your PATH."
25
+ )
26
+
27
+
28
+ def get_project_media_path(
29
+ project: str,
30
+ run: str | None = None,
31
+ step: int | None = None,
32
+ relative_path: str | Path | None = None,
33
+ ) -> Path:
34
+ """
35
+ Get the full path where uploaded files are stored for a Trackio project (and create the directory if it doesn't exist).
36
+ If a run is not provided, the files are stored in a project-level directory with the given relative path.
37
+
38
+ Args:
39
+ project: The project name
40
+ run: The run name
41
+ step: The step number
42
+ relative_path: The relative path within the directory (only used if run is not provided)
43
+
44
+ Returns:
45
+ The full path to the media file
46
+ """
47
+ if step is not None and run is None:
48
+ raise ValueError("Uploading files at a specific step requires a run")
49
+
50
+ path = MEDIA_DIR / project
51
+ if run:
52
+ path /= run
53
+ if step is not None:
54
+ path /= str(step)
55
+ else:
56
+ path /= "files"
57
+ if relative_path:
58
+ path /= relative_path
59
+ path.mkdir(parents=True, exist_ok=True)
60
+ return path
trackio/media/video.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import subprocess
4
+ from pathlib import Path
5
+ from typing import Literal
6
+
7
+ import numpy as np
8
+
9
+ from trackio.media.media import TrackioMedia
10
+ from trackio.media.utils import check_ffmpeg_installed, check_path
11
+
12
+ TrackioVideoSourceType = str | Path | np.ndarray
13
+ TrackioVideoFormatType = Literal["gif", "mp4", "webm"]
14
+ VideoCodec = Literal["h264", "vp9", "gif"]
15
+
16
+
17
+ class TrackioVideo(TrackioMedia):
18
+ """
19
+ Initializes a Video object.
20
+
21
+ Example:
22
+ ```python
23
+ import trackio
24
+ import numpy as np
25
+
26
+ # Create a simple video from numpy array
27
+ frames = np.random.randint(0, 255, (10, 3, 64, 64), dtype=np.uint8)
28
+ video = trackio.Video(frames, caption="Random video", fps=30)
29
+
30
+ # Create a batch of videos
31
+ batch_frames = np.random.randint(0, 255, (3, 10, 3, 64, 64), dtype=np.uint8)
32
+ batch_video = trackio.Video(batch_frames, caption="Batch of videos", fps=15)
33
+
34
+ # Create video from file path
35
+ video = trackio.Video("path/to/video.mp4", caption="Video from file")
36
+ ```
37
+
38
+ Args:
39
+ value (`str`, `Path`, or `numpy.ndarray`, *optional*):
40
+ A path to a video file, or a numpy array.
41
+ If numpy array, should be of type `np.uint8` with RGB values in the range `[0, 255]`.
42
+ It is expected to have shape of either (frames, channels, height, width) or (batch, frames, channels, height, width).
43
+ For the latter, the videos will be tiled into a grid.
44
+ caption (`str`, *optional*):
45
+ A string caption for the video.
46
+ fps (`int`, *optional*):
47
+ Frames per second for the video. Only used when value is an ndarray. Default is `24`.
48
+ format (`Literal["gif", "mp4", "webm"]`, *optional*):
49
+ Video format ("gif", "mp4", or "webm"). Only used when value is an ndarray. Default is "gif".
50
+ """
51
+
52
+ TYPE = "trackio.video"
53
+
54
+ def __init__(
55
+ self,
56
+ value: TrackioVideoSourceType,
57
+ caption: str | None = None,
58
+ fps: int | None = None,
59
+ format: TrackioVideoFormatType | None = None,
60
+ ):
61
+ super().__init__(value, caption)
62
+
63
+ if not isinstance(self._value, TrackioVideoSourceType):
64
+ raise ValueError(
65
+ f"Invalid value type, expected {TrackioVideoSourceType}, got {type(self._value)}"
66
+ )
67
+ if isinstance(self._value, np.ndarray):
68
+ if self._value.dtype != np.uint8:
69
+ raise ValueError(
70
+ f"Invalid value dtype, expected np.uint8, got {self._value.dtype}"
71
+ )
72
+ if format is None:
73
+ format = "gif"
74
+ if fps is None:
75
+ fps = 24
76
+ self._fps = fps
77
+ self._format = format
78
+
79
+ @staticmethod
80
+ def _check_array_format(video: np.ndarray) -> None:
81
+ """Raise an error if the array is not in the expected format."""
82
+ if not (video.ndim == 4 and video.shape[-1] == 3):
83
+ raise ValueError(
84
+ f"Expected RGB input shaped (F, H, W, 3), got {video.shape}. "
85
+ f"Input has {video.ndim} dimensions, expected 4."
86
+ )
87
+ if video.dtype != np.uint8:
88
+ raise TypeError(
89
+ f"Expected dtype=uint8, got {video.dtype}. "
90
+ "Please convert your video data to uint8 format."
91
+ )
92
+
93
+ @staticmethod
94
+ def write_video(
95
+ file_path: str | Path, video: np.ndarray, fps: float, codec: VideoCodec
96
+ ) -> None:
97
+ """RGB uint8 only, shape (F, H, W, 3)."""
98
+ check_ffmpeg_installed()
99
+ check_path(file_path)
100
+
101
+ if codec not in {"h264", "vp9", "gif"}:
102
+ raise ValueError("Unsupported codec. Use h264, vp9, or gif.")
103
+
104
+ arr = np.asarray(video)
105
+ TrackioVideo._check_array_format(arr)
106
+
107
+ frames = np.ascontiguousarray(arr)
108
+ _, height, width, _ = frames.shape
109
+ out_path = str(file_path)
110
+
111
+ cmd = [
112
+ "ffmpeg",
113
+ "-y",
114
+ "-f",
115
+ "rawvideo",
116
+ "-s",
117
+ f"{width}x{height}",
118
+ "-pix_fmt",
119
+ "rgb24",
120
+ "-r",
121
+ str(fps),
122
+ "-i",
123
+ "-",
124
+ "-an",
125
+ ]
126
+
127
+ if codec == "gif":
128
+ video_filter = "split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse"
129
+ cmd += [
130
+ "-vf",
131
+ video_filter,
132
+ "-loop",
133
+ "0",
134
+ ]
135
+ elif codec == "h264":
136
+ cmd += [
137
+ "-vcodec",
138
+ "libx264",
139
+ "-pix_fmt",
140
+ "yuv420p",
141
+ "-movflags",
142
+ "+faststart",
143
+ ]
144
+ elif codec == "vp9":
145
+ bpp = 0.08
146
+ bps = int(width * height * fps * bpp)
147
+ if bps >= 1_000_000:
148
+ bitrate = f"{round(bps / 1_000_000)}M"
149
+ elif bps >= 1_000:
150
+ bitrate = f"{round(bps / 1_000)}k"
151
+ else:
152
+ bitrate = str(max(bps, 1))
153
+ cmd += [
154
+ "-vcodec",
155
+ "libvpx-vp9",
156
+ "-b:v",
157
+ bitrate,
158
+ "-pix_fmt",
159
+ "yuv420p",
160
+ ]
161
+ cmd += [out_path]
162
+ proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
163
+ try:
164
+ for frame in frames:
165
+ proc.stdin.write(frame.tobytes())
166
+ finally:
167
+ if proc.stdin:
168
+ proc.stdin.close()
169
+ stderr = (
170
+ proc.stderr.read().decode("utf-8", errors="ignore")
171
+ if proc.stderr
172
+ else ""
173
+ )
174
+ ret = proc.wait()
175
+ if ret != 0:
176
+ raise RuntimeError(f"ffmpeg failed with code {ret}\n{stderr}")
177
+
178
+ @property
179
+ def _codec(self) -> str:
180
+ match self._format:
181
+ case "gif":
182
+ return "gif"
183
+ case "mp4":
184
+ return "h264"
185
+ case "webm":
186
+ return "vp9"
187
+ case _:
188
+ raise ValueError(f"Unsupported format: {self._format}")
189
+
190
+ def _save_media(self, file_path: Path):
191
+ if isinstance(self._value, np.ndarray):
192
+ video = TrackioVideo._process_ndarray(self._value)
193
+ TrackioVideo.write_video(file_path, video, fps=self._fps, codec=self._codec)
194
+ elif isinstance(self._value, str | Path):
195
+ if os.path.isfile(self._value):
196
+ shutil.copy(self._value, file_path)
197
+ else:
198
+ raise ValueError(f"File not found: {self._value}")
199
+
200
+ @staticmethod
201
+ def _process_ndarray(value: np.ndarray) -> np.ndarray:
202
+ # Verify value is either 4D (single video) or 5D array (batched videos).
203
+ # Expected format: (frames, channels, height, width) or (batch, frames, channels, height, width)
204
+ if value.ndim < 4:
205
+ raise ValueError(
206
+ "Video requires at least 4 dimensions (frames, channels, height, width)"
207
+ )
208
+ if value.ndim > 5:
209
+ raise ValueError(
210
+ "Videos can have at most 5 dimensions (batch, frames, channels, height, width)"
211
+ )
212
+ if value.ndim == 4:
213
+ # Reshape to 5D with single batch: (1, frames, channels, height, width)
214
+ value = value[np.newaxis, ...]
215
+
216
+ value = TrackioVideo._tile_batched_videos(value)
217
+ return value
218
+
219
+ @staticmethod
220
+ def _tile_batched_videos(video: np.ndarray) -> np.ndarray:
221
+ """
222
+ Tiles a batch of videos into a grid of videos.
223
+
224
+ Input format: (batch, frames, channels, height, width) - original FCHW format
225
+ Output format: (frames, total_height, total_width, channels)
226
+ """
227
+ batch_size, frames, channels, height, width = video.shape
228
+
229
+ next_pow2 = 1 << (batch_size - 1).bit_length()
230
+ if batch_size != next_pow2:
231
+ pad_len = next_pow2 - batch_size
232
+ pad_shape = (pad_len, frames, channels, height, width)
233
+ padding = np.zeros(pad_shape, dtype=video.dtype)
234
+ video = np.concatenate((video, padding), axis=0)
235
+ batch_size = next_pow2
236
+
237
+ n_rows = 1 << ((batch_size.bit_length() - 1) // 2)
238
+ n_cols = batch_size // n_rows
239
+
240
+ # Reshape to grid layout: (n_rows, n_cols, frames, channels, height, width)
241
+ video = video.reshape(n_rows, n_cols, frames, channels, height, width)
242
+
243
+ # Rearrange dimensions to (frames, total_height, total_width, channels)
244
+ video = video.transpose(2, 0, 4, 1, 5, 3)
245
+ video = video.reshape(frames, n_rows * height, n_cols * width, channels)
246
+ return video
trackio/package.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "name": "trackio",
3
+ "version": "0.21.0",
4
+ "description": "",
5
+ "python": "true"
6
+ }
trackio/py.typed ADDED
File without changes
trackio/remote_client.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from gradio_client import Client
4
+
5
+
6
+ class RemoteClient:
7
+ def __init__(self, space: str, hf_token: str | None = None):
8
+ self._space = space
9
+ kwargs: dict = {"verbose": False}
10
+ if hf_token:
11
+ kwargs["hf_token"] = hf_token
12
+ try:
13
+ self._client = Client(space, **kwargs)
14
+ except Exception as e:
15
+ raise ConnectionError(
16
+ f"Could not connect to Space '{space}'. Is it running?\n{e}"
17
+ )
18
+
19
+ def predict(self, *args, api_name: str):
20
+ try:
21
+ return self._client.predict(*args, api_name=api_name)
22
+ except Exception as e:
23
+ if "API Not Found" in str(e) or "api_name" in str(e):
24
+ raise RuntimeError(
25
+ f"Space '{self._space}' does not support '{api_name}'. "
26
+ "Redeploy with `trackio sync`."
27
+ )
28
+ raise
trackio/run.py ADDED
@@ -0,0 +1,739 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import threading
4
+ import uuid
5
+ import warnings
6
+ from datetime import datetime, timezone
7
+ from pathlib import Path
8
+
9
+ import huggingface_hub
10
+ from gradio_client import Client, handle_file
11
+
12
+ from trackio import utils
13
+ from trackio.alerts import (
14
+ AlertLevel,
15
+ format_alert_terminal,
16
+ resolve_webhook_min_level,
17
+ send_webhook,
18
+ should_send_webhook,
19
+ )
20
+ from trackio.apple_gpu import AppleGpuMonitor, apple_gpu_available
21
+ from trackio.gpu import GpuMonitor, gpu_available
22
+ from trackio.histogram import Histogram
23
+ from trackio.markdown import Markdown
24
+ from trackio.media import TrackioMedia, get_project_media_path
25
+ from trackio.sqlite_storage import SQLiteStorage
26
+ from trackio.table import Table
27
+ from trackio.typehints import AlertEntry, LogEntry, SystemLogEntry, UploadEntry
28
+ from trackio.utils import _get_default_namespace
29
+
30
+ BATCH_SEND_INTERVAL = 0.5
31
+ MAX_BACKOFF = 30
32
+
33
+
34
+ class Run:
35
+ def __init__(
36
+ self,
37
+ url: str | None,
38
+ project: str,
39
+ client: Client | None,
40
+ name: str | None = None,
41
+ group: str | None = None,
42
+ config: dict | None = None,
43
+ space_id: str | None = None,
44
+ auto_log_gpu: bool = False,
45
+ gpu_log_interval: float = 10.0,
46
+ webhook_url: str | None = None,
47
+ webhook_min_level: AlertLevel | str | None = None,
48
+ ):
49
+ """
50
+ Initialize a Run for logging metrics to Trackio.
51
+
52
+ Args:
53
+ url: The URL of the Trackio server (local Gradio app or HF Space).
54
+ project: The name of the project to log metrics to.
55
+ client: A pre-configured gradio_client.Client instance, or None to
56
+ create one automatically in a background thread with retry logic.
57
+ Passing None is recommended for normal usage. Passing a client
58
+ is useful for testing (e.g., injecting a mock client).
59
+ name: The name of this run. If None, a readable name like
60
+ "brave-sunset-0" is auto-generated. If space_id is provided,
61
+ generates a "username-timestamp" format instead.
62
+ group: Optional group name to organize related runs together.
63
+ config: A dictionary of configuration/hyperparameters for this run.
64
+ Keys starting with '_' are reserved for internal use.
65
+ space_id: The HF Space ID if logging to a Space (e.g., "user/space").
66
+ If provided, media files will be uploaded to the Space.
67
+ auto_log_gpu: Whether to automatically log GPU metrics (utilization,
68
+ memory, temperature) at regular intervals.
69
+ gpu_log_interval: The interval in seconds between GPU metric logs.
70
+ Only used when auto_log_gpu is True.
71
+ webhook_url: A webhook URL to POST alert payloads to. Supports
72
+ Slack and Discord webhook URLs natively. Can also be set via
73
+ the TRACKIO_WEBHOOK_URL environment variable.
74
+ webhook_min_level: Minimum alert level that should trigger webhook
75
+ delivery. For example, `AlertLevel.WARN` sends only WARN and
76
+ ERROR alerts to webhook destinations. Can also be set via
77
+ `TRACKIO_WEBHOOK_MIN_LEVEL`.
78
+ """
79
+ self.url = url
80
+ self.project = project
81
+ self._client_lock = threading.Lock()
82
+ self._client_thread = None
83
+ self._client = client
84
+ self._space_id = space_id
85
+ self.name = name or utils.generate_readable_name(
86
+ SQLiteStorage.get_runs(project), space_id
87
+ )
88
+ self.group = group
89
+ self.config = utils.to_json_safe(config or {})
90
+
91
+ if isinstance(self.config, dict):
92
+ for key in self.config:
93
+ if key.startswith("_"):
94
+ raise ValueError(
95
+ f"Config key '{key}' is reserved (keys starting with '_' are reserved for internal use)"
96
+ )
97
+
98
+ self.config["_Username"] = self._get_username()
99
+ self.config["_Created"] = datetime.now(timezone.utc).isoformat()
100
+ self.config["_Group"] = self.group
101
+
102
+ self._queued_logs: list[LogEntry] = []
103
+ self._queued_system_logs: list[SystemLogEntry] = []
104
+ self._queued_uploads: list[UploadEntry] = []
105
+ self._queued_alerts: list[AlertEntry] = []
106
+ self._stop_flag = threading.Event()
107
+ self._config_logged = False
108
+ max_step = SQLiteStorage.get_max_step_for_run(self.project, self.name)
109
+ self._next_step = 0 if max_step is None else max_step + 1
110
+ self._has_local_buffer = False
111
+
112
+ self._is_local = space_id is None
113
+ self._webhook_url = webhook_url or os.environ.get("TRACKIO_WEBHOOK_URL")
114
+ self._webhook_min_level = resolve_webhook_min_level(
115
+ webhook_min_level or os.environ.get("TRACKIO_WEBHOOK_MIN_LEVEL")
116
+ )
117
+
118
+ if self._is_local:
119
+ self._local_sender_thread = threading.Thread(
120
+ target=self._local_batch_sender
121
+ )
122
+ self._local_sender_thread.daemon = True
123
+ self._local_sender_thread.start()
124
+ else:
125
+ self._client_thread = threading.Thread(target=self._init_client_background)
126
+ self._client_thread.daemon = True
127
+ self._client_thread.start()
128
+
129
+ self._gpu_monitor: "GpuMonitor | AppleGpuMonitor | None" = None
130
+ if auto_log_gpu:
131
+ if gpu_available():
132
+ self._gpu_monitor = GpuMonitor(self, interval=gpu_log_interval)
133
+ self._gpu_monitor.start()
134
+ elif apple_gpu_available():
135
+ self._gpu_monitor = AppleGpuMonitor(self, interval=gpu_log_interval)
136
+ self._gpu_monitor.start()
137
+
138
+ def _get_username(self) -> str | None:
139
+ try:
140
+ return _get_default_namespace()
141
+ except Exception:
142
+ return None
143
+
144
+ def _local_batch_sender(self):
145
+ while (
146
+ not self._stop_flag.is_set()
147
+ or len(self._queued_logs) > 0
148
+ or len(self._queued_system_logs) > 0
149
+ or len(self._queued_alerts) > 0
150
+ ):
151
+ if not self._stop_flag.is_set():
152
+ self._stop_flag.wait(timeout=BATCH_SEND_INTERVAL)
153
+
154
+ with self._client_lock:
155
+ if self._queued_logs:
156
+ logs_to_send = self._queued_logs.copy()
157
+ self._queued_logs.clear()
158
+ self._write_logs_to_sqlite(logs_to_send)
159
+
160
+ if self._queued_system_logs:
161
+ system_logs_to_send = self._queued_system_logs.copy()
162
+ self._queued_system_logs.clear()
163
+ self._write_system_logs_to_sqlite(system_logs_to_send)
164
+
165
+ if self._queued_alerts:
166
+ alerts_to_send = self._queued_alerts.copy()
167
+ self._queued_alerts.clear()
168
+ self._write_alerts_to_sqlite(alerts_to_send)
169
+
170
+ def _write_logs_to_sqlite(self, logs: list[LogEntry]):
171
+ logs_by_run: dict[tuple, dict] = {}
172
+ for entry in logs:
173
+ key = (entry["project"], entry["run"])
174
+ if key not in logs_by_run:
175
+ logs_by_run[key] = {
176
+ "metrics": [],
177
+ "steps": [],
178
+ "log_ids": [],
179
+ "config": None,
180
+ }
181
+ logs_by_run[key]["metrics"].append(entry["metrics"])
182
+ logs_by_run[key]["steps"].append(entry.get("step"))
183
+ logs_by_run[key]["log_ids"].append(entry.get("log_id"))
184
+ if entry.get("config") and logs_by_run[key]["config"] is None:
185
+ logs_by_run[key]["config"] = entry["config"]
186
+
187
+ for (project, run), data in logs_by_run.items():
188
+ has_log_ids = any(lid is not None for lid in data["log_ids"])
189
+ SQLiteStorage.bulk_log(
190
+ project=project,
191
+ run=run,
192
+ metrics_list=data["metrics"],
193
+ steps=data["steps"],
194
+ config=data["config"],
195
+ log_ids=data["log_ids"] if has_log_ids else None,
196
+ )
197
+
198
+ def _write_system_logs_to_sqlite(self, logs: list[SystemLogEntry]):
199
+ logs_by_run: dict[tuple, dict] = {}
200
+ for entry in logs:
201
+ key = (entry["project"], entry["run"])
202
+ if key not in logs_by_run:
203
+ logs_by_run[key] = {"metrics": [], "timestamps": [], "log_ids": []}
204
+ logs_by_run[key]["metrics"].append(entry["metrics"])
205
+ logs_by_run[key]["timestamps"].append(entry.get("timestamp"))
206
+ logs_by_run[key]["log_ids"].append(entry.get("log_id"))
207
+
208
+ for (project, run), data in logs_by_run.items():
209
+ has_log_ids = any(lid is not None for lid in data["log_ids"])
210
+ SQLiteStorage.bulk_log_system(
211
+ project=project,
212
+ run=run,
213
+ metrics_list=data["metrics"],
214
+ timestamps=data["timestamps"],
215
+ log_ids=data["log_ids"] if has_log_ids else None,
216
+ )
217
+
218
+ def _write_alerts_to_sqlite(self, alerts: list[AlertEntry]):
219
+ alerts_by_run: dict[tuple, dict] = {}
220
+ for entry in alerts:
221
+ key = (entry["project"], entry["run"])
222
+ if key not in alerts_by_run:
223
+ alerts_by_run[key] = {
224
+ "titles": [],
225
+ "texts": [],
226
+ "levels": [],
227
+ "steps": [],
228
+ "timestamps": [],
229
+ "alert_ids": [],
230
+ }
231
+ alerts_by_run[key]["titles"].append(entry["title"])
232
+ alerts_by_run[key]["texts"].append(entry.get("text"))
233
+ alerts_by_run[key]["levels"].append(entry["level"])
234
+ alerts_by_run[key]["steps"].append(entry.get("step"))
235
+ alerts_by_run[key]["timestamps"].append(entry.get("timestamp"))
236
+ alerts_by_run[key]["alert_ids"].append(entry.get("alert_id"))
237
+
238
+ for (project, run), data in alerts_by_run.items():
239
+ has_alert_ids = any(aid is not None for aid in data["alert_ids"])
240
+ SQLiteStorage.bulk_alert(
241
+ project=project,
242
+ run=run,
243
+ titles=data["titles"],
244
+ texts=data["texts"],
245
+ levels=data["levels"],
246
+ steps=data["steps"],
247
+ timestamps=data["timestamps"],
248
+ alert_ids=data["alert_ids"] if has_alert_ids else None,
249
+ )
250
+
251
+ def _batch_sender(self):
252
+ consecutive_failures = 0
253
+ while (
254
+ not self._stop_flag.is_set()
255
+ or len(self._queued_logs) > 0
256
+ or len(self._queued_system_logs) > 0
257
+ or len(self._queued_uploads) > 0
258
+ or len(self._queued_alerts) > 0
259
+ or self._has_local_buffer
260
+ ):
261
+ if not self._stop_flag.is_set():
262
+ if consecutive_failures:
263
+ sleep_time = min(
264
+ BATCH_SEND_INTERVAL * (2**consecutive_failures), MAX_BACKOFF
265
+ )
266
+ else:
267
+ sleep_time = BATCH_SEND_INTERVAL
268
+ self._stop_flag.wait(timeout=sleep_time)
269
+ elif self._has_local_buffer:
270
+ self._stop_flag.wait(timeout=BATCH_SEND_INTERVAL)
271
+
272
+ with self._client_lock:
273
+ if self._client is None:
274
+ if self._stop_flag.is_set():
275
+ if self._queued_logs:
276
+ self._persist_logs_locally(self._queued_logs)
277
+ self._queued_logs.clear()
278
+ if self._queued_system_logs:
279
+ self._persist_system_logs_locally(self._queued_system_logs)
280
+ self._queued_system_logs.clear()
281
+ if self._queued_uploads:
282
+ self._persist_uploads_locally(self._queued_uploads)
283
+ self._queued_uploads.clear()
284
+ if self._queued_alerts:
285
+ self._write_alerts_to_sqlite(self._queued_alerts)
286
+ self._queued_alerts.clear()
287
+ return
288
+
289
+ failed = False
290
+
291
+ if self._queued_logs:
292
+ logs_to_send = self._queued_logs.copy()
293
+ self._queued_logs.clear()
294
+ try:
295
+ self._client.predict(
296
+ api_name="/bulk_log",
297
+ logs=logs_to_send,
298
+ hf_token=huggingface_hub.utils.get_token(),
299
+ )
300
+ except Exception:
301
+ self._persist_logs_locally(logs_to_send)
302
+ failed = True
303
+
304
+ if self._queued_system_logs:
305
+ system_logs_to_send = self._queued_system_logs.copy()
306
+ self._queued_system_logs.clear()
307
+ try:
308
+ self._client.predict(
309
+ api_name="/bulk_log_system",
310
+ logs=system_logs_to_send,
311
+ hf_token=huggingface_hub.utils.get_token(),
312
+ )
313
+ except Exception:
314
+ self._persist_system_logs_locally(system_logs_to_send)
315
+ failed = True
316
+
317
+ if self._queued_uploads:
318
+ uploads_to_send = self._queued_uploads.copy()
319
+ self._queued_uploads.clear()
320
+ try:
321
+ self._client.predict(
322
+ api_name="/bulk_upload_media",
323
+ uploads=uploads_to_send,
324
+ hf_token=huggingface_hub.utils.get_token(),
325
+ )
326
+ except Exception:
327
+ self._persist_uploads_locally(uploads_to_send)
328
+ failed = True
329
+
330
+ if self._queued_alerts:
331
+ alerts_to_send = self._queued_alerts.copy()
332
+ self._queued_alerts.clear()
333
+ try:
334
+ self._client.predict(
335
+ api_name="/bulk_alert",
336
+ alerts=alerts_to_send,
337
+ hf_token=huggingface_hub.utils.get_token(),
338
+ )
339
+ except Exception:
340
+ self._write_alerts_to_sqlite(alerts_to_send)
341
+ failed = True
342
+
343
+ if failed:
344
+ consecutive_failures += 1
345
+ else:
346
+ consecutive_failures = 0
347
+ if self._has_local_buffer:
348
+ self._flush_local_buffer()
349
+
350
+ def _persist_logs_locally(self, logs: list[LogEntry]):
351
+ if not self._space_id:
352
+ return
353
+ logs_by_run: dict[tuple, dict] = {}
354
+ for entry in logs:
355
+ key = (entry["project"], entry["run"])
356
+ if key not in logs_by_run:
357
+ logs_by_run[key] = {
358
+ "metrics": [],
359
+ "steps": [],
360
+ "log_ids": [],
361
+ "config": None,
362
+ }
363
+ logs_by_run[key]["metrics"].append(entry["metrics"])
364
+ logs_by_run[key]["steps"].append(entry.get("step"))
365
+ logs_by_run[key]["log_ids"].append(entry.get("log_id"))
366
+ if entry.get("config") and logs_by_run[key]["config"] is None:
367
+ logs_by_run[key]["config"] = entry["config"]
368
+
369
+ for (project, run), data in logs_by_run.items():
370
+ SQLiteStorage.bulk_log(
371
+ project=project,
372
+ run=run,
373
+ metrics_list=data["metrics"],
374
+ steps=data["steps"],
375
+ log_ids=data["log_ids"],
376
+ config=data["config"],
377
+ space_id=self._space_id,
378
+ )
379
+ self._has_local_buffer = True
380
+
381
+ def _persist_system_logs_locally(self, logs: list[SystemLogEntry]):
382
+ if not self._space_id:
383
+ return
384
+ logs_by_run: dict[tuple, dict] = {}
385
+ for entry in logs:
386
+ key = (entry["project"], entry["run"])
387
+ if key not in logs_by_run:
388
+ logs_by_run[key] = {"metrics": [], "timestamps": [], "log_ids": []}
389
+ logs_by_run[key]["metrics"].append(entry["metrics"])
390
+ logs_by_run[key]["timestamps"].append(entry.get("timestamp"))
391
+ logs_by_run[key]["log_ids"].append(entry.get("log_id"))
392
+
393
+ for (project, run), data in logs_by_run.items():
394
+ SQLiteStorage.bulk_log_system(
395
+ project=project,
396
+ run=run,
397
+ metrics_list=data["metrics"],
398
+ timestamps=data["timestamps"],
399
+ log_ids=data["log_ids"],
400
+ space_id=self._space_id,
401
+ )
402
+ self._has_local_buffer = True
403
+
404
+ def _persist_uploads_locally(self, uploads: list[UploadEntry]):
405
+ if not self._space_id:
406
+ return
407
+ for entry in uploads:
408
+ file_data = entry.get("uploaded_file")
409
+ file_path = ""
410
+ if isinstance(file_data, dict):
411
+ file_path = file_data.get("path", "")
412
+ elif hasattr(file_data, "path"):
413
+ file_path = str(file_data.path)
414
+ else:
415
+ file_path = str(file_data)
416
+ SQLiteStorage.add_pending_upload(
417
+ project=entry["project"],
418
+ space_id=self._space_id,
419
+ run_name=entry.get("run"),
420
+ step=entry.get("step"),
421
+ file_path=file_path,
422
+ relative_path=entry.get("relative_path"),
423
+ )
424
+ self._has_local_buffer = True
425
+
426
+ def _flush_local_buffer(self):
427
+ try:
428
+ buffered_logs = SQLiteStorage.get_pending_logs(self.project)
429
+ if buffered_logs:
430
+ self._client.predict(
431
+ api_name="/bulk_log",
432
+ logs=buffered_logs["logs"],
433
+ hf_token=huggingface_hub.utils.get_token(),
434
+ )
435
+ SQLiteStorage.clear_pending_logs(self.project, buffered_logs["ids"])
436
+
437
+ buffered_sys = SQLiteStorage.get_pending_system_logs(self.project)
438
+ if buffered_sys:
439
+ self._client.predict(
440
+ api_name="/bulk_log_system",
441
+ logs=buffered_sys["logs"],
442
+ hf_token=huggingface_hub.utils.get_token(),
443
+ )
444
+ SQLiteStorage.clear_pending_system_logs(
445
+ self.project, buffered_sys["ids"]
446
+ )
447
+
448
+ buffered_uploads = SQLiteStorage.get_pending_uploads(self.project)
449
+ if buffered_uploads:
450
+ upload_entries = []
451
+ for u in buffered_uploads["uploads"]:
452
+ fp = u["file_path"]
453
+ if Path(fp).exists():
454
+ upload_entries.append(
455
+ {
456
+ "project": u["project"],
457
+ "run": u["run"],
458
+ "step": u["step"],
459
+ "relative_path": u["relative_path"],
460
+ "uploaded_file": handle_file(fp),
461
+ }
462
+ )
463
+ if upload_entries:
464
+ self._client.predict(
465
+ api_name="/bulk_upload_media",
466
+ uploads=upload_entries,
467
+ hf_token=huggingface_hub.utils.get_token(),
468
+ )
469
+ SQLiteStorage.clear_pending_uploads(
470
+ self.project, buffered_uploads["ids"]
471
+ )
472
+
473
+ self._has_local_buffer = False
474
+ except Exception:
475
+ pass
476
+
477
+ def _init_client_background(self):
478
+ if self._client is None:
479
+ fib = utils.fibo()
480
+ for sleep_coefficient in fib:
481
+ if self._stop_flag.is_set():
482
+ break
483
+ try:
484
+ client = Client(self.url, verbose=False)
485
+
486
+ with self._client_lock:
487
+ self._client = client
488
+ break
489
+ except Exception:
490
+ pass
491
+ sleep_time = min(0.1 * sleep_coefficient, MAX_BACKOFF)
492
+ self._stop_flag.wait(timeout=sleep_time)
493
+
494
+ self._batch_sender()
495
+
496
+ def _queue_upload(
497
+ self,
498
+ file_path,
499
+ step: int | None,
500
+ relative_path: str | None = None,
501
+ use_run_name: bool = True,
502
+ ):
503
+ if self._is_local:
504
+ self._save_upload_locally(file_path, step, relative_path, use_run_name)
505
+ else:
506
+ upload_entry: UploadEntry = {
507
+ "project": self.project,
508
+ "run": self.name if use_run_name else None,
509
+ "step": step,
510
+ "relative_path": relative_path,
511
+ "uploaded_file": handle_file(file_path),
512
+ }
513
+ with self._client_lock:
514
+ self._queued_uploads.append(upload_entry)
515
+
516
+ def _save_upload_locally(
517
+ self,
518
+ file_path,
519
+ step: int | None,
520
+ relative_path: str | None = None,
521
+ use_run_name: bool = True,
522
+ ):
523
+ media_path = get_project_media_path(
524
+ project=self.project,
525
+ run=self.name if use_run_name else None,
526
+ step=step,
527
+ relative_path=relative_path,
528
+ )
529
+ src = Path(file_path)
530
+ if src.exists() and str(src.resolve()) != str(Path(media_path).resolve()):
531
+ shutil.copy(str(src), str(media_path))
532
+
533
+ def _process_media(self, value: TrackioMedia, step: int | None) -> dict:
534
+ value._save(self.project, self.name, step if step is not None else 0)
535
+ if self._space_id:
536
+ self._queue_upload(value._get_absolute_file_path(), step)
537
+ return value._to_dict()
538
+
539
+ def _scan_and_queue_media_uploads(self, table_dict: dict, step: int | None):
540
+ if not self._space_id:
541
+ return
542
+
543
+ table_data = table_dict.get("_value", [])
544
+ for row in table_data:
545
+ for value in row.values():
546
+ if isinstance(value, dict) and value.get("_type") in [
547
+ "trackio.image",
548
+ "trackio.video",
549
+ "trackio.audio",
550
+ ]:
551
+ file_path = value.get("file_path")
552
+ if file_path:
553
+ from trackio.utils import MEDIA_DIR
554
+
555
+ absolute_path = MEDIA_DIR / file_path
556
+ self._queue_upload(absolute_path, step)
557
+ elif isinstance(value, list):
558
+ for item in value:
559
+ if isinstance(item, dict) and item.get("_type") in [
560
+ "trackio.image",
561
+ "trackio.video",
562
+ "trackio.audio",
563
+ ]:
564
+ file_path = item.get("file_path")
565
+ if file_path:
566
+ from trackio.utils import MEDIA_DIR
567
+
568
+ absolute_path = MEDIA_DIR / file_path
569
+ self._queue_upload(absolute_path, step)
570
+
571
+ def _ensure_sender_alive(self):
572
+ if self._is_local:
573
+ if (
574
+ hasattr(self, "_local_sender_thread")
575
+ and not self._local_sender_thread.is_alive()
576
+ and not self._stop_flag.is_set()
577
+ ):
578
+ self._local_sender_thread = threading.Thread(
579
+ target=self._local_batch_sender
580
+ )
581
+ self._local_sender_thread.daemon = True
582
+ self._local_sender_thread.start()
583
+ else:
584
+ if (
585
+ self._client_thread is not None
586
+ and not self._client_thread.is_alive()
587
+ and not self._stop_flag.is_set()
588
+ ):
589
+ self._client_thread = threading.Thread(
590
+ target=self._init_client_background
591
+ )
592
+ self._client_thread.daemon = True
593
+ self._client_thread.start()
594
+
595
+ def log(self, metrics: dict, step: int | None = None):
596
+ renamed_keys = []
597
+ new_metrics = {}
598
+
599
+ for k, v in metrics.items():
600
+ if k in utils.RESERVED_KEYS or k.startswith("__"):
601
+ new_key = f"__{k}"
602
+ renamed_keys.append(k)
603
+ new_metrics[new_key] = v
604
+ else:
605
+ new_metrics[k] = v
606
+
607
+ if renamed_keys:
608
+ warnings.warn(f"Reserved keys renamed: {renamed_keys} → '__{{key}}'")
609
+
610
+ metrics = new_metrics
611
+ for key, value in metrics.items():
612
+ if isinstance(value, Table):
613
+ metrics[key] = value._to_dict(
614
+ project=self.project, run=self.name, step=step
615
+ )
616
+ self._scan_and_queue_media_uploads(metrics[key], step)
617
+ elif isinstance(value, Histogram):
618
+ metrics[key] = value._to_dict()
619
+ elif isinstance(value, Markdown):
620
+ metrics[key] = value._to_dict()
621
+ elif isinstance(value, TrackioMedia):
622
+ metrics[key] = self._process_media(value, step)
623
+ metrics = utils.serialize_values(metrics)
624
+
625
+ if step is None:
626
+ step = self._next_step
627
+ self._next_step = max(self._next_step, step + 1)
628
+
629
+ config_to_log = None
630
+ if not self._config_logged and self.config:
631
+ config_to_log = utils.to_json_safe(self.config)
632
+ self._config_logged = True
633
+
634
+ log_entry: LogEntry = {
635
+ "project": self.project,
636
+ "run": self.name,
637
+ "metrics": metrics,
638
+ "step": step,
639
+ "config": config_to_log,
640
+ "log_id": uuid.uuid4().hex,
641
+ }
642
+
643
+ with self._client_lock:
644
+ self._queued_logs.append(log_entry)
645
+ self._ensure_sender_alive()
646
+
647
+ def alert(
648
+ self,
649
+ title: str,
650
+ text: str | None = None,
651
+ level: AlertLevel = AlertLevel.WARN,
652
+ step: int | None = None,
653
+ webhook_url: str | None = None,
654
+ ):
655
+ if step is None:
656
+ step = max(self._next_step - 1, 0)
657
+ timestamp = datetime.now(timezone.utc).isoformat()
658
+
659
+ print(format_alert_terminal(level, title, text, step))
660
+
661
+ alert_entry: AlertEntry = {
662
+ "project": self.project,
663
+ "run": self.name,
664
+ "title": title,
665
+ "text": text,
666
+ "level": level.value,
667
+ "step": step,
668
+ "timestamp": timestamp,
669
+ "alert_id": uuid.uuid4().hex,
670
+ }
671
+
672
+ with self._client_lock:
673
+ self._queued_alerts.append(alert_entry)
674
+ self._ensure_sender_alive()
675
+
676
+ url = webhook_url or self._webhook_url
677
+ if url and should_send_webhook(level, self._webhook_min_level):
678
+ t = threading.Thread(
679
+ target=send_webhook,
680
+ args=(
681
+ url,
682
+ level,
683
+ title,
684
+ text,
685
+ self.project,
686
+ self.name,
687
+ step,
688
+ timestamp,
689
+ ),
690
+ daemon=True,
691
+ )
692
+ t.start()
693
+
694
+ def log_system(self, metrics: dict):
695
+ metrics = utils.serialize_values(metrics)
696
+ timestamp = datetime.now(timezone.utc).isoformat()
697
+
698
+ system_log_entry: SystemLogEntry = {
699
+ "project": self.project,
700
+ "run": self.name,
701
+ "metrics": metrics,
702
+ "timestamp": timestamp,
703
+ "log_id": uuid.uuid4().hex,
704
+ }
705
+
706
+ with self._client_lock:
707
+ self._queued_system_logs.append(system_log_entry)
708
+ self._ensure_sender_alive()
709
+
710
+ def finish(self):
711
+ if self._gpu_monitor is not None:
712
+ self._gpu_monitor.stop()
713
+
714
+ self._stop_flag.set()
715
+
716
+ if self._is_local:
717
+ if hasattr(self, "_local_sender_thread"):
718
+ print("* Run finished. Uploading logs to Trackio (please wait...)")
719
+ self._local_sender_thread.join(timeout=30)
720
+ if self._local_sender_thread.is_alive():
721
+ warnings.warn(
722
+ "Could not flush all logs within 30s. Some data may be buffered locally."
723
+ )
724
+ else:
725
+ if self._client_thread is not None:
726
+ print(
727
+ "* Run finished. Uploading logs to Trackio Space (please wait...)"
728
+ )
729
+ self._client_thread.join(timeout=30)
730
+ if self._client_thread.is_alive():
731
+ warnings.warn(
732
+ "Could not flush all logs within 30s. Some data may be buffered locally."
733
+ )
734
+ if SQLiteStorage.has_pending_data(self.project):
735
+ warnings.warn(
736
+ f"* Some logs could not be sent to the Space (it may still be starting up). "
737
+ f"They have been saved locally and will be sent automatically next time you call: "
738
+ f'trackio.init(project="{self.project}", space_id="{self._space_id}")'
739
+ )
trackio/server.py ADDED
@@ -0,0 +1,729 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The main API layer for the Trackio UI."""
2
+
3
+ import base64
4
+ import logging
5
+ import os
6
+ import re
7
+ import secrets
8
+ import shutil
9
+ import sqlite3
10
+ import threading
11
+ import time
12
+ from collections import deque
13
+ from functools import lru_cache
14
+ from typing import Any
15
+ from urllib.parse import urlencode
16
+
17
+ import gradio as gr
18
+ import httpx
19
+ import huggingface_hub as hf
20
+ from starlette.requests import Request
21
+ from starlette.responses import RedirectResponse
22
+
23
+ import trackio.utils as utils
24
+ from trackio.media import get_project_media_path
25
+ from trackio.sqlite_storage import SQLiteStorage
26
+ from trackio.typehints import AlertEntry, LogEntry, SystemLogEntry, UploadEntry
27
+
28
+ HfApi = hf.HfApi()
29
+
30
+ logger = logging.getLogger("trackio")
31
+
32
+ _write_queue: deque[tuple[str, Any]] = deque()
33
+ _flush_thread: threading.Thread | None = None
34
+ _flush_lock = threading.Lock()
35
+ _FLUSH_INTERVAL = 2.0
36
+ _MAX_RETRIES = 30
37
+
38
+
39
+ def _enqueue_write(kind: str, payload: Any) -> None:
40
+ _write_queue.append((kind, payload))
41
+ _ensure_flush_thread()
42
+
43
+
44
+ def _ensure_flush_thread() -> None:
45
+ global _flush_thread
46
+ with _flush_lock:
47
+ if _flush_thread is not None and _flush_thread.is_alive():
48
+ return
49
+ _flush_thread = threading.Thread(target=_flush_loop, daemon=True)
50
+ _flush_thread.start()
51
+
52
+
53
+ def _flush_loop() -> None:
54
+ retries = 0
55
+ while _write_queue and retries < _MAX_RETRIES:
56
+ kind, payload = _write_queue[0]
57
+ try:
58
+ if kind == "bulk_log":
59
+ SQLiteStorage.bulk_log(**payload)
60
+ elif kind == "bulk_log_system":
61
+ SQLiteStorage.bulk_log_system(**payload)
62
+ elif kind == "bulk_alert":
63
+ SQLiteStorage.bulk_alert(**payload)
64
+ _write_queue.popleft()
65
+ retries = 0
66
+ except sqlite3.OperationalError as e:
67
+ msg = str(e).lower()
68
+ if "disk i/o error" in msg or "readonly" in msg:
69
+ retries += 1
70
+ logger.warning(
71
+ "write queue: flush failed (%s), retry %d/%d",
72
+ e,
73
+ retries,
74
+ _MAX_RETRIES,
75
+ )
76
+ time.sleep(min(_FLUSH_INTERVAL * retries, 15.0))
77
+ else:
78
+ logger.error("write queue: non-retryable error (%s), dropping entry", e)
79
+ _write_queue.popleft()
80
+ retries = 0
81
+ if _write_queue:
82
+ logger.error(
83
+ "write queue: giving up after %d retries, %d entries dropped",
84
+ _MAX_RETRIES,
85
+ len(_write_queue),
86
+ )
87
+ _write_queue.clear()
88
+
89
+
90
+ write_token = secrets.token_urlsafe(32)
91
+
92
+ OAUTH_CALLBACK_PATH = "/login/callback"
93
+ OAUTH_START_PATH = "/oauth/hf/start"
94
+
95
+
96
+ def _hf_access_token(request: gr.Request) -> str | None:
97
+ session_id = None
98
+ try:
99
+ session_id = request.headers.get("x-trackio-oauth-session")
100
+ except (AttributeError, TypeError):
101
+ pass
102
+ if session_id and session_id in _oauth_sessions:
103
+ token, created = _oauth_sessions[session_id]
104
+ if time.monotonic() - created <= _OAUTH_SESSION_TTL:
105
+ return token
106
+ del _oauth_sessions[session_id]
107
+ cookie_header = ""
108
+ try:
109
+ cookie_header = request.headers.get("cookie", "")
110
+ except (AttributeError, TypeError):
111
+ pass
112
+ if cookie_header:
113
+ for cookie in cookie_header.split(";"):
114
+ parts = cookie.strip().split("=", 1)
115
+ if len(parts) == 2 and parts[0] == "trackio_hf_access_token":
116
+ return parts[1] or None
117
+ return None
118
+
119
+
120
+ def _oauth_redirect_uri(request: Request) -> str:
121
+ space_host = os.getenv("SPACE_HOST")
122
+ if space_host:
123
+ space_host = space_host.split(",")[0]
124
+ return f"https://{space_host}{OAUTH_CALLBACK_PATH}"
125
+ return str(request.base_url).rstrip("/") + OAUTH_CALLBACK_PATH
126
+
127
+
128
+ class TrackioServer(gr.Server):
129
+ def close(self, verbose: bool = True) -> None:
130
+ if self.blocks is None:
131
+ return
132
+ if self.blocks.is_running:
133
+ self.blocks.close(verbose=verbose)
134
+
135
+
136
+ _OAUTH_STATE_TTL = 86400
137
+ _OAUTH_SESSION_TTL = 86400 * 30
138
+ _pending_oauth_states: dict[str, float] = {}
139
+ _oauth_sessions: dict[str, tuple[str, float]] = {}
140
+
141
+
142
+ def _evict_expired_oauth():
143
+ now = time.monotonic()
144
+ expired_states = [
145
+ k for k, t in _pending_oauth_states.items() if now - t > _OAUTH_STATE_TTL
146
+ ]
147
+ for k in expired_states:
148
+ del _pending_oauth_states[k]
149
+ expired_sessions = [
150
+ k for k, (_, t) in _oauth_sessions.items() if now - t > _OAUTH_SESSION_TTL
151
+ ]
152
+ for k in expired_sessions:
153
+ del _oauth_sessions[k]
154
+
155
+
156
+ def oauth_hf_start(request: Request):
157
+ client_id = os.getenv("OAUTH_CLIENT_ID")
158
+ if not client_id:
159
+ return RedirectResponse(url="/", status_code=302)
160
+ _evict_expired_oauth()
161
+ state = secrets.token_urlsafe(32)
162
+ _pending_oauth_states[state] = time.monotonic()
163
+ redirect_uri = _oauth_redirect_uri(request)
164
+ scope = os.getenv("OAUTH_SCOPES", "openid profile").strip()
165
+ url = "https://huggingface.co/oauth/authorize?" + urlencode(
166
+ {
167
+ "client_id": client_id,
168
+ "redirect_uri": redirect_uri,
169
+ "response_type": "code",
170
+ "scope": scope,
171
+ "state": state,
172
+ }
173
+ )
174
+ return RedirectResponse(url=url, status_code=302)
175
+
176
+
177
+ def oauth_hf_callback(request: Request):
178
+ client_id = os.getenv("OAUTH_CLIENT_ID")
179
+ client_secret = os.getenv("OAUTH_CLIENT_SECRET")
180
+ err = "/?oauth_error=1"
181
+ if not client_id or not client_secret:
182
+ return RedirectResponse(url=err, status_code=302)
183
+ got_state = request.query_params.get("state")
184
+ code = request.query_params.get("code")
185
+ if not got_state or got_state not in _pending_oauth_states or not code:
186
+ return RedirectResponse(url=err, status_code=302)
187
+ state_created = _pending_oauth_states.pop(got_state)
188
+ if time.monotonic() - state_created > _OAUTH_STATE_TTL:
189
+ return RedirectResponse(url=err, status_code=302)
190
+ redirect_uri = _oauth_redirect_uri(request)
191
+ auth_b64 = base64.b64encode(f"{client_id}:{client_secret}".encode()).decode()
192
+ try:
193
+ with httpx.Client() as client:
194
+ token_resp = client.post(
195
+ "https://huggingface.co/oauth/token",
196
+ headers={"Authorization": f"Basic {auth_b64}"},
197
+ data={
198
+ "grant_type": "authorization_code",
199
+ "code": code,
200
+ "redirect_uri": redirect_uri,
201
+ "client_id": client_id,
202
+ },
203
+ )
204
+ token_resp.raise_for_status()
205
+ access_token = token_resp.json()["access_token"]
206
+ except Exception:
207
+ return RedirectResponse(url=err, status_code=302)
208
+ session_id = secrets.token_urlsafe(32)
209
+ _oauth_sessions[session_id] = (access_token, time.monotonic())
210
+ on_spaces = os.getenv("SYSTEM") == "spaces"
211
+ resp = RedirectResponse(url=f"/?oauth_session={session_id}", status_code=302)
212
+ resp.set_cookie(
213
+ key="trackio_hf_access_token",
214
+ value=access_token,
215
+ httponly=True,
216
+ samesite="none" if on_spaces else "lax",
217
+ max_age=86400 * 30,
218
+ path="/",
219
+ secure=on_spaces,
220
+ )
221
+ return resp
222
+
223
+
224
+ def oauth_logout(request: Request):
225
+ on_spaces = os.getenv("SYSTEM") == "spaces"
226
+ resp = RedirectResponse(url="/", status_code=302)
227
+ resp.delete_cookie(
228
+ "trackio_hf_access_token",
229
+ path="/",
230
+ samesite="none" if on_spaces else "lax",
231
+ secure=on_spaces,
232
+ )
233
+ return resp
234
+
235
+
236
+ @lru_cache(maxsize=32)
237
+ def check_hf_token_has_write_access(hf_token: str | None) -> None:
238
+ if os.getenv("SYSTEM") == "spaces":
239
+ if hf_token is None:
240
+ raise PermissionError(
241
+ "Expected a HF_TOKEN to be provided when logging to a Space"
242
+ )
243
+ who = HfApi.whoami(hf_token)
244
+ owner_name = os.getenv("SPACE_AUTHOR_NAME")
245
+ repo_name = os.getenv("SPACE_REPO_NAME")
246
+ orgs = [o["name"] for o in who["orgs"]]
247
+ if owner_name != who["name"] and owner_name not in orgs:
248
+ raise PermissionError(
249
+ "Expected the provided hf_token to be the user owner of the space, or be a member of the org owner of the space"
250
+ )
251
+ access_token = who["auth"]["accessToken"]
252
+ if access_token["role"] == "fineGrained":
253
+ matched = False
254
+ for item in access_token["fineGrained"]["scoped"]:
255
+ if (
256
+ item["entity"]["type"] == "space"
257
+ and item["entity"]["name"] == f"{owner_name}/{repo_name}"
258
+ and "repo.write" in item["permissions"]
259
+ ):
260
+ matched = True
261
+ break
262
+ if (
263
+ (
264
+ item["entity"]["type"] == "user"
265
+ or item["entity"]["type"] == "org"
266
+ )
267
+ and item["entity"]["name"] == owner_name
268
+ and "repo.write" in item["permissions"]
269
+ ):
270
+ matched = True
271
+ break
272
+ if not matched:
273
+ raise PermissionError(
274
+ "Expected the provided hf_token with fine grained permissions to provide write access to the space"
275
+ )
276
+ elif access_token["role"] != "write":
277
+ raise PermissionError(
278
+ "Expected the provided hf_token to provide write permissions"
279
+ )
280
+
281
+
282
+ _oauth_write_cache: dict[str, tuple[bool, float]] = {}
283
+ _OAUTH_WRITE_CACHE_TTL = 300
284
+
285
+
286
+ def check_oauth_token_has_write_access(oauth_token: str | None) -> None:
287
+ if not os.getenv("SYSTEM") == "spaces":
288
+ return
289
+ if oauth_token is None:
290
+ raise PermissionError(
291
+ "Expected an oauth to be provided when logging to a Space"
292
+ )
293
+ now = time.monotonic()
294
+ cached = _oauth_write_cache.get(oauth_token)
295
+ if cached is not None:
296
+ allowed, ts = cached
297
+ if now - ts < _OAUTH_WRITE_CACHE_TTL:
298
+ if not allowed:
299
+ raise PermissionError(
300
+ "Expected the oauth token to be the user owner of the space, or be a member of the org owner of the space"
301
+ )
302
+ return
303
+ who = HfApi.whoami(oauth_token)
304
+ user_name = who["name"]
305
+ owner_name = os.getenv("SPACE_AUTHOR_NAME")
306
+ if user_name == owner_name:
307
+ _oauth_write_cache[oauth_token] = (True, now)
308
+ return
309
+ for org in who["orgs"]:
310
+ if org["name"] == owner_name and org["roleInOrg"] == "write":
311
+ _oauth_write_cache[oauth_token] = (True, now)
312
+ return
313
+ _oauth_write_cache[oauth_token] = (False, now)
314
+ raise PermissionError(
315
+ "Expected the oauth token to be the user owner of the space, or be a member of the org owner of the space"
316
+ )
317
+
318
+
319
+ def check_write_access(request: gr.Request, token: str) -> bool:
320
+ cookies = request.headers.get("cookie", "")
321
+ if cookies:
322
+ for cookie in cookies.split(";"):
323
+ parts = cookie.strip().split("=", 1)
324
+ if len(parts) == 2 and parts[0] == "trackio_write_token":
325
+ return parts[1] == token
326
+ if hasattr(request, "query_params") and request.query_params:
327
+ qp = request.query_params.get("write_token")
328
+ return qp == token
329
+ return False
330
+
331
+
332
+ def assert_can_mutate_runs(request: gr.Request) -> None:
333
+ if os.getenv("SYSTEM") != "spaces":
334
+ if check_write_access(request, write_token):
335
+ return
336
+ raise gr.Error(
337
+ "A write_token is required to delete or rename runs. "
338
+ "Open the dashboard using the link that includes the write_token query parameter."
339
+ )
340
+ hf_tok = _hf_access_token(request)
341
+ if hf_tok is not None:
342
+ try:
343
+ check_oauth_token_has_write_access(hf_tok)
344
+ except PermissionError as e:
345
+ raise gr.Error(str(e)) from e
346
+ return
347
+ if check_write_access(request, write_token):
348
+ return
349
+ raise gr.Error(
350
+ "Sign in with Hugging Face to delete or rename runs. You need write access to this Space, "
351
+ "or open the dashboard using a link that includes the write_token query parameter."
352
+ )
353
+
354
+
355
+ def get_run_mutation_status(request: gr.Request) -> dict[str, Any]:
356
+ if os.getenv("SYSTEM") != "spaces":
357
+ if check_write_access(request, write_token):
358
+ return {"spaces": False, "allowed": True, "auth": "local"}
359
+ return {"spaces": False, "allowed": False, "auth": "none"}
360
+ hf_tok = _hf_access_token(request)
361
+ if hf_tok is not None:
362
+ try:
363
+ check_oauth_token_has_write_access(hf_tok)
364
+ return {"spaces": True, "allowed": True, "auth": "oauth"}
365
+ except PermissionError:
366
+ return {"spaces": True, "allowed": False, "auth": "oauth_insufficient"}
367
+ if check_write_access(request, write_token):
368
+ return {"spaces": True, "allowed": True, "auth": "write_token"}
369
+ return {"spaces": True, "allowed": False, "auth": "none"}
370
+
371
+
372
+ def upload_db_to_space(
373
+ project: str, uploaded_db: gr.FileData, hf_token: str | None
374
+ ) -> None:
375
+ check_hf_token_has_write_access(hf_token)
376
+ db_project_path = SQLiteStorage.get_project_db_path(project)
377
+ os.makedirs(os.path.dirname(db_project_path), exist_ok=True)
378
+ shutil.copy(uploaded_db["path"], db_project_path)
379
+
380
+
381
+ def bulk_upload_media(uploads: list[UploadEntry], hf_token: str | None) -> None:
382
+ check_hf_token_has_write_access(hf_token)
383
+ for upload in uploads:
384
+ media_path = get_project_media_path(
385
+ project=upload["project"],
386
+ run=upload["run"],
387
+ step=upload["step"],
388
+ relative_path=upload["relative_path"],
389
+ )
390
+ shutil.copy(upload["uploaded_file"]["path"], media_path)
391
+
392
+
393
+ def log(
394
+ project: str,
395
+ run: str,
396
+ metrics: dict[str, Any],
397
+ step: int | None,
398
+ hf_token: str | None,
399
+ ) -> None:
400
+ check_hf_token_has_write_access(hf_token)
401
+ SQLiteStorage.log(project=project, run=run, metrics=metrics, step=step)
402
+
403
+
404
+ def bulk_log(
405
+ logs: list[LogEntry],
406
+ hf_token: str | None,
407
+ ) -> None:
408
+ check_hf_token_has_write_access(hf_token)
409
+
410
+ logs_by_run = {}
411
+ for log_entry in logs:
412
+ key = (log_entry["project"], log_entry["run"])
413
+ if key not in logs_by_run:
414
+ logs_by_run[key] = {
415
+ "metrics": [],
416
+ "steps": [],
417
+ "log_ids": [],
418
+ "config": None,
419
+ }
420
+ logs_by_run[key]["metrics"].append(log_entry["metrics"])
421
+ logs_by_run[key]["steps"].append(log_entry.get("step"))
422
+ logs_by_run[key]["log_ids"].append(log_entry.get("log_id"))
423
+ if log_entry.get("config") and logs_by_run[key]["config"] is None:
424
+ logs_by_run[key]["config"] = log_entry["config"]
425
+
426
+ for (project, run), data in logs_by_run.items():
427
+ has_log_ids = any(lid is not None for lid in data["log_ids"])
428
+ payload = dict(
429
+ project=project,
430
+ run=run,
431
+ metrics_list=data["metrics"],
432
+ steps=data["steps"],
433
+ config=data["config"],
434
+ log_ids=data["log_ids"] if has_log_ids else None,
435
+ )
436
+ try:
437
+ SQLiteStorage.bulk_log(**payload)
438
+ except sqlite3.OperationalError:
439
+ _enqueue_write("bulk_log", payload)
440
+
441
+
442
+ def bulk_log_system(
443
+ logs: list[SystemLogEntry],
444
+ hf_token: str | None,
445
+ ) -> None:
446
+ check_hf_token_has_write_access(hf_token)
447
+
448
+ logs_by_run = {}
449
+ for log_entry in logs:
450
+ key = (log_entry["project"], log_entry["run"])
451
+ if key not in logs_by_run:
452
+ logs_by_run[key] = {"metrics": [], "timestamps": [], "log_ids": []}
453
+ logs_by_run[key]["metrics"].append(log_entry["metrics"])
454
+ logs_by_run[key]["timestamps"].append(log_entry.get("timestamp"))
455
+ logs_by_run[key]["log_ids"].append(log_entry.get("log_id"))
456
+
457
+ for (project, run), data in logs_by_run.items():
458
+ has_log_ids = any(lid is not None for lid in data["log_ids"])
459
+ payload = dict(
460
+ project=project,
461
+ run=run,
462
+ metrics_list=data["metrics"],
463
+ timestamps=data["timestamps"],
464
+ log_ids=data["log_ids"] if has_log_ids else None,
465
+ )
466
+ try:
467
+ SQLiteStorage.bulk_log_system(**payload)
468
+ except sqlite3.OperationalError:
469
+ _enqueue_write("bulk_log_system", payload)
470
+
471
+
472
+ def bulk_alert(
473
+ alerts: list[AlertEntry],
474
+ hf_token: str | None,
475
+ ) -> None:
476
+ check_hf_token_has_write_access(hf_token)
477
+
478
+ alerts_by_run: dict[tuple, dict] = {}
479
+ for entry in alerts:
480
+ key = (entry["project"], entry["run"])
481
+ if key not in alerts_by_run:
482
+ alerts_by_run[key] = {
483
+ "titles": [],
484
+ "texts": [],
485
+ "levels": [],
486
+ "steps": [],
487
+ "timestamps": [],
488
+ "alert_ids": [],
489
+ }
490
+ alerts_by_run[key]["titles"].append(entry["title"])
491
+ alerts_by_run[key]["texts"].append(entry.get("text"))
492
+ alerts_by_run[key]["levels"].append(entry["level"])
493
+ alerts_by_run[key]["steps"].append(entry.get("step"))
494
+ alerts_by_run[key]["timestamps"].append(entry.get("timestamp"))
495
+ alerts_by_run[key]["alert_ids"].append(entry.get("alert_id"))
496
+
497
+ for (project, run), data in alerts_by_run.items():
498
+ has_alert_ids = any(aid is not None for aid in data["alert_ids"])
499
+ payload = dict(
500
+ project=project,
501
+ run=run,
502
+ titles=data["titles"],
503
+ texts=data["texts"],
504
+ levels=data["levels"],
505
+ steps=data["steps"],
506
+ timestamps=data["timestamps"],
507
+ alert_ids=data["alert_ids"] if has_alert_ids else None,
508
+ )
509
+ try:
510
+ SQLiteStorage.bulk_alert(**payload)
511
+ except sqlite3.OperationalError:
512
+ _enqueue_write("bulk_alert", payload)
513
+
514
+
515
+ def get_alerts(
516
+ project: str,
517
+ run: str | None = None,
518
+ level: str | None = None,
519
+ since: str | None = None,
520
+ ) -> list[dict]:
521
+ return SQLiteStorage.get_alerts(project, run_name=run, level=level, since=since)
522
+
523
+
524
+ def get_metric_values(
525
+ project: str,
526
+ run: str,
527
+ metric_name: str,
528
+ step: int | None = None,
529
+ around_step: int | None = None,
530
+ at_time: str | None = None,
531
+ window: int | None = None,
532
+ ) -> list[dict]:
533
+ return SQLiteStorage.get_metric_values(
534
+ project,
535
+ run,
536
+ metric_name,
537
+ step=step,
538
+ around_step=around_step,
539
+ at_time=at_time,
540
+ window=window,
541
+ )
542
+
543
+
544
+ def get_runs_for_project(project: str) -> list[str]:
545
+ return SQLiteStorage.get_runs(project)
546
+
547
+
548
+ def get_metrics_for_run(project: str, run: str) -> list[str]:
549
+ return SQLiteStorage.get_all_metrics_for_run(project, run)
550
+
551
+
552
+ def filter_metrics_by_regex(metrics: list[str], filter_pattern: str) -> list[str]:
553
+ if not filter_pattern.strip():
554
+ return metrics
555
+ try:
556
+ pattern = re.compile(filter_pattern, re.IGNORECASE)
557
+ return [metric for metric in metrics if pattern.search(metric)]
558
+ except re.error:
559
+ return [
560
+ metric for metric in metrics if filter_pattern.lower() in metric.lower()
561
+ ]
562
+
563
+
564
+ def get_all_projects() -> list[str]:
565
+ return SQLiteStorage.get_projects()
566
+
567
+
568
+ def get_project_summary(project: str) -> dict:
569
+ runs = SQLiteStorage.get_runs(project)
570
+ if not runs:
571
+ return {"project": project, "num_runs": 0, "runs": [], "last_activity": None}
572
+
573
+ last_steps = SQLiteStorage.get_max_steps_for_runs(project)
574
+
575
+ return {
576
+ "project": project,
577
+ "num_runs": len(runs),
578
+ "runs": runs,
579
+ "last_activity": max(last_steps.values()) if last_steps else None,
580
+ }
581
+
582
+
583
+ def get_run_summary(project: str, run: str) -> dict:
584
+ num_logs = SQLiteStorage.get_log_count(project, run)
585
+ if num_logs == 0:
586
+ return {
587
+ "project": project,
588
+ "run": run,
589
+ "num_logs": 0,
590
+ "metrics": [],
591
+ "config": None,
592
+ "last_step": None,
593
+ }
594
+
595
+ metrics = SQLiteStorage.get_all_metrics_for_run(project, run)
596
+ config = SQLiteStorage.get_run_config(project, run)
597
+ last_step = SQLiteStorage.get_last_step(project, run)
598
+
599
+ return {
600
+ "project": project,
601
+ "run": run,
602
+ "num_logs": num_logs,
603
+ "metrics": metrics,
604
+ "config": config,
605
+ "last_step": last_step,
606
+ }
607
+
608
+
609
+ def get_system_metrics_for_run(project: str, run: str) -> list[str]:
610
+ return SQLiteStorage.get_all_system_metrics_for_run(project, run)
611
+
612
+
613
+ def get_system_logs(project: str, run: str) -> list[dict]:
614
+ return SQLiteStorage.get_system_logs(project, run)
615
+
616
+
617
+ def get_snapshot(
618
+ project: str,
619
+ run: str,
620
+ step: int | None = None,
621
+ around_step: int | None = None,
622
+ at_time: str | None = None,
623
+ window: int | None = None,
624
+ ) -> dict:
625
+ return SQLiteStorage.get_snapshot(
626
+ project, run, step=step, around_step=around_step, at_time=at_time, window=window
627
+ )
628
+
629
+
630
+ def get_logs(project: str, run: str) -> list[dict]:
631
+ return SQLiteStorage.get_logs(project, run, max_points=1500)
632
+
633
+
634
+ def get_settings() -> dict:
635
+ return {
636
+ "logo_urls": utils.get_logo_urls(),
637
+ "color_palette": utils.get_color_palette(),
638
+ "plot_order": [
639
+ item.strip()
640
+ for item in os.environ.get("TRACKIO_PLOT_ORDER", "").split(",")
641
+ if item.strip()
642
+ ],
643
+ "table_truncate_length": int(
644
+ os.environ.get("TRACKIO_TABLE_TRUNCATE_LENGTH", "250")
645
+ ),
646
+ "media_dir": str(utils.MEDIA_DIR),
647
+ }
648
+
649
+
650
+ def get_project_files(project: str) -> list[dict]:
651
+ files_dir = utils.MEDIA_DIR / project / "files"
652
+ if not files_dir.exists():
653
+ return []
654
+ results = []
655
+ for file_path in sorted(files_dir.rglob("*")):
656
+ if file_path.is_file():
657
+ relative = file_path.relative_to(files_dir)
658
+ results.append(
659
+ {
660
+ "name": str(relative),
661
+ "path": str(file_path),
662
+ "size": file_path.stat().st_size,
663
+ }
664
+ )
665
+ return results
666
+
667
+
668
+ def delete_run(request: gr.Request, project: str, run: str) -> bool:
669
+ assert_can_mutate_runs(request)
670
+ return SQLiteStorage.delete_run(project, run)
671
+
672
+
673
+ def rename_run(
674
+ request: gr.Request,
675
+ project: str,
676
+ old_name: str,
677
+ new_name: str,
678
+ ) -> bool:
679
+ assert_can_mutate_runs(request)
680
+ SQLiteStorage.rename_run(project, old_name, new_name)
681
+ return True
682
+
683
+
684
+ def force_sync() -> bool:
685
+ if os.environ.get("TRACKIO_BUCKET_ID"):
686
+ return True
687
+ SQLiteStorage._dataset_import_attempted = True
688
+ SQLiteStorage.export_to_parquet()
689
+ scheduler = SQLiteStorage.get_scheduler()
690
+ scheduler.trigger().result()
691
+ return True
692
+
693
+
694
+ CSS = ""
695
+ HEAD = ""
696
+
697
+ gr.set_static_paths(paths=[utils.MEDIA_DIR])
698
+
699
+
700
+ def make_trackio_server() -> TrackioServer:
701
+ server = TrackioServer(title="Trackio Dashboard")
702
+ server.add_api_route(OAUTH_START_PATH, oauth_hf_start, methods=["GET"])
703
+ server.add_api_route(OAUTH_CALLBACK_PATH, oauth_hf_callback, methods=["GET"])
704
+ server.add_api_route("/oauth/logout", oauth_logout, methods=["GET"])
705
+ server.api(fn=get_run_mutation_status, name="get_run_mutation_status")
706
+ server.api(fn=upload_db_to_space, name="upload_db_to_space")
707
+ server.api(fn=bulk_upload_media, name="bulk_upload_media")
708
+ server.api(fn=log, name="log")
709
+ server.api(fn=bulk_log, name="bulk_log")
710
+ server.api(fn=bulk_log_system, name="bulk_log_system")
711
+ server.api(fn=bulk_alert, name="bulk_alert")
712
+ server.api(fn=get_alerts, name="get_alerts")
713
+ server.api(fn=get_metric_values, name="get_metric_values")
714
+ server.api(fn=get_runs_for_project, name="get_runs_for_project")
715
+ server.api(fn=get_metrics_for_run, name="get_metrics_for_run")
716
+ server.api(fn=get_all_projects, name="get_all_projects")
717
+ server.api(fn=get_project_summary, name="get_project_summary")
718
+ server.api(fn=get_run_summary, name="get_run_summary")
719
+ server.api(fn=get_system_metrics_for_run, name="get_system_metrics_for_run")
720
+ server.api(fn=get_system_logs, name="get_system_logs")
721
+ server.api(fn=get_snapshot, name="get_snapshot")
722
+ server.api(fn=get_logs, name="get_logs")
723
+ server.api(fn=get_settings, name="get_settings")
724
+ server.api(fn=get_project_files, name="get_project_files")
725
+ server.api(fn=delete_run, name="delete_run")
726
+ server.api(fn=rename_run, name="rename_run")
727
+ server.api(fn=force_sync, name="force_sync")
728
+ server.write_token = write_token
729
+ return server
trackio/sqlite_storage.py ADDED
@@ -0,0 +1,1906 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json as json_mod
2
+ import os
3
+ import shutil
4
+ import sqlite3
5
+ import time
6
+ from collections.abc import Iterator
7
+ from contextlib import contextmanager
8
+ from datetime import datetime, timezone
9
+ from pathlib import Path
10
+ from threading import Lock
11
+
12
+ try:
13
+ import fcntl
14
+ except ImportError:
15
+ fcntl = None
16
+
17
+ try:
18
+ import msvcrt as _msvcrt
19
+ except ImportError:
20
+ _msvcrt = None
21
+
22
+ import huggingface_hub as hf
23
+ import orjson
24
+ import pandas as pd
25
+
26
+ from trackio.commit_scheduler import CommitScheduler
27
+ from trackio.dummy_commit_scheduler import DummyCommitScheduler
28
+ from trackio.utils import (
29
+ MEDIA_DIR,
30
+ TRACKIO_DIR,
31
+ deserialize_values,
32
+ get_color_palette,
33
+ serialize_values,
34
+ )
35
+
36
+ DB_EXT = ".db"
37
+
38
+ _JOURNAL_MODE_WHITELIST = frozenset(
39
+ {"wal", "delete", "truncate", "persist", "memory", "off"}
40
+ )
41
+
42
+
43
+ def _configure_sqlite_pragmas(conn: sqlite3.Connection) -> None:
44
+ override = os.environ.get("TRACKIO_SQLITE_JOURNAL_MODE", "").strip().lower()
45
+ if override in _JOURNAL_MODE_WHITELIST:
46
+ journal = override.upper()
47
+ elif os.environ.get("SYSTEM") == "spaces":
48
+ journal = "DELETE"
49
+ else:
50
+ journal = "WAL"
51
+ conn.execute(f"PRAGMA journal_mode = {journal}")
52
+ conn.execute("PRAGMA synchronous = NORMAL")
53
+ conn.execute("PRAGMA temp_store = MEMORY")
54
+ conn.execute("PRAGMA cache_size = -20000")
55
+
56
+
57
+ class ProcessLock:
58
+ """A file-based lock that works across processes using fcntl (Unix) or msvcrt (Windows)."""
59
+
60
+ def __init__(self, lockfile_path: Path):
61
+ self.lockfile_path = lockfile_path
62
+ self.lockfile = None
63
+
64
+ def __enter__(self):
65
+ if fcntl is None and _msvcrt is None:
66
+ return self
67
+ self.lockfile_path.parent.mkdir(parents=True, exist_ok=True)
68
+ self.lockfile = open(self.lockfile_path, "w")
69
+
70
+ max_retries = 100
71
+ for attempt in range(max_retries):
72
+ try:
73
+ if fcntl is not None:
74
+ fcntl.flock(self.lockfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
75
+ else:
76
+ _msvcrt.locking(self.lockfile.fileno(), _msvcrt.LK_NBLCK, 1)
77
+ return self
78
+ except (IOError, OSError):
79
+ if attempt < max_retries - 1:
80
+ time.sleep(0.1)
81
+ else:
82
+ raise IOError("Could not acquire database lock after 10 seconds")
83
+
84
+ def __exit__(self, exc_type, exc_val, exc_tb):
85
+ if self.lockfile:
86
+ try:
87
+ if fcntl is not None:
88
+ fcntl.flock(self.lockfile.fileno(), fcntl.LOCK_UN)
89
+ elif _msvcrt is not None:
90
+ _msvcrt.locking(self.lockfile.fileno(), _msvcrt.LK_UNLCK, 1)
91
+ except (IOError, OSError):
92
+ pass
93
+ self.lockfile.close()
94
+
95
+
96
+ class SQLiteStorage:
97
+ _dataset_import_attempted = False
98
+ _current_scheduler: CommitScheduler | DummyCommitScheduler | None = None
99
+ _scheduler_lock = Lock()
100
+
101
+ @staticmethod
102
+ @contextmanager
103
+ def _get_connection(
104
+ db_path: Path,
105
+ *,
106
+ timeout: float = 30.0,
107
+ configure_pragmas: bool = True,
108
+ row_factory=sqlite3.Row,
109
+ ) -> Iterator[sqlite3.Connection]:
110
+ conn = sqlite3.connect(str(db_path), timeout=timeout)
111
+ try:
112
+ if configure_pragmas:
113
+ _configure_sqlite_pragmas(conn)
114
+ if row_factory is not None:
115
+ conn.row_factory = row_factory
116
+ with conn:
117
+ yield conn
118
+ finally:
119
+ conn.close()
120
+
121
+ @staticmethod
122
+ def _get_process_lock(project: str) -> ProcessLock:
123
+ lockfile_path = TRACKIO_DIR / f"{project}.lock"
124
+ return ProcessLock(lockfile_path)
125
+
126
+ @staticmethod
127
+ def get_project_db_filename(project: str) -> str:
128
+ """Get the database filename for a specific project."""
129
+ safe_project_name = "".join(
130
+ c for c in project if c.isalnum() or c in ("-", "_")
131
+ ).rstrip()
132
+ if not safe_project_name:
133
+ safe_project_name = "default"
134
+ return f"{safe_project_name}{DB_EXT}"
135
+
136
+ @staticmethod
137
+ def get_project_db_path(project: str) -> Path:
138
+ """Get the database path for a specific project."""
139
+ filename = SQLiteStorage.get_project_db_filename(project)
140
+ return TRACKIO_DIR / filename
141
+
142
+ @staticmethod
143
+ def init_db(project: str) -> Path:
144
+ """
145
+ Initialize the SQLite database with required tables.
146
+ Returns the database path.
147
+ """
148
+ SQLiteStorage._ensure_hub_loaded()
149
+ db_path = SQLiteStorage.get_project_db_path(project)
150
+ db_path.parent.mkdir(parents=True, exist_ok=True)
151
+ with SQLiteStorage._get_process_lock(project):
152
+ with SQLiteStorage._get_connection(db_path, row_factory=None) as conn:
153
+ cursor = conn.cursor()
154
+ cursor.execute(
155
+ """
156
+ CREATE TABLE IF NOT EXISTS metrics (
157
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
158
+ timestamp TEXT NOT NULL,
159
+ run_name TEXT NOT NULL,
160
+ step INTEGER NOT NULL,
161
+ metrics TEXT NOT NULL
162
+ )
163
+ """
164
+ )
165
+ cursor.execute(
166
+ """
167
+ CREATE TABLE IF NOT EXISTS configs (
168
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
169
+ run_name TEXT NOT NULL,
170
+ config TEXT NOT NULL,
171
+ created_at TEXT NOT NULL,
172
+ UNIQUE(run_name)
173
+ )
174
+ """
175
+ )
176
+ cursor.execute(
177
+ """
178
+ CREATE INDEX IF NOT EXISTS idx_metrics_run_step
179
+ ON metrics(run_name, step)
180
+ """
181
+ )
182
+ cursor.execute(
183
+ """
184
+ CREATE INDEX IF NOT EXISTS idx_configs_run_name
185
+ ON configs(run_name)
186
+ """
187
+ )
188
+ cursor.execute(
189
+ """
190
+ CREATE INDEX IF NOT EXISTS idx_metrics_run_timestamp
191
+ ON metrics(run_name, timestamp)
192
+ """
193
+ )
194
+ cursor.execute(
195
+ """
196
+ CREATE TABLE IF NOT EXISTS system_metrics (
197
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
198
+ timestamp TEXT NOT NULL,
199
+ run_name TEXT NOT NULL,
200
+ metrics TEXT NOT NULL
201
+ )
202
+ """
203
+ )
204
+ cursor.execute(
205
+ """
206
+ CREATE INDEX IF NOT EXISTS idx_system_metrics_run_timestamp
207
+ ON system_metrics(run_name, timestamp)
208
+ """
209
+ )
210
+
211
+ cursor.execute(
212
+ """
213
+ CREATE TABLE IF NOT EXISTS project_metadata (
214
+ key TEXT PRIMARY KEY,
215
+ value TEXT NOT NULL
216
+ )
217
+ """
218
+ )
219
+
220
+ cursor.execute(
221
+ """
222
+ CREATE TABLE IF NOT EXISTS pending_uploads (
223
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
224
+ space_id TEXT NOT NULL,
225
+ run_name TEXT,
226
+ step INTEGER,
227
+ file_path TEXT NOT NULL,
228
+ relative_path TEXT,
229
+ created_at TEXT NOT NULL
230
+ )
231
+ """
232
+ )
233
+
234
+ cursor.execute(
235
+ """
236
+ CREATE TABLE IF NOT EXISTS alerts (
237
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
238
+ timestamp TEXT NOT NULL,
239
+ run_name TEXT NOT NULL,
240
+ title TEXT NOT NULL,
241
+ text TEXT,
242
+ level TEXT NOT NULL DEFAULT 'warn',
243
+ step INTEGER,
244
+ alert_id TEXT
245
+ )
246
+ """
247
+ )
248
+ cursor.execute(
249
+ """
250
+ CREATE INDEX IF NOT EXISTS idx_alerts_run
251
+ ON alerts(run_name)
252
+ """
253
+ )
254
+ cursor.execute(
255
+ """
256
+ CREATE INDEX IF NOT EXISTS idx_alerts_timestamp
257
+ ON alerts(timestamp)
258
+ """
259
+ )
260
+ cursor.execute(
261
+ """
262
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_alerts_alert_id
263
+ ON alerts(alert_id) WHERE alert_id IS NOT NULL
264
+ """
265
+ )
266
+
267
+ for table in ("metrics", "system_metrics"):
268
+ for col in ("log_id TEXT", "space_id TEXT"):
269
+ try:
270
+ cursor.execute(f"ALTER TABLE {table} ADD COLUMN {col}")
271
+ except sqlite3.OperationalError:
272
+ pass
273
+ cursor.execute(
274
+ f"""CREATE UNIQUE INDEX IF NOT EXISTS idx_{table}_log_id
275
+ ON {table}(log_id) WHERE log_id IS NOT NULL"""
276
+ )
277
+ cursor.execute(
278
+ f"""CREATE INDEX IF NOT EXISTS idx_{table}_pending
279
+ ON {table}(space_id) WHERE space_id IS NOT NULL"""
280
+ )
281
+
282
+ conn.commit()
283
+ return db_path
284
+
285
+ @staticmethod
286
+ def _flatten_json_column(df: pd.DataFrame, col: str) -> pd.DataFrame:
287
+ if df.empty:
288
+ return df
289
+ expanded = df[col].copy()
290
+ expanded = pd.DataFrame(
291
+ expanded.apply(
292
+ lambda x: deserialize_values(orjson.loads(x))
293
+ ).values.tolist(),
294
+ index=df.index,
295
+ )
296
+ df = df.drop(columns=[col])
297
+ for c in expanded.columns:
298
+ df[c] = expanded[c]
299
+ return df
300
+
301
+ @staticmethod
302
+ def _read_table(db_path: Path, table: str) -> pd.DataFrame:
303
+ try:
304
+ with SQLiteStorage._get_connection(
305
+ db_path, timeout=5.0, configure_pragmas=False, row_factory=None
306
+ ) as conn:
307
+ return pd.read_sql(f"SELECT * FROM {table}", conn)
308
+ except Exception:
309
+ return pd.DataFrame()
310
+
311
+ @staticmethod
312
+ def _flatten_and_write_parquet(
313
+ db_path: Path, table: str, json_col: str, parquet_path: Path
314
+ ) -> None:
315
+ if (
316
+ parquet_path.exists()
317
+ and db_path.stat().st_mtime <= parquet_path.stat().st_mtime
318
+ ):
319
+ return
320
+ df = SQLiteStorage._read_table(db_path, table)
321
+ if df.empty:
322
+ return
323
+ df = SQLiteStorage._flatten_json_column(df, json_col)
324
+ df.to_parquet(
325
+ parquet_path,
326
+ write_page_index=True,
327
+ use_content_defined_chunking=True,
328
+ )
329
+
330
+ @staticmethod
331
+ def export_to_parquet():
332
+ """
333
+ Exports all projects' DB files as Parquet under the same path but with extension ".parquet".
334
+ Also exports system_metrics to separate parquet files with "_system.parquet" suffix.
335
+ Also exports configs to separate parquet files with "_configs.parquet" suffix.
336
+ """
337
+ if not SQLiteStorage._dataset_import_attempted:
338
+ return
339
+ if not TRACKIO_DIR.exists():
340
+ return
341
+
342
+ all_paths = os.listdir(TRACKIO_DIR)
343
+ db_names = [f for f in all_paths if f.endswith(DB_EXT)]
344
+ for db_name in db_names:
345
+ db_path = TRACKIO_DIR / db_name
346
+ SQLiteStorage._flatten_and_write_parquet(
347
+ db_path, "metrics", "metrics", db_path.with_suffix(".parquet")
348
+ )
349
+ SQLiteStorage._flatten_and_write_parquet(
350
+ db_path,
351
+ "system_metrics",
352
+ "metrics",
353
+ TRACKIO_DIR / (db_path.stem + "_system.parquet"),
354
+ )
355
+ SQLiteStorage._flatten_and_write_parquet(
356
+ db_path,
357
+ "configs",
358
+ "config",
359
+ TRACKIO_DIR / (db_path.stem + "_configs.parquet"),
360
+ )
361
+
362
+ @staticmethod
363
+ def export_for_static_space(project: str, output_dir: Path) -> None:
364
+ """
365
+ Exports a single project's data as Parquet + JSON files for static Space deployment.
366
+ """
367
+ db_path = SQLiteStorage.get_project_db_path(project)
368
+ if not db_path.exists():
369
+ raise FileNotFoundError(f"No database found for project '{project}'")
370
+
371
+ output_dir.mkdir(parents=True, exist_ok=True)
372
+ aux_dir = output_dir / "aux"
373
+ aux_dir.mkdir(parents=True, exist_ok=True)
374
+
375
+ metrics_df = SQLiteStorage._read_table(db_path, "metrics")
376
+ if not metrics_df.empty:
377
+ flat = SQLiteStorage._flatten_json_column(metrics_df.copy(), "metrics")
378
+ flat.to_parquet(output_dir / "metrics.parquet")
379
+
380
+ sys_df = SQLiteStorage._read_table(db_path, "system_metrics")
381
+ if not sys_df.empty:
382
+ flat = SQLiteStorage._flatten_json_column(sys_df.copy(), "metrics")
383
+ flat.to_parquet(aux_dir / "system_metrics.parquet")
384
+
385
+ configs_df = SQLiteStorage._read_table(db_path, "configs")
386
+ if not configs_df.empty:
387
+ flat = SQLiteStorage._flatten_json_column(configs_df.copy(), "config")
388
+ flat.to_parquet(aux_dir / "configs.parquet")
389
+
390
+ runs = SQLiteStorage.get_runs(project)
391
+ runs_meta = []
392
+ for run_name in runs:
393
+ last_step = SQLiteStorage.get_last_step(project, run_name)
394
+ log_count = SQLiteStorage.get_log_count(project, run_name)
395
+ runs_meta.append(
396
+ {
397
+ "name": run_name,
398
+ "last_step": last_step,
399
+ "log_count": log_count,
400
+ }
401
+ )
402
+ with open(output_dir / "runs.json", "w") as f:
403
+ json_mod.dump(runs_meta, f)
404
+
405
+ settings = {
406
+ "color_palette": get_color_palette(),
407
+ "plot_order": [
408
+ item.strip()
409
+ for item in os.environ.get("TRACKIO_PLOT_ORDER", "").split(",")
410
+ if item.strip()
411
+ ],
412
+ }
413
+ with open(output_dir / "settings.json", "w") as f:
414
+ json_mod.dump(settings, f)
415
+
416
+ @staticmethod
417
+ def _cleanup_wal_sidecars(db_path: Path) -> None:
418
+ """Remove leftover -wal/-shm files for a DB basename (prevents disk I/O errors)."""
419
+ for suffix in ("-wal", "-shm"):
420
+ sidecar = Path(str(db_path) + suffix)
421
+ try:
422
+ if sidecar.exists():
423
+ sidecar.unlink()
424
+ except Exception:
425
+ pass
426
+
427
+ @staticmethod
428
+ def import_from_parquet():
429
+ """
430
+ Imports to all DB files that have matching files under the same path but with extension ".parquet".
431
+ Also imports system_metrics from "_system.parquet" files.
432
+ Also imports configs from "_configs.parquet" files.
433
+ """
434
+ if not TRACKIO_DIR.exists():
435
+ return
436
+
437
+ all_paths = os.listdir(TRACKIO_DIR)
438
+ parquet_names = [
439
+ f
440
+ for f in all_paths
441
+ if f.endswith(".parquet")
442
+ and not f.endswith("_system.parquet")
443
+ and not f.endswith("_configs.parquet")
444
+ ]
445
+ imported_projects = {Path(name).stem for name in parquet_names}
446
+ for pq_name in parquet_names:
447
+ parquet_path = TRACKIO_DIR / pq_name
448
+ db_path = parquet_path.with_suffix(DB_EXT)
449
+
450
+ SQLiteStorage._cleanup_wal_sidecars(db_path)
451
+
452
+ df = pd.read_parquet(parquet_path)
453
+ if "metrics" not in df.columns:
454
+ metrics = df.copy()
455
+ structural_cols = [
456
+ "id",
457
+ "timestamp",
458
+ "run_name",
459
+ "step",
460
+ "log_id",
461
+ "space_id",
462
+ ]
463
+ df = df[[c for c in structural_cols if c in df.columns]]
464
+ for col in structural_cols:
465
+ if col in metrics.columns:
466
+ del metrics[col]
467
+ metrics = orjson.loads(metrics.to_json(orient="records"))
468
+ df["metrics"] = [orjson.dumps(serialize_values(row)) for row in metrics]
469
+
470
+ with SQLiteStorage._get_connection(
471
+ db_path, configure_pragmas=False, row_factory=None
472
+ ) as conn:
473
+ df.to_sql("metrics", conn, if_exists="replace", index=False)
474
+ conn.commit()
475
+
476
+ system_parquet_names = [f for f in all_paths if f.endswith("_system.parquet")]
477
+ for pq_name in system_parquet_names:
478
+ parquet_path = TRACKIO_DIR / pq_name
479
+ db_name = pq_name.replace("_system.parquet", DB_EXT)
480
+ db_path = TRACKIO_DIR / db_name
481
+ project_name = db_path.stem
482
+ if project_name not in imported_projects and not db_path.exists():
483
+ continue
484
+
485
+ df = pd.read_parquet(parquet_path)
486
+ if "metrics" not in df.columns:
487
+ metrics = df.copy()
488
+ other_cols = ["id", "timestamp", "run_name"]
489
+ df = df[[c for c in other_cols if c in df.columns]]
490
+ for col in other_cols:
491
+ if col in metrics.columns:
492
+ del metrics[col]
493
+ metrics = orjson.loads(metrics.to_json(orient="records"))
494
+ df["metrics"] = [orjson.dumps(serialize_values(row)) for row in metrics]
495
+
496
+ with SQLiteStorage._get_connection(
497
+ db_path, configure_pragmas=False, row_factory=None
498
+ ) as conn:
499
+ df.to_sql("system_metrics", conn, if_exists="replace", index=False)
500
+ conn.commit()
501
+
502
+ configs_parquet_names = [f for f in all_paths if f.endswith("_configs.parquet")]
503
+ for pq_name in configs_parquet_names:
504
+ parquet_path = TRACKIO_DIR / pq_name
505
+ db_name = pq_name.replace("_configs.parquet", DB_EXT)
506
+ db_path = TRACKIO_DIR / db_name
507
+ project_name = db_path.stem
508
+ if project_name not in imported_projects and not db_path.exists():
509
+ continue
510
+
511
+ df = pd.read_parquet(parquet_path)
512
+ if "config" not in df.columns:
513
+ config_data = df.copy()
514
+ other_cols = ["id", "run_name", "created_at"]
515
+ df = df[[c for c in other_cols if c in df.columns]]
516
+ for col in other_cols:
517
+ if col in config_data.columns:
518
+ del config_data[col]
519
+ config_data = orjson.loads(config_data.to_json(orient="records"))
520
+ df["config"] = [
521
+ orjson.dumps(serialize_values(row)) for row in config_data
522
+ ]
523
+
524
+ with SQLiteStorage._get_connection(
525
+ db_path, configure_pragmas=False, row_factory=None
526
+ ) as conn:
527
+ df.to_sql("configs", conn, if_exists="replace", index=False)
528
+ conn.commit()
529
+
530
+ @staticmethod
531
+ def get_scheduler():
532
+ """
533
+ Get the scheduler for the database based on the environment variables.
534
+ This applies to both local and Spaces.
535
+ """
536
+ with SQLiteStorage._scheduler_lock:
537
+ if SQLiteStorage._current_scheduler is not None:
538
+ return SQLiteStorage._current_scheduler
539
+ hf_token = os.environ.get("HF_TOKEN")
540
+ dataset_id = os.environ.get("TRACKIO_DATASET_ID")
541
+ space_repo_name = os.environ.get("SPACE_REPO_NAME")
542
+ if dataset_id is not None and space_repo_name is not None:
543
+ scheduler = CommitScheduler(
544
+ repo_id=dataset_id,
545
+ repo_type="dataset",
546
+ folder_path=TRACKIO_DIR,
547
+ private=True,
548
+ allow_patterns=[
549
+ "*.parquet",
550
+ "*_system.parquet",
551
+ "*_configs.parquet",
552
+ "media/**/*",
553
+ ],
554
+ squash_history=True,
555
+ token=hf_token,
556
+ on_before_commit=SQLiteStorage.export_to_parquet,
557
+ )
558
+ else:
559
+ scheduler = DummyCommitScheduler()
560
+ SQLiteStorage._current_scheduler = scheduler
561
+ return scheduler
562
+
563
+ @staticmethod
564
+ def log(project: str, run: str, metrics: dict, step: int | None = None):
565
+ """
566
+ Safely log metrics to the database. Before logging, this method will ensure the database exists
567
+ and is set up with the correct tables. It also uses a cross-process lock to prevent
568
+ database locking errors when multiple processes access the same database.
569
+
570
+ This method is not used in the latest versions of Trackio (replaced by bulk_log) but
571
+ is kept for backwards compatibility for users who are connecting to a newer version of
572
+ a Trackio Spaces dashboard with an older version of Trackio installed locally.
573
+ """
574
+ db_path = SQLiteStorage.init_db(project)
575
+ with SQLiteStorage._get_process_lock(project):
576
+ with SQLiteStorage._get_connection(db_path) as conn:
577
+ cursor = conn.cursor()
578
+ cursor.execute(
579
+ """
580
+ SELECT MAX(step)
581
+ FROM metrics
582
+ WHERE run_name = ?
583
+ """,
584
+ (run,),
585
+ )
586
+ last_step = cursor.fetchone()[0]
587
+ current_step = (
588
+ 0
589
+ if step is None and last_step is None
590
+ else (step if step is not None else last_step + 1)
591
+ )
592
+ current_timestamp = datetime.now(timezone.utc).isoformat()
593
+ cursor.execute(
594
+ """
595
+ INSERT INTO metrics
596
+ (timestamp, run_name, step, metrics)
597
+ VALUES (?, ?, ?, ?)
598
+ """,
599
+ (
600
+ current_timestamp,
601
+ run,
602
+ current_step,
603
+ orjson.dumps(serialize_values(metrics)),
604
+ ),
605
+ )
606
+ conn.commit()
607
+
608
+ @staticmethod
609
+ def bulk_log(
610
+ project: str,
611
+ run: str,
612
+ metrics_list: list[dict],
613
+ steps: list[int] | None = None,
614
+ timestamps: list[str] | None = None,
615
+ config: dict | None = None,
616
+ log_ids: list[str] | None = None,
617
+ space_id: str | None = None,
618
+ ):
619
+ """
620
+ Safely log bulk metrics to the database. Before logging, this method will ensure the database exists
621
+ and is set up with the correct tables. It also uses a cross-process lock to prevent
622
+ database locking errors when multiple processes access the same database.
623
+ """
624
+ if not metrics_list:
625
+ return
626
+
627
+ if timestamps is None:
628
+ timestamps = [datetime.now(timezone.utc).isoformat()] * len(metrics_list)
629
+
630
+ db_path = SQLiteStorage.init_db(project)
631
+ with SQLiteStorage._get_process_lock(project):
632
+ with SQLiteStorage._get_connection(db_path) as conn:
633
+ cursor = conn.cursor()
634
+
635
+ if steps is None:
636
+ steps = list(range(len(metrics_list)))
637
+ elif any(s is None for s in steps):
638
+ cursor.execute(
639
+ "SELECT MAX(step) FROM metrics WHERE run_name = ?", (run,)
640
+ )
641
+ last_step = cursor.fetchone()[0]
642
+ current_step = 0 if last_step is None else last_step + 1
643
+ processed_steps = []
644
+ for step in steps:
645
+ if step is None:
646
+ processed_steps.append(current_step)
647
+ current_step += 1
648
+ else:
649
+ processed_steps.append(step)
650
+ steps = processed_steps
651
+
652
+ if len(metrics_list) != len(steps) or len(metrics_list) != len(
653
+ timestamps
654
+ ):
655
+ raise ValueError(
656
+ "metrics_list, steps, and timestamps must have the same length"
657
+ )
658
+
659
+ data = []
660
+ for i, metrics in enumerate(metrics_list):
661
+ lid = log_ids[i] if log_ids else None
662
+ data.append(
663
+ (
664
+ timestamps[i],
665
+ run,
666
+ steps[i],
667
+ orjson.dumps(serialize_values(metrics)),
668
+ lid,
669
+ space_id,
670
+ )
671
+ )
672
+
673
+ cursor.executemany(
674
+ """
675
+ INSERT OR IGNORE INTO metrics
676
+ (timestamp, run_name, step, metrics, log_id, space_id)
677
+ VALUES (?, ?, ?, ?, ?, ?)
678
+ """,
679
+ data,
680
+ )
681
+
682
+ if config:
683
+ current_timestamp = datetime.now(timezone.utc).isoformat()
684
+ cursor.execute(
685
+ """
686
+ INSERT OR REPLACE INTO configs
687
+ (run_name, config, created_at)
688
+ VALUES (?, ?, ?)
689
+ """,
690
+ (
691
+ run,
692
+ orjson.dumps(serialize_values(config)),
693
+ current_timestamp,
694
+ ),
695
+ )
696
+
697
+ conn.commit()
698
+
699
+ @staticmethod
700
+ def bulk_log_system(
701
+ project: str,
702
+ run: str,
703
+ metrics_list: list[dict],
704
+ timestamps: list[str] | None = None,
705
+ log_ids: list[str] | None = None,
706
+ space_id: str | None = None,
707
+ ):
708
+ """
709
+ Log system metrics (GPU, etc.) to the database without step numbers.
710
+ These metrics use timestamps for the x-axis instead of steps.
711
+ """
712
+ if not metrics_list:
713
+ return
714
+
715
+ if timestamps is None:
716
+ timestamps = [datetime.now(timezone.utc).isoformat()] * len(metrics_list)
717
+
718
+ if len(metrics_list) != len(timestamps):
719
+ raise ValueError("metrics_list and timestamps must have the same length")
720
+
721
+ db_path = SQLiteStorage.init_db(project)
722
+ with SQLiteStorage._get_process_lock(project):
723
+ with SQLiteStorage._get_connection(db_path) as conn:
724
+ cursor = conn.cursor()
725
+ data = []
726
+ for i, metrics in enumerate(metrics_list):
727
+ lid = log_ids[i] if log_ids else None
728
+ data.append(
729
+ (
730
+ timestamps[i],
731
+ run,
732
+ orjson.dumps(serialize_values(metrics)),
733
+ lid,
734
+ space_id,
735
+ )
736
+ )
737
+
738
+ cursor.executemany(
739
+ """
740
+ INSERT OR IGNORE INTO system_metrics
741
+ (timestamp, run_name, metrics, log_id, space_id)
742
+ VALUES (?, ?, ?, ?, ?)
743
+ """,
744
+ data,
745
+ )
746
+ conn.commit()
747
+
748
+ @staticmethod
749
+ def bulk_alert(
750
+ project: str,
751
+ run: str,
752
+ titles: list[str],
753
+ texts: list[str | None],
754
+ levels: list[str],
755
+ steps: list[int | None],
756
+ timestamps: list[str] | None = None,
757
+ alert_ids: list[str] | None = None,
758
+ ):
759
+ if not titles:
760
+ return
761
+
762
+ if timestamps is None:
763
+ timestamps = [datetime.now(timezone.utc).isoformat()] * len(titles)
764
+
765
+ db_path = SQLiteStorage.init_db(project)
766
+ with SQLiteStorage._get_process_lock(project):
767
+ with SQLiteStorage._get_connection(db_path) as conn:
768
+ cursor = conn.cursor()
769
+ data = []
770
+ for i in range(len(titles)):
771
+ aid = alert_ids[i] if alert_ids else None
772
+ data.append(
773
+ (
774
+ timestamps[i],
775
+ run,
776
+ titles[i],
777
+ texts[i],
778
+ levels[i],
779
+ steps[i],
780
+ aid,
781
+ )
782
+ )
783
+
784
+ cursor.executemany(
785
+ """
786
+ INSERT OR IGNORE INTO alerts
787
+ (timestamp, run_name, title, text, level, step, alert_id)
788
+ VALUES (?, ?, ?, ?, ?, ?, ?)
789
+ """,
790
+ data,
791
+ )
792
+ conn.commit()
793
+
794
+ @staticmethod
795
+ def get_alerts(
796
+ project: str,
797
+ run_name: str | None = None,
798
+ level: str | None = None,
799
+ since: str | None = None,
800
+ ) -> list[dict]:
801
+ db_path = SQLiteStorage.get_project_db_path(project)
802
+ if not db_path.exists():
803
+ return []
804
+
805
+ with SQLiteStorage._get_connection(db_path) as conn:
806
+ cursor = conn.cursor()
807
+ try:
808
+ query = (
809
+ "SELECT timestamp, run_name, title, text, level, step FROM alerts"
810
+ )
811
+ conditions = []
812
+ params = []
813
+ if run_name is not None:
814
+ conditions.append("run_name = ?")
815
+ params.append(run_name)
816
+ if level is not None:
817
+ conditions.append("level = ?")
818
+ params.append(level)
819
+ if since is not None:
820
+ conditions.append("timestamp > ?")
821
+ params.append(since)
822
+ if conditions:
823
+ query += " WHERE " + " AND ".join(conditions)
824
+ query += " ORDER BY timestamp DESC"
825
+ cursor.execute(query, params)
826
+
827
+ rows = cursor.fetchall()
828
+ return [
829
+ {
830
+ "timestamp": row["timestamp"],
831
+ "run": row["run_name"],
832
+ "title": row["title"],
833
+ "text": row["text"],
834
+ "level": row["level"],
835
+ "step": row["step"],
836
+ }
837
+ for row in rows
838
+ ]
839
+ except sqlite3.OperationalError as e:
840
+ if "no such table: alerts" in str(e):
841
+ return []
842
+ raise
843
+
844
+ @staticmethod
845
+ def get_alert_count(project: str) -> int:
846
+ db_path = SQLiteStorage.get_project_db_path(project)
847
+ if not db_path.exists():
848
+ return 0
849
+
850
+ with SQLiteStorage._get_connection(db_path) as conn:
851
+ cursor = conn.cursor()
852
+ try:
853
+ cursor.execute("SELECT COUNT(*) FROM alerts")
854
+ return cursor.fetchone()[0]
855
+ except sqlite3.OperationalError:
856
+ return 0
857
+
858
+ @staticmethod
859
+ def get_system_logs(project: str, run: str) -> list[dict]:
860
+ """Retrieve system metrics for a specific run. Returns metrics with timestamps (no steps)."""
861
+ db_path = SQLiteStorage.get_project_db_path(project)
862
+ if not db_path.exists():
863
+ return []
864
+
865
+ with SQLiteStorage._get_connection(db_path) as conn:
866
+ cursor = conn.cursor()
867
+ try:
868
+ cursor.execute(
869
+ """
870
+ SELECT timestamp, metrics
871
+ FROM system_metrics
872
+ WHERE run_name = ?
873
+ ORDER BY timestamp
874
+ """,
875
+ (run,),
876
+ )
877
+
878
+ rows = cursor.fetchall()
879
+ results = []
880
+ for row in rows:
881
+ metrics = orjson.loads(row["metrics"])
882
+ metrics = deserialize_values(metrics)
883
+ metrics["timestamp"] = row["timestamp"]
884
+ results.append(metrics)
885
+ return results
886
+ except sqlite3.OperationalError as e:
887
+ if "no such table: system_metrics" in str(e):
888
+ return []
889
+ raise
890
+
891
+ @staticmethod
892
+ def get_all_system_metrics_for_run(project: str, run: str) -> list[str]:
893
+ """Get all system metric names for a specific project/run."""
894
+ return SQLiteStorage._get_metric_names(
895
+ project, run, "system_metrics", exclude_keys={"timestamp"}
896
+ )
897
+
898
+ @staticmethod
899
+ def has_system_metrics(project: str) -> bool:
900
+ """Check if a project has any system metrics logged."""
901
+ db_path = SQLiteStorage.get_project_db_path(project)
902
+ if not db_path.exists():
903
+ return False
904
+
905
+ with SQLiteStorage._get_connection(db_path) as conn:
906
+ cursor = conn.cursor()
907
+ try:
908
+ cursor.execute("SELECT COUNT(*) FROM system_metrics LIMIT 1")
909
+ count = cursor.fetchone()[0]
910
+ return count > 0
911
+ except sqlite3.OperationalError:
912
+ return False
913
+
914
+ @staticmethod
915
+ def get_log_count(project: str, run: str) -> int:
916
+ SQLiteStorage._ensure_hub_loaded()
917
+ db_path = SQLiteStorage.get_project_db_path(project)
918
+ if not db_path.exists():
919
+ return 0
920
+ try:
921
+ with SQLiteStorage._get_connection(db_path) as conn:
922
+ cursor = conn.cursor()
923
+ cursor.execute(
924
+ "SELECT COUNT(*) FROM metrics WHERE run_name = ?",
925
+ (run,),
926
+ )
927
+ return cursor.fetchone()[0]
928
+ except sqlite3.OperationalError as e:
929
+ if "no such table: metrics" in str(e):
930
+ return 0
931
+ raise
932
+
933
+ @staticmethod
934
+ def get_last_step(project: str, run: str) -> int | None:
935
+ db_path = SQLiteStorage.get_project_db_path(project)
936
+ if not db_path.exists():
937
+ return None
938
+ try:
939
+ with SQLiteStorage._get_connection(db_path) as conn:
940
+ cursor = conn.cursor()
941
+ cursor.execute(
942
+ "SELECT MAX(step) FROM metrics WHERE run_name = ?",
943
+ (run,),
944
+ )
945
+ row = cursor.fetchone()
946
+ return row[0] if row and row[0] is not None else None
947
+ except sqlite3.OperationalError as e:
948
+ if "no such table: metrics" in str(e):
949
+ return None
950
+ raise
951
+
952
+ @staticmethod
953
+ def get_logs(project: str, run: str, max_points: int | None = None) -> list[dict]:
954
+ """Retrieve logs for a specific run. Logs include the step count (int) and the timestamp (datetime object)."""
955
+ db_path = SQLiteStorage.get_project_db_path(project)
956
+ if not db_path.exists():
957
+ return []
958
+
959
+ try:
960
+ with SQLiteStorage._get_connection(db_path) as conn:
961
+ cursor = conn.cursor()
962
+ cursor.execute(
963
+ """
964
+ SELECT timestamp, step, metrics
965
+ FROM metrics
966
+ WHERE run_name = ?
967
+ ORDER BY timestamp
968
+ """,
969
+ (run,),
970
+ )
971
+
972
+ rows = cursor.fetchall()
973
+ if max_points is not None and len(rows) > max_points:
974
+ step = len(rows) / max_points
975
+ indices = {int(i * step) for i in range(max_points)}
976
+ indices.add(len(rows) - 1)
977
+ rows = [rows[i] for i in sorted(indices)]
978
+
979
+ results = []
980
+ for row in rows:
981
+ metrics = orjson.loads(row["metrics"])
982
+ metrics = deserialize_values(metrics)
983
+ metrics["timestamp"] = row["timestamp"]
984
+ metrics["step"] = row["step"]
985
+ results.append(metrics)
986
+ return results
987
+ except sqlite3.OperationalError as e:
988
+ if "no such table: metrics" in str(e):
989
+ return []
990
+ raise
991
+
992
+ @staticmethod
993
+ def load_from_dataset():
994
+ bucket_id = os.environ.get("TRACKIO_BUCKET_ID")
995
+ if bucket_id is not None:
996
+ if not SQLiteStorage._dataset_import_attempted:
997
+ from trackio.bucket_storage import download_bucket_to_trackio_dir
998
+
999
+ try:
1000
+ download_bucket_to_trackio_dir(bucket_id)
1001
+ except Exception:
1002
+ pass
1003
+ SQLiteStorage._dataset_import_attempted = True
1004
+ return
1005
+ dataset_id = os.environ.get("TRACKIO_DATASET_ID")
1006
+ space_repo_name = os.environ.get("SPACE_REPO_NAME")
1007
+ if dataset_id is not None and space_repo_name is not None:
1008
+ hfapi = hf.HfApi()
1009
+ updated = False
1010
+ if not TRACKIO_DIR.exists():
1011
+ TRACKIO_DIR.mkdir(parents=True, exist_ok=True)
1012
+ with SQLiteStorage.get_scheduler().lock:
1013
+ try:
1014
+ files = hfapi.list_repo_files(dataset_id, repo_type="dataset")
1015
+ for file in files:
1016
+ # Download parquet and media assets
1017
+ if not (file.endswith(".parquet") or file.startswith("media/")):
1018
+ continue
1019
+ if (TRACKIO_DIR / file).exists():
1020
+ continue
1021
+ hf.hf_hub_download(
1022
+ dataset_id, file, repo_type="dataset", local_dir=TRACKIO_DIR
1023
+ )
1024
+ updated = True
1025
+ except hf.errors.EntryNotFoundError:
1026
+ pass
1027
+ except hf.errors.RepositoryNotFoundError:
1028
+ pass
1029
+ if updated:
1030
+ SQLiteStorage.import_from_parquet()
1031
+ SQLiteStorage._dataset_import_attempted = True
1032
+
1033
+ @staticmethod
1034
+ def _ensure_hub_loaded():
1035
+ if not SQLiteStorage._dataset_import_attempted:
1036
+ SQLiteStorage.load_from_dataset()
1037
+
1038
+ @staticmethod
1039
+ def get_projects() -> list[str]:
1040
+ """
1041
+ Get list of all projects by scanning the database files in the trackio directory.
1042
+ """
1043
+ SQLiteStorage._ensure_hub_loaded()
1044
+
1045
+ projects: set[str] = set()
1046
+ if not TRACKIO_DIR.exists():
1047
+ return []
1048
+
1049
+ for db_file in TRACKIO_DIR.glob(f"*{DB_EXT}"):
1050
+ project_name = db_file.stem
1051
+ projects.add(project_name)
1052
+ return sorted(projects)
1053
+
1054
+ @staticmethod
1055
+ def get_runs(project: str) -> list[str]:
1056
+ """Get list of all runs for a project, ordered by creation time."""
1057
+ SQLiteStorage._ensure_hub_loaded()
1058
+ db_path = SQLiteStorage.get_project_db_path(project)
1059
+ if not db_path.exists():
1060
+ return []
1061
+
1062
+ try:
1063
+ with SQLiteStorage._get_connection(db_path) as conn:
1064
+ cursor = conn.cursor()
1065
+ cursor.execute(
1066
+ """
1067
+ SELECT run_name
1068
+ FROM metrics
1069
+ GROUP BY run_name
1070
+ ORDER BY MIN(timestamp) ASC
1071
+ """,
1072
+ )
1073
+ return [row[0] for row in cursor.fetchall()]
1074
+ except sqlite3.OperationalError as e:
1075
+ if "no such table: metrics" in str(e):
1076
+ return []
1077
+ raise
1078
+
1079
+ @staticmethod
1080
+ def get_max_steps_for_runs(project: str) -> dict[str, int]:
1081
+ """Get the maximum step for each run in a project."""
1082
+ db_path = SQLiteStorage.get_project_db_path(project)
1083
+ if not db_path.exists():
1084
+ return {}
1085
+
1086
+ try:
1087
+ with SQLiteStorage._get_connection(db_path) as conn:
1088
+ cursor = conn.cursor()
1089
+ cursor.execute(
1090
+ """
1091
+ SELECT run_name, MAX(step) as max_step
1092
+ FROM metrics
1093
+ GROUP BY run_name
1094
+ """
1095
+ )
1096
+
1097
+ results = {}
1098
+ for row in cursor.fetchall():
1099
+ results[row["run_name"]] = row["max_step"]
1100
+
1101
+ return results
1102
+ except sqlite3.OperationalError as e:
1103
+ if "no such table: metrics" in str(e):
1104
+ return {}
1105
+ raise
1106
+
1107
+ @staticmethod
1108
+ def get_max_step_for_run(project: str, run: str) -> int | None:
1109
+ """Get the maximum step for a specific run, or None if no logs exist."""
1110
+ db_path = SQLiteStorage.get_project_db_path(project)
1111
+ if not db_path.exists():
1112
+ return None
1113
+
1114
+ try:
1115
+ with SQLiteStorage._get_connection(db_path) as conn:
1116
+ cursor = conn.cursor()
1117
+ cursor.execute(
1118
+ "SELECT MAX(step) FROM metrics WHERE run_name = ?", (run,)
1119
+ )
1120
+ result = cursor.fetchone()[0]
1121
+ return result
1122
+ except sqlite3.OperationalError as e:
1123
+ if "no such table: metrics" in str(e):
1124
+ return None
1125
+ raise
1126
+
1127
+ @staticmethod
1128
+ def get_run_config(project: str, run: str) -> dict | None:
1129
+ """Get configuration for a specific run."""
1130
+ db_path = SQLiteStorage.get_project_db_path(project)
1131
+ if not db_path.exists():
1132
+ return None
1133
+
1134
+ with SQLiteStorage._get_connection(db_path) as conn:
1135
+ cursor = conn.cursor()
1136
+ try:
1137
+ cursor.execute(
1138
+ """
1139
+ SELECT config FROM configs WHERE run_name = ?
1140
+ """,
1141
+ (run,),
1142
+ )
1143
+
1144
+ row = cursor.fetchone()
1145
+ if row:
1146
+ config = orjson.loads(row["config"])
1147
+ return deserialize_values(config)
1148
+ return None
1149
+ except sqlite3.OperationalError as e:
1150
+ if "no such table: configs" in str(e):
1151
+ return None
1152
+ raise
1153
+
1154
+ @staticmethod
1155
+ def delete_run(project: str, run: str) -> bool:
1156
+ """Delete a run from the database (metrics, config, and system_metrics)."""
1157
+ db_path = SQLiteStorage.get_project_db_path(project)
1158
+ if not db_path.exists():
1159
+ return False
1160
+
1161
+ with SQLiteStorage._get_process_lock(project):
1162
+ with SQLiteStorage._get_connection(db_path) as conn:
1163
+ cursor = conn.cursor()
1164
+ try:
1165
+ cursor.execute("DELETE FROM metrics WHERE run_name = ?", (run,))
1166
+ cursor.execute("DELETE FROM configs WHERE run_name = ?", (run,))
1167
+ try:
1168
+ cursor.execute(
1169
+ "DELETE FROM system_metrics WHERE run_name = ?", (run,)
1170
+ )
1171
+ except sqlite3.OperationalError:
1172
+ pass
1173
+ try:
1174
+ cursor.execute("DELETE FROM alerts WHERE run_name = ?", (run,))
1175
+ except sqlite3.OperationalError:
1176
+ pass
1177
+ conn.commit()
1178
+ return True
1179
+ except sqlite3.Error:
1180
+ return False
1181
+
1182
+ @staticmethod
1183
+ def _update_media_paths(obj, old_prefix, new_prefix):
1184
+ """Update media file paths in nested data structures."""
1185
+ if isinstance(obj, dict):
1186
+ if obj.get("_type") in [
1187
+ "trackio.image",
1188
+ "trackio.video",
1189
+ "trackio.audio",
1190
+ ]:
1191
+ old_path = obj.get("file_path", "")
1192
+ if isinstance(old_path, str):
1193
+ normalized_path = old_path.replace("\\", "/")
1194
+ if normalized_path.startswith(old_prefix):
1195
+ new_path = normalized_path.replace(old_prefix, new_prefix, 1)
1196
+ return {**obj, "file_path": new_path}
1197
+ return {
1198
+ key: SQLiteStorage._update_media_paths(value, old_prefix, new_prefix)
1199
+ for key, value in obj.items()
1200
+ }
1201
+ elif isinstance(obj, list):
1202
+ return [
1203
+ SQLiteStorage._update_media_paths(item, old_prefix, new_prefix)
1204
+ for item in obj
1205
+ ]
1206
+ return obj
1207
+
1208
+ @staticmethod
1209
+ def _rewrite_metrics_rows(metrics_rows, new_run_name, old_prefix, new_prefix):
1210
+ """Deserialize metrics rows, update media paths, and reserialize."""
1211
+ result = []
1212
+ for row in metrics_rows:
1213
+ metrics_data = orjson.loads(row["metrics"])
1214
+ metrics_deserialized = deserialize_values(metrics_data)
1215
+ updated = SQLiteStorage._update_media_paths(
1216
+ metrics_deserialized, old_prefix, new_prefix
1217
+ )
1218
+ result.append(
1219
+ (
1220
+ row["timestamp"],
1221
+ new_run_name,
1222
+ row["step"],
1223
+ orjson.dumps(serialize_values(updated)),
1224
+ )
1225
+ )
1226
+ return result
1227
+
1228
+ @staticmethod
1229
+ def _move_media_dir(source: Path, target: Path):
1230
+ """Move a media directory from source to target."""
1231
+ if source.exists():
1232
+ target.parent.mkdir(parents=True, exist_ok=True)
1233
+ if target.exists():
1234
+ shutil.rmtree(target)
1235
+ shutil.move(str(source), str(target))
1236
+
1237
+ @staticmethod
1238
+ def rename_run(project: str, old_name: str, new_name: str) -> None:
1239
+ """Rename a run within the same project.
1240
+
1241
+ Raises:
1242
+ ValueError: If the new name is empty, the old run doesn't exist,
1243
+ or a run with the new name already exists.
1244
+ RuntimeError: If the database operation fails.
1245
+ """
1246
+ if not new_name or not new_name.strip():
1247
+ raise ValueError("New run name cannot be empty")
1248
+
1249
+ new_name = new_name.strip()
1250
+
1251
+ db_path = SQLiteStorage.get_project_db_path(project)
1252
+ if not db_path.exists():
1253
+ raise ValueError(f"Project '{project}' does not exist")
1254
+
1255
+ with SQLiteStorage._get_process_lock(project):
1256
+ with SQLiteStorage._get_connection(db_path) as conn:
1257
+ cursor = conn.cursor()
1258
+
1259
+ cursor.execute(
1260
+ "SELECT COUNT(*) FROM metrics WHERE run_name = ?", (old_name,)
1261
+ )
1262
+ if cursor.fetchone()[0] == 0:
1263
+ raise ValueError(
1264
+ f"Run '{old_name}' does not exist in project '{project}'"
1265
+ )
1266
+
1267
+ cursor.execute(
1268
+ "SELECT COUNT(*) FROM metrics WHERE run_name = ?", (new_name,)
1269
+ )
1270
+ if cursor.fetchone()[0] > 0:
1271
+ raise ValueError(
1272
+ f"A run named '{new_name}' already exists in project '{project}'"
1273
+ )
1274
+
1275
+ try:
1276
+ cursor.execute(
1277
+ "SELECT timestamp, step, metrics FROM metrics WHERE run_name = ?",
1278
+ (old_name,),
1279
+ )
1280
+ metrics_rows = cursor.fetchall()
1281
+
1282
+ old_prefix = f"{project}/{old_name}/"
1283
+ new_prefix = f"{project}/{new_name}/"
1284
+
1285
+ updated_rows = SQLiteStorage._rewrite_metrics_rows(
1286
+ metrics_rows, new_name, old_prefix, new_prefix
1287
+ )
1288
+
1289
+ cursor.execute(
1290
+ "DELETE FROM metrics WHERE run_name = ?", (old_name,)
1291
+ )
1292
+ cursor.executemany(
1293
+ "INSERT INTO metrics (timestamp, run_name, step, metrics) VALUES (?, ?, ?, ?)",
1294
+ updated_rows,
1295
+ )
1296
+
1297
+ cursor.execute(
1298
+ "UPDATE configs SET run_name = ? WHERE run_name = ?",
1299
+ (new_name, old_name),
1300
+ )
1301
+
1302
+ try:
1303
+ cursor.execute(
1304
+ "UPDATE system_metrics SET run_name = ? WHERE run_name = ?",
1305
+ (new_name, old_name),
1306
+ )
1307
+ except sqlite3.OperationalError:
1308
+ pass
1309
+
1310
+ try:
1311
+ cursor.execute(
1312
+ "UPDATE alerts SET run_name = ? WHERE run_name = ?",
1313
+ (new_name, old_name),
1314
+ )
1315
+ except sqlite3.OperationalError:
1316
+ pass
1317
+
1318
+ conn.commit()
1319
+
1320
+ SQLiteStorage._move_media_dir(
1321
+ MEDIA_DIR / project / old_name,
1322
+ MEDIA_DIR / project / new_name,
1323
+ )
1324
+ except sqlite3.Error as e:
1325
+ raise RuntimeError(
1326
+ f"Database error while renaming run '{old_name}' to '{new_name}': {e}"
1327
+ ) from e
1328
+
1329
+ @staticmethod
1330
+ def move_run(project: str, run: str, new_project: str) -> bool:
1331
+ """Move a run from one project to another."""
1332
+ source_db_path = SQLiteStorage.get_project_db_path(project)
1333
+ if not source_db_path.exists():
1334
+ return False
1335
+
1336
+ target_db_path = SQLiteStorage.init_db(new_project)
1337
+
1338
+ with SQLiteStorage._get_process_lock(project):
1339
+ with SQLiteStorage._get_process_lock(new_project):
1340
+ with SQLiteStorage._get_connection(source_db_path) as source_conn:
1341
+ source_cursor = source_conn.cursor()
1342
+
1343
+ source_cursor.execute(
1344
+ "SELECT timestamp, step, metrics FROM metrics WHERE run_name = ?",
1345
+ (run,),
1346
+ )
1347
+ metrics_rows = source_cursor.fetchall()
1348
+
1349
+ source_cursor.execute(
1350
+ "SELECT config, created_at FROM configs WHERE run_name = ?",
1351
+ (run,),
1352
+ )
1353
+ config_row = source_cursor.fetchone()
1354
+
1355
+ try:
1356
+ source_cursor.execute(
1357
+ "SELECT timestamp, metrics FROM system_metrics WHERE run_name = ?",
1358
+ (run,),
1359
+ )
1360
+ system_metrics_rows = source_cursor.fetchall()
1361
+ except sqlite3.OperationalError:
1362
+ system_metrics_rows = []
1363
+
1364
+ try:
1365
+ source_cursor.execute(
1366
+ "SELECT timestamp, title, text, level, step, alert_id FROM alerts WHERE run_name = ?",
1367
+ (run,),
1368
+ )
1369
+ alert_rows = source_cursor.fetchall()
1370
+ except sqlite3.OperationalError:
1371
+ alert_rows = []
1372
+
1373
+ if not metrics_rows and not config_row and not system_metrics_rows:
1374
+ return False
1375
+
1376
+ with SQLiteStorage._get_connection(target_db_path) as target_conn:
1377
+ target_cursor = target_conn.cursor()
1378
+
1379
+ old_prefix = f"{project}/{run}/"
1380
+ new_prefix = f"{new_project}/{run}/"
1381
+ updated_rows = SQLiteStorage._rewrite_metrics_rows(
1382
+ metrics_rows, run, old_prefix, new_prefix
1383
+ )
1384
+
1385
+ target_cursor.executemany(
1386
+ "INSERT INTO metrics (timestamp, run_name, step, metrics) VALUES (?, ?, ?, ?)",
1387
+ updated_rows,
1388
+ )
1389
+
1390
+ if config_row:
1391
+ target_cursor.execute(
1392
+ """
1393
+ INSERT OR REPLACE INTO configs (run_name, config, created_at)
1394
+ VALUES (?, ?, ?)
1395
+ """,
1396
+ (run, config_row["config"], config_row["created_at"]),
1397
+ )
1398
+
1399
+ for row in system_metrics_rows:
1400
+ try:
1401
+ target_cursor.execute(
1402
+ """
1403
+ INSERT INTO system_metrics (timestamp, run_name, metrics)
1404
+ VALUES (?, ?, ?)
1405
+ """,
1406
+ (row["timestamp"], run, row["metrics"]),
1407
+ )
1408
+ except sqlite3.OperationalError:
1409
+ pass
1410
+
1411
+ for row in alert_rows:
1412
+ try:
1413
+ target_cursor.execute(
1414
+ """
1415
+ INSERT OR IGNORE INTO alerts (timestamp, run_name, title, text, level, step, alert_id)
1416
+ VALUES (?, ?, ?, ?, ?, ?, ?)
1417
+ """,
1418
+ (
1419
+ row["timestamp"],
1420
+ run,
1421
+ row["title"],
1422
+ row["text"],
1423
+ row["level"],
1424
+ row["step"],
1425
+ row["alert_id"],
1426
+ ),
1427
+ )
1428
+ except sqlite3.OperationalError:
1429
+ pass
1430
+
1431
+ target_conn.commit()
1432
+
1433
+ SQLiteStorage._move_media_dir(
1434
+ MEDIA_DIR / project / run,
1435
+ MEDIA_DIR / new_project / run,
1436
+ )
1437
+
1438
+ source_cursor.execute(
1439
+ "DELETE FROM metrics WHERE run_name = ?", (run,)
1440
+ )
1441
+ source_cursor.execute(
1442
+ "DELETE FROM configs WHERE run_name = ?", (run,)
1443
+ )
1444
+ try:
1445
+ source_cursor.execute(
1446
+ "DELETE FROM system_metrics WHERE run_name = ?", (run,)
1447
+ )
1448
+ except sqlite3.OperationalError:
1449
+ pass
1450
+ try:
1451
+ source_cursor.execute(
1452
+ "DELETE FROM alerts WHERE run_name = ?", (run,)
1453
+ )
1454
+ except sqlite3.OperationalError:
1455
+ pass
1456
+ source_conn.commit()
1457
+
1458
+ return True
1459
+
1460
+ @staticmethod
1461
+ def get_all_run_configs(project: str) -> dict[str, dict]:
1462
+ """Get configurations for all runs in a project."""
1463
+ db_path = SQLiteStorage.get_project_db_path(project)
1464
+ if not db_path.exists():
1465
+ return {}
1466
+
1467
+ with SQLiteStorage._get_connection(db_path) as conn:
1468
+ cursor = conn.cursor()
1469
+ try:
1470
+ cursor.execute(
1471
+ """
1472
+ SELECT run_name, config FROM configs
1473
+ """
1474
+ )
1475
+
1476
+ results = {}
1477
+ for row in cursor.fetchall():
1478
+ config = orjson.loads(row["config"])
1479
+ results[row["run_name"]] = deserialize_values(config)
1480
+ return results
1481
+ except sqlite3.OperationalError as e:
1482
+ if "no such table: configs" in str(e):
1483
+ return {}
1484
+ raise
1485
+
1486
+ @staticmethod
1487
+ def get_metric_values(
1488
+ project: str,
1489
+ run: str,
1490
+ metric_name: str,
1491
+ step: int | None = None,
1492
+ around_step: int | None = None,
1493
+ at_time: str | None = None,
1494
+ window: int | float | None = None,
1495
+ ) -> list[dict]:
1496
+ """Get values for a specific metric in a project/run with optional filtering.
1497
+
1498
+ Filtering modes:
1499
+ - step: return the single row at exactly this step
1500
+ - around_step + window: return rows where step is in [around_step - window, around_step + window]
1501
+ - at_time + window: return rows within ±window seconds of the ISO timestamp
1502
+ - No filters: return all rows
1503
+ """
1504
+ db_path = SQLiteStorage.get_project_db_path(project)
1505
+ if not db_path.exists():
1506
+ return []
1507
+
1508
+ with SQLiteStorage._get_connection(db_path) as conn:
1509
+ cursor = conn.cursor()
1510
+ query = "SELECT timestamp, step, metrics FROM metrics WHERE run_name = ?"
1511
+ params: list = [run]
1512
+
1513
+ if step is not None:
1514
+ query += " AND step = ?"
1515
+ params.append(step)
1516
+ elif around_step is not None and window is not None:
1517
+ query += " AND step >= ? AND step <= ?"
1518
+ params.extend([around_step - int(window), around_step + int(window)])
1519
+ elif at_time is not None and window is not None:
1520
+ query += (
1521
+ " AND timestamp >= datetime(?, '-' || ? || ' seconds')"
1522
+ " AND timestamp <= datetime(?, '+' || ? || ' seconds')"
1523
+ )
1524
+ params.extend([at_time, int(window), at_time, int(window)])
1525
+
1526
+ query += " ORDER BY timestamp"
1527
+ cursor.execute(query, params)
1528
+
1529
+ rows = cursor.fetchall()
1530
+ results = []
1531
+ for row in rows:
1532
+ metrics = orjson.loads(row["metrics"])
1533
+ metrics = deserialize_values(metrics)
1534
+ if metric_name in metrics:
1535
+ results.append(
1536
+ {
1537
+ "timestamp": row["timestamp"],
1538
+ "step": row["step"],
1539
+ "value": metrics[metric_name],
1540
+ }
1541
+ )
1542
+ return results
1543
+
1544
+ @staticmethod
1545
+ def get_snapshot(
1546
+ project: str,
1547
+ run: str,
1548
+ step: int | None = None,
1549
+ around_step: int | None = None,
1550
+ at_time: str | None = None,
1551
+ window: int | float | None = None,
1552
+ ) -> dict[str, list[dict]]:
1553
+ """Get all metrics at/around a point in time or step.
1554
+
1555
+ Returns a dict mapping metric names to lists of {timestamp, step, value}.
1556
+ """
1557
+ db_path = SQLiteStorage.get_project_db_path(project)
1558
+ if not db_path.exists():
1559
+ return {}
1560
+
1561
+ with SQLiteStorage._get_connection(db_path) as conn:
1562
+ cursor = conn.cursor()
1563
+ query = "SELECT timestamp, step, metrics FROM metrics WHERE run_name = ?"
1564
+ params: list = [run]
1565
+
1566
+ if step is not None:
1567
+ query += " AND step = ?"
1568
+ params.append(step)
1569
+ elif around_step is not None and window is not None:
1570
+ query += " AND step >= ? AND step <= ?"
1571
+ params.extend([around_step - int(window), around_step + int(window)])
1572
+ elif at_time is not None and window is not None:
1573
+ query += (
1574
+ " AND timestamp >= datetime(?, '-' || ? || ' seconds')"
1575
+ " AND timestamp <= datetime(?, '+' || ? || ' seconds')"
1576
+ )
1577
+ params.extend([at_time, int(window), at_time, int(window)])
1578
+
1579
+ query += " ORDER BY timestamp"
1580
+ cursor.execute(query, params)
1581
+
1582
+ result: dict[str, list[dict]] = {}
1583
+ for row in cursor.fetchall():
1584
+ metrics = orjson.loads(row["metrics"])
1585
+ metrics = deserialize_values(metrics)
1586
+ for key, value in metrics.items():
1587
+ if key not in result:
1588
+ result[key] = []
1589
+ result[key].append(
1590
+ {
1591
+ "timestamp": row["timestamp"],
1592
+ "step": row["step"],
1593
+ "value": value,
1594
+ }
1595
+ )
1596
+ return result
1597
+
1598
+ @staticmethod
1599
+ def get_all_metrics_for_run(project: str, run: str) -> list[str]:
1600
+ """Get all metric names for a specific project/run."""
1601
+ return SQLiteStorage._get_metric_names(
1602
+ project, run, "metrics", exclude_keys={"timestamp", "step"}
1603
+ )
1604
+
1605
+ @staticmethod
1606
+ def _get_metric_names(
1607
+ project: str, run: str, table: str, exclude_keys: set[str]
1608
+ ) -> list[str]:
1609
+ db_path = SQLiteStorage.get_project_db_path(project)
1610
+ if not db_path.exists():
1611
+ return []
1612
+
1613
+ with SQLiteStorage._get_connection(db_path) as conn:
1614
+ cursor = conn.cursor()
1615
+ try:
1616
+ cursor.execute(
1617
+ f"""
1618
+ SELECT metrics
1619
+ FROM {table}
1620
+ WHERE run_name = ?
1621
+ ORDER BY timestamp
1622
+ """,
1623
+ (run,),
1624
+ )
1625
+
1626
+ rows = cursor.fetchall()
1627
+ all_metrics = set()
1628
+ for row in rows:
1629
+ metrics = orjson.loads(row["metrics"])
1630
+ metrics = deserialize_values(metrics)
1631
+ for key in metrics.keys():
1632
+ if key not in exclude_keys:
1633
+ all_metrics.add(key)
1634
+ return sorted(list(all_metrics))
1635
+ except sqlite3.OperationalError as e:
1636
+ if f"no such table: {table}" in str(e):
1637
+ return []
1638
+ raise
1639
+
1640
+ @staticmethod
1641
+ def set_project_metadata(project: str, key: str, value: str) -> None:
1642
+ db_path = SQLiteStorage.init_db(project)
1643
+ with SQLiteStorage._get_process_lock(project):
1644
+ with SQLiteStorage._get_connection(db_path) as conn:
1645
+ conn.execute(
1646
+ "INSERT OR REPLACE INTO project_metadata (key, value) VALUES (?, ?)",
1647
+ (key, value),
1648
+ )
1649
+ conn.commit()
1650
+
1651
+ @staticmethod
1652
+ def get_project_metadata(project: str, key: str) -> str | None:
1653
+ db_path = SQLiteStorage.get_project_db_path(project)
1654
+ if not db_path.exists():
1655
+ return None
1656
+ with SQLiteStorage._get_connection(db_path) as conn:
1657
+ cursor = conn.cursor()
1658
+ try:
1659
+ cursor.execute(
1660
+ "SELECT value FROM project_metadata WHERE key = ?", (key,)
1661
+ )
1662
+ row = cursor.fetchone()
1663
+ return row[0] if row else None
1664
+ except sqlite3.OperationalError:
1665
+ return None
1666
+
1667
+ @staticmethod
1668
+ def get_space_id(project: str) -> str | None:
1669
+ return SQLiteStorage.get_project_metadata(project, "space_id")
1670
+
1671
+ @staticmethod
1672
+ def has_pending_data(project: str) -> bool:
1673
+ db_path = SQLiteStorage.get_project_db_path(project)
1674
+ if not db_path.exists():
1675
+ return False
1676
+ with SQLiteStorage._get_connection(db_path) as conn:
1677
+ cursor = conn.cursor()
1678
+ try:
1679
+ cursor.execute(
1680
+ "SELECT EXISTS(SELECT 1 FROM metrics WHERE space_id IS NOT NULL LIMIT 1)"
1681
+ )
1682
+ if cursor.fetchone()[0]:
1683
+ return True
1684
+ except sqlite3.OperationalError:
1685
+ pass
1686
+ try:
1687
+ cursor.execute(
1688
+ "SELECT EXISTS(SELECT 1 FROM system_metrics WHERE space_id IS NOT NULL LIMIT 1)"
1689
+ )
1690
+ if cursor.fetchone()[0]:
1691
+ return True
1692
+ except sqlite3.OperationalError:
1693
+ pass
1694
+ try:
1695
+ cursor.execute("SELECT EXISTS(SELECT 1 FROM pending_uploads LIMIT 1)")
1696
+ if cursor.fetchone()[0]:
1697
+ return True
1698
+ except sqlite3.OperationalError:
1699
+ pass
1700
+ return False
1701
+
1702
+ @staticmethod
1703
+ def get_pending_logs(project: str) -> dict | None:
1704
+ return SQLiteStorage._get_pending(
1705
+ project, "metrics", extra_fields=["step"], include_config=True
1706
+ )
1707
+
1708
+ @staticmethod
1709
+ def clear_pending_logs(project: str, metric_ids: list[int]) -> None:
1710
+ SQLiteStorage._clear_pending(project, "metrics", metric_ids)
1711
+
1712
+ @staticmethod
1713
+ def get_pending_system_logs(project: str) -> dict | None:
1714
+ return SQLiteStorage._get_pending(project, "system_metrics")
1715
+
1716
+ @staticmethod
1717
+ def _get_pending(
1718
+ project: str,
1719
+ table: str,
1720
+ extra_fields: list[str] | None = None,
1721
+ include_config: bool = False,
1722
+ ) -> dict | None:
1723
+ db_path = SQLiteStorage.get_project_db_path(project)
1724
+ if not db_path.exists():
1725
+ return None
1726
+ extra_cols = ", ".join(extra_fields) + ", " if extra_fields else ""
1727
+ with SQLiteStorage._get_connection(db_path) as conn:
1728
+ cursor = conn.cursor()
1729
+ try:
1730
+ cursor.execute(
1731
+ f"""SELECT id, timestamp, run_name, {extra_cols}metrics, log_id, space_id
1732
+ FROM {table} WHERE space_id IS NOT NULL"""
1733
+ )
1734
+ except sqlite3.OperationalError:
1735
+ return None
1736
+ rows = cursor.fetchall()
1737
+ if not rows:
1738
+ return None
1739
+ logs = []
1740
+ ids = []
1741
+ for row in rows:
1742
+ metrics = deserialize_values(orjson.loads(row["metrics"]))
1743
+ entry = {
1744
+ "project": project,
1745
+ "run": row["run_name"],
1746
+ "metrics": metrics,
1747
+ "timestamp": row["timestamp"],
1748
+ "log_id": row["log_id"],
1749
+ }
1750
+ for field in extra_fields or []:
1751
+ entry[field] = row[field]
1752
+ if include_config:
1753
+ entry["config"] = None
1754
+ logs.append(entry)
1755
+ ids.append(row["id"])
1756
+ return {"logs": logs, "ids": ids, "space_id": rows[0]["space_id"]}
1757
+
1758
+ @staticmethod
1759
+ def clear_pending_system_logs(project: str, metric_ids: list[int]) -> None:
1760
+ SQLiteStorage._clear_pending(project, "system_metrics", metric_ids)
1761
+
1762
+ @staticmethod
1763
+ def _clear_pending(project: str, table: str, ids: list[int]) -> None:
1764
+ if not ids:
1765
+ return
1766
+ db_path = SQLiteStorage.get_project_db_path(project)
1767
+ if not db_path.exists():
1768
+ return
1769
+ with SQLiteStorage._get_process_lock(project):
1770
+ with SQLiteStorage._get_connection(db_path) as conn:
1771
+ placeholders = ",".join("?" * len(ids))
1772
+ conn.execute(
1773
+ f"DELETE FROM {table} WHERE id IN ({placeholders})",
1774
+ ids,
1775
+ )
1776
+ conn.commit()
1777
+
1778
+ @staticmethod
1779
+ def get_pending_uploads(project: str) -> dict | None:
1780
+ db_path = SQLiteStorage.get_project_db_path(project)
1781
+ if not db_path.exists():
1782
+ return None
1783
+ with SQLiteStorage._get_connection(db_path) as conn:
1784
+ cursor = conn.cursor()
1785
+ try:
1786
+ cursor.execute(
1787
+ """SELECT id, space_id, run_name, step, file_path, relative_path
1788
+ FROM pending_uploads"""
1789
+ )
1790
+ except sqlite3.OperationalError:
1791
+ return None
1792
+ rows = cursor.fetchall()
1793
+ if not rows:
1794
+ return None
1795
+ uploads = []
1796
+ ids = []
1797
+ for row in rows:
1798
+ uploads.append(
1799
+ {
1800
+ "project": project,
1801
+ "run": row["run_name"],
1802
+ "step": row["step"],
1803
+ "file_path": row["file_path"],
1804
+ "relative_path": row["relative_path"],
1805
+ }
1806
+ )
1807
+ ids.append(row["id"])
1808
+ return {"uploads": uploads, "ids": ids, "space_id": rows[0]["space_id"]}
1809
+
1810
+ @staticmethod
1811
+ def clear_pending_uploads(project: str, upload_ids: list[int]) -> None:
1812
+ if not upload_ids:
1813
+ return
1814
+ db_path = SQLiteStorage.get_project_db_path(project)
1815
+ if not db_path.exists():
1816
+ return
1817
+ with SQLiteStorage._get_process_lock(project):
1818
+ with SQLiteStorage._get_connection(db_path) as conn:
1819
+ placeholders = ",".join("?" * len(upload_ids))
1820
+ conn.execute(
1821
+ f"DELETE FROM pending_uploads WHERE id IN ({placeholders})",
1822
+ upload_ids,
1823
+ )
1824
+ conn.commit()
1825
+
1826
+ @staticmethod
1827
+ def add_pending_upload(
1828
+ project: str,
1829
+ space_id: str,
1830
+ run_name: str | None,
1831
+ step: int | None,
1832
+ file_path: str,
1833
+ relative_path: str | None,
1834
+ ) -> None:
1835
+ db_path = SQLiteStorage.init_db(project)
1836
+ with SQLiteStorage._get_process_lock(project):
1837
+ with SQLiteStorage._get_connection(db_path) as conn:
1838
+ conn.execute(
1839
+ """INSERT INTO pending_uploads
1840
+ (space_id, run_name, step, file_path, relative_path, created_at)
1841
+ VALUES (?, ?, ?, ?, ?, ?)""",
1842
+ (
1843
+ space_id,
1844
+ run_name,
1845
+ step,
1846
+ file_path,
1847
+ relative_path,
1848
+ datetime.now(timezone.utc).isoformat(),
1849
+ ),
1850
+ )
1851
+ conn.commit()
1852
+
1853
+ @staticmethod
1854
+ def get_all_logs_for_sync(project: str) -> list[dict]:
1855
+ return SQLiteStorage._get_all_for_sync(
1856
+ project,
1857
+ "metrics",
1858
+ order_by="run_name, step",
1859
+ extra_fields=["step"],
1860
+ include_config=True,
1861
+ )
1862
+
1863
+ @staticmethod
1864
+ def get_all_system_logs_for_sync(project: str) -> list[dict]:
1865
+ return SQLiteStorage._get_all_for_sync(
1866
+ project, "system_metrics", order_by="run_name, timestamp"
1867
+ )
1868
+
1869
+ @staticmethod
1870
+ def _get_all_for_sync(
1871
+ project: str,
1872
+ table: str,
1873
+ order_by: str,
1874
+ extra_fields: list[str] | None = None,
1875
+ include_config: bool = False,
1876
+ ) -> list[dict]:
1877
+ db_path = SQLiteStorage.get_project_db_path(project)
1878
+ if not db_path.exists():
1879
+ return []
1880
+ extra_cols = ", ".join(extra_fields) + ", " if extra_fields else ""
1881
+ with SQLiteStorage._get_connection(db_path) as conn:
1882
+ cursor = conn.cursor()
1883
+ try:
1884
+ cursor.execute(
1885
+ f"""SELECT timestamp, run_name, {extra_cols}metrics, log_id
1886
+ FROM {table} ORDER BY {order_by}"""
1887
+ )
1888
+ except sqlite3.OperationalError:
1889
+ return []
1890
+ rows = cursor.fetchall()
1891
+ results = []
1892
+ for row in rows:
1893
+ metrics = deserialize_values(orjson.loads(row["metrics"]))
1894
+ entry = {
1895
+ "project": project,
1896
+ "run": row["run_name"],
1897
+ "metrics": metrics,
1898
+ "timestamp": row["timestamp"],
1899
+ "log_id": row["log_id"],
1900
+ }
1901
+ for field in extra_fields or []:
1902
+ entry[field] = row[field]
1903
+ if include_config:
1904
+ entry["config"] = None
1905
+ results.append(entry)
1906
+ return results
trackio/table.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Any, Literal
3
+
4
+ from pandas import DataFrame
5
+
6
+ from trackio.media.media import TrackioMedia
7
+ from trackio.utils import MEDIA_DIR
8
+
9
+
10
+ class Table:
11
+ """
12
+ Initializes a Table object.
13
+
14
+ Tables can be used to log tabular data including images, numbers, and text.
15
+
16
+ Args:
17
+ columns (`list[str]`, *optional*):
18
+ Names of the columns in the table. Optional if `data` is provided. Not
19
+ expected if `dataframe` is provided. Currently ignored.
20
+ data (`list[list[Any]]`, *optional*):
21
+ 2D row-oriented array of values. Each value can be a number, a string
22
+ (treated as Markdown and truncated if too long), or a `Trackio.Image` or
23
+ list of `Trackio.Image` objects.
24
+ dataframe (`pandas.DataFrame`, *optional*):
25
+ DataFrame used to create the table. When set, `data` and `columns`
26
+ arguments are ignored.
27
+ rows (`list[list[Any]]`, *optional*):
28
+ Currently ignored.
29
+ optional (`bool` or `list[bool]`, *optional*, defaults to `True`):
30
+ Currently ignored.
31
+ allow_mixed_types (`bool`, *optional*, defaults to `False`):
32
+ Currently ignored.
33
+ log_mode: (`Literal["IMMUTABLE", "MUTABLE", "INCREMENTAL"]` or `None`, *optional*, defaults to `"IMMUTABLE"`):
34
+ Currently ignored.
35
+ """
36
+
37
+ TYPE = "trackio.table"
38
+
39
+ def __init__(
40
+ self,
41
+ columns: list[str] | None = None,
42
+ data: list[list[Any]] | None = None,
43
+ dataframe: DataFrame | None = None,
44
+ rows: list[list[Any]] | None = None,
45
+ optional: bool | list[bool] = True,
46
+ allow_mixed_types: bool = False,
47
+ log_mode: Literal["IMMUTABLE", "MUTABLE", "INCREMENTAL"] | None = "IMMUTABLE",
48
+ ):
49
+ # TODO: implement support for columns, dtype, optional, allow_mixed_types, and log_mode.
50
+ # for now (like `rows`) they are included for API compat but don't do anything.
51
+ if dataframe is None:
52
+ self.data = DataFrame(data) if data is not None else DataFrame()
53
+ else:
54
+ self.data = dataframe
55
+
56
+ def _has_media_objects(self, dataframe: DataFrame) -> bool:
57
+ """Check if dataframe contains any TrackioMedia objects or lists of TrackioMedia objects."""
58
+ for col in dataframe.columns:
59
+ if dataframe[col].apply(lambda x: isinstance(x, TrackioMedia)).any():
60
+ return True
61
+ if (
62
+ dataframe[col]
63
+ .apply(
64
+ lambda x: (
65
+ isinstance(x, list)
66
+ and len(x) > 0
67
+ and isinstance(x[0], TrackioMedia)
68
+ )
69
+ )
70
+ .any()
71
+ ):
72
+ return True
73
+ return False
74
+
75
+ def _process_data(self, project: str, run: str, step: int = 0):
76
+ """Convert dataframe to dict format, processing any TrackioMedia objects if present."""
77
+ df = self.data
78
+ if not self._has_media_objects(df):
79
+ return df.to_dict(orient="records")
80
+
81
+ processed_df = df.copy()
82
+ for col in processed_df.columns:
83
+ for idx in processed_df.index:
84
+ value = processed_df.at[idx, col]
85
+ if isinstance(value, TrackioMedia):
86
+ value._save(project, run, step)
87
+ processed_df.at[idx, col] = value._to_dict()
88
+ if (
89
+ isinstance(value, list)
90
+ and len(value) > 0
91
+ and isinstance(value[0], TrackioMedia)
92
+ ):
93
+ [v._save(project, run, step) for v in value]
94
+ processed_df.at[idx, col] = [v._to_dict() for v in value]
95
+
96
+ return processed_df.to_dict(orient="records")
97
+
98
+ @staticmethod
99
+ def to_display_format(table_data: list[dict]) -> list[dict]:
100
+ """
101
+ Converts stored table data to display format for UI rendering.
102
+
103
+ Note:
104
+ This does not use the `self.data` attribute, but instead uses the
105
+ `table_data` parameter, which is what the UI receives.
106
+
107
+ Args:
108
+ table_data (`list[dict]`):
109
+ List of dictionaries representing table rows (from stored `_value`).
110
+
111
+ Returns:
112
+ `list[dict]`: Table data with images converted to markdown syntax and long
113
+ text truncated.
114
+ """
115
+ truncate_length = int(os.getenv("TRACKIO_TABLE_TRUNCATE_LENGTH", "250"))
116
+
117
+ def convert_image_to_markdown(image_data: dict) -> str:
118
+ relative_path = image_data.get("file_path", "")
119
+ caption = image_data.get("caption", "")
120
+ absolute_path = MEDIA_DIR / relative_path
121
+ return f'<img src="/gradio_api/file={absolute_path}" alt="{caption}" />'
122
+
123
+ processed_data = []
124
+ for row in table_data:
125
+ processed_row = {}
126
+ for key, value in row.items():
127
+ if isinstance(value, dict) and value.get("_type") == "trackio.image":
128
+ processed_row[key] = convert_image_to_markdown(value)
129
+ elif (
130
+ isinstance(value, list)
131
+ and len(value) > 0
132
+ and isinstance(value[0], dict)
133
+ and value[0].get("_type") == "trackio.image"
134
+ ):
135
+ # This assumes that if the first item is an image, all items are images. Ok for now since we don't support mixed types in a single cell.
136
+ processed_row[key] = (
137
+ '<div style="display: flex; gap: 10px;">'
138
+ + "".join([convert_image_to_markdown(item) for item in value])
139
+ + "</div>"
140
+ )
141
+ elif isinstance(value, str) and len(value) > truncate_length:
142
+ truncated = value[:truncate_length]
143
+ full_text = value.replace("<", "&lt;").replace(">", "&gt;")
144
+ processed_row[key] = (
145
+ f'<details style="display: inline;">'
146
+ f'<summary style="display: inline; cursor: pointer;">{truncated}…<span><em>(truncated, click to expand)</em></span></summary>'
147
+ f'<div style="margin-top: 10px; padding: 10px; background: #f5f5f5; border-radius: 4px; max-height: 400px; overflow: auto;">'
148
+ f'<pre style="white-space: pre-wrap; word-wrap: break-word; margin: 0;">{full_text}</pre>'
149
+ f"</div>"
150
+ f"</details>"
151
+ )
152
+ else:
153
+ processed_row[key] = value
154
+ processed_data.append(processed_row)
155
+ return processed_data
156
+
157
+ def _to_dict(self, project: str, run: str, step: int = 0):
158
+ """
159
+ Converts the table to a dictionary representation.
160
+
161
+ Args:
162
+ project (`str`):
163
+ Project name for saving media files.
164
+ run (`str`):
165
+ Run name for saving media files.
166
+ step (`int`, *optional*, defaults to `0`):
167
+ Step number for saving media files.
168
+ """
169
+ data = self._process_data(project, run, step)
170
+ return {
171
+ "_type": self.TYPE,
172
+ "_value": data,
173
+ }
trackio/typehints.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, TypedDict
2
+
3
+ from gradio import FileData
4
+
5
+
6
+ class LogEntry(TypedDict, total=False):
7
+ project: str
8
+ run: str
9
+ metrics: dict[str, Any]
10
+ step: int | None
11
+ config: dict[str, Any] | None
12
+ log_id: str | None
13
+
14
+
15
+ class SystemLogEntry(TypedDict, total=False):
16
+ project: str
17
+ run: str
18
+ metrics: dict[str, Any]
19
+ timestamp: str
20
+ log_id: str | None
21
+
22
+
23
+ class AlertEntry(TypedDict, total=False):
24
+ project: str
25
+ run: str
26
+ title: str
27
+ text: str | None
28
+ level: str
29
+ step: int | None
30
+ timestamp: str
31
+ alert_id: str | None
32
+
33
+
34
+ class UploadEntry(TypedDict):
35
+ project: str
36
+ run: str | None
37
+ step: int | None
38
+ relative_path: str | None
39
+ uploaded_file: FileData
trackio/utils.py ADDED
@@ -0,0 +1,933 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import re
4
+ import secrets
5
+ import time
6
+ import warnings
7
+ from datetime import datetime, timezone
8
+ from functools import lru_cache
9
+ from pathlib import Path
10
+ from typing import TYPE_CHECKING
11
+ from urllib.parse import urlencode
12
+
13
+ import huggingface_hub
14
+ import numpy as np
15
+ import pandas as pd
16
+ from huggingface_hub.constants import HF_HOME
17
+
18
+ if TYPE_CHECKING:
19
+ from trackio.commit_scheduler import CommitScheduler
20
+ from trackio.dummy_commit_scheduler import DummyCommitScheduler
21
+
22
+ RESERVED_KEYS = ["project", "run", "timestamp", "step", "time", "metrics"]
23
+
24
+ TRACKIO_LOGO_DIR = Path(__file__).parent / "assets"
25
+
26
+
27
+ def get_logo_urls() -> dict[str, str]:
28
+ """Get logo URLs from environment variables or use defaults."""
29
+ light_url = os.environ.get(
30
+ "TRACKIO_LOGO_LIGHT_URL",
31
+ f"/gradio_api/file={TRACKIO_LOGO_DIR}/trackio_logo_type_light_transparent.png",
32
+ )
33
+ dark_url = os.environ.get(
34
+ "TRACKIO_LOGO_DARK_URL",
35
+ f"/gradio_api/file={TRACKIO_LOGO_DIR}/trackio_logo_type_dark_transparent.png",
36
+ )
37
+ return {"light": light_url, "dark": dark_url}
38
+
39
+
40
+ def order_metrics_by_plot_preference(metrics: list[str]) -> tuple[list[str], dict]:
41
+ """
42
+ Order metrics based on TRACKIO_PLOT_ORDER environment variable and group them.
43
+
44
+ Args:
45
+ metrics: List of metric names to order and group
46
+
47
+ Returns:
48
+ Tuple of (ordered_group_names, grouped_metrics_dict)
49
+ """
50
+ plot_order_env = os.environ.get("TRACKIO_PLOT_ORDER", "")
51
+ if not plot_order_env.strip():
52
+ plot_order = []
53
+ else:
54
+ plot_order = [
55
+ item.strip() for item in plot_order_env.split(",") if item.strip()
56
+ ]
57
+
58
+ def get_metric_priority(metric: str) -> tuple[int, int, str]:
59
+ if not plot_order:
60
+ return (float("inf"), float("inf"), metric)
61
+
62
+ group_prefix = metric.split("/")[0] if "/" in metric else "charts"
63
+ no_match_priority = len(plot_order)
64
+
65
+ group_priority = no_match_priority
66
+ for i, pattern in enumerate(plot_order):
67
+ pattern_group = pattern.split("/")[0] if "/" in pattern else "charts"
68
+ if pattern_group == group_prefix:
69
+ group_priority = i
70
+ break
71
+
72
+ within_group_priority = no_match_priority
73
+ for i, pattern in enumerate(plot_order):
74
+ if pattern == metric:
75
+ within_group_priority = i
76
+ break
77
+ elif pattern.endswith("/*") and within_group_priority == no_match_priority:
78
+ pattern_prefix = pattern[:-2]
79
+ if metric.startswith(pattern_prefix + "/"):
80
+ within_group_priority = i + len(plot_order)
81
+
82
+ return (group_priority, within_group_priority, metric)
83
+
84
+ result = {}
85
+ for metric in metrics:
86
+ if "/" not in metric:
87
+ if "charts" not in result:
88
+ result["charts"] = {"direct_metrics": [], "subgroups": {}}
89
+ result["charts"]["direct_metrics"].append(metric)
90
+ else:
91
+ parts = metric.split("/")
92
+ main_prefix = parts[0]
93
+ if main_prefix not in result:
94
+ result[main_prefix] = {"direct_metrics": [], "subgroups": {}}
95
+ if len(parts) == 2:
96
+ result[main_prefix]["direct_metrics"].append(metric)
97
+ else:
98
+ subprefix = parts[1]
99
+ if subprefix not in result[main_prefix]["subgroups"]:
100
+ result[main_prefix]["subgroups"][subprefix] = []
101
+ result[main_prefix]["subgroups"][subprefix].append(metric)
102
+
103
+ for group_data in result.values():
104
+ group_data["direct_metrics"].sort(key=get_metric_priority)
105
+ for subgroup_name in group_data["subgroups"]:
106
+ group_data["subgroups"][subgroup_name].sort(key=get_metric_priority)
107
+
108
+ if "charts" in result and not result["charts"]["direct_metrics"]:
109
+ del result["charts"]
110
+
111
+ def get_group_priority(group_name: str) -> tuple[int, str]:
112
+ if not plot_order:
113
+ return (float("inf"), group_name)
114
+
115
+ min_priority = len(plot_order)
116
+ for i, pattern in enumerate(plot_order):
117
+ pattern_group = pattern.split("/")[0] if "/" in pattern else "charts"
118
+ if pattern_group == group_name:
119
+ min_priority = min(min_priority, i)
120
+ return (min_priority, group_name)
121
+
122
+ ordered_groups = sorted(result.keys(), key=get_group_priority)
123
+
124
+ return ordered_groups, result
125
+
126
+
127
+ def persistent_storage_enabled() -> bool:
128
+ return (
129
+ os.environ.get("PERSISTANT_STORAGE_ENABLED") == "true"
130
+ ) # typo in the name of the environment variable
131
+
132
+
133
+ def _get_trackio_dir() -> Path:
134
+ if persistent_storage_enabled():
135
+ return Path("/data/trackio")
136
+ if os.environ.get("TRACKIO_DIR"):
137
+ return Path(os.environ.get("TRACKIO_DIR"))
138
+ return Path(HF_HOME) / "trackio"
139
+
140
+
141
+ TRACKIO_DIR = _get_trackio_dir()
142
+ MEDIA_DIR = TRACKIO_DIR / "media"
143
+
144
+
145
+ def get_or_create_project_hash(project: str) -> str:
146
+ hash_path = TRACKIO_DIR / f"{project}.hash"
147
+ if hash_path.exists():
148
+ return hash_path.read_text().strip()
149
+ hash_value = secrets.token_urlsafe(8)
150
+ TRACKIO_DIR.mkdir(parents=True, exist_ok=True)
151
+ hash_path.write_text(hash_value)
152
+ return hash_value
153
+
154
+
155
+ def generate_readable_name(used_names: list[str], space_id: str | None = None) -> str:
156
+ """
157
+ Generates a random, readable name like "dainty-sunset-0".
158
+ If space_id is provided, generates username-timestamp format instead.
159
+ """
160
+ if space_id is not None:
161
+ username = _get_default_namespace()
162
+ timestamp = int(time.time())
163
+ return f"{username}-{timestamp}"
164
+ adjectives = [
165
+ "dainty",
166
+ "brave",
167
+ "calm",
168
+ "eager",
169
+ "fancy",
170
+ "gentle",
171
+ "happy",
172
+ "jolly",
173
+ "kind",
174
+ "lively",
175
+ "merry",
176
+ "nice",
177
+ "proud",
178
+ "quick",
179
+ "hugging",
180
+ "silly",
181
+ "tidy",
182
+ "witty",
183
+ "zealous",
184
+ "bright",
185
+ "shy",
186
+ "bold",
187
+ "clever",
188
+ "daring",
189
+ "elegant",
190
+ "faithful",
191
+ "graceful",
192
+ "honest",
193
+ "inventive",
194
+ "jovial",
195
+ "keen",
196
+ "lucky",
197
+ "modest",
198
+ "noble",
199
+ "optimistic",
200
+ "patient",
201
+ "quirky",
202
+ "resourceful",
203
+ "sincere",
204
+ "thoughtful",
205
+ "upbeat",
206
+ "valiant",
207
+ "warm",
208
+ "youthful",
209
+ "zesty",
210
+ "adventurous",
211
+ "breezy",
212
+ "cheerful",
213
+ "delightful",
214
+ "energetic",
215
+ "fearless",
216
+ "glad",
217
+ "hopeful",
218
+ "imaginative",
219
+ "joyful",
220
+ "kindly",
221
+ "luminous",
222
+ "mysterious",
223
+ "neat",
224
+ "outgoing",
225
+ "playful",
226
+ "radiant",
227
+ "spirited",
228
+ "tranquil",
229
+ "unique",
230
+ "vivid",
231
+ "wise",
232
+ "zany",
233
+ "artful",
234
+ "bubbly",
235
+ "charming",
236
+ "dazzling",
237
+ "earnest",
238
+ "festive",
239
+ "gentlemanly",
240
+ "hearty",
241
+ "intrepid",
242
+ "jubilant",
243
+ "knightly",
244
+ "lively",
245
+ "magnetic",
246
+ "nimble",
247
+ "orderly",
248
+ "peaceful",
249
+ "quick-witted",
250
+ "robust",
251
+ "sturdy",
252
+ "trusty",
253
+ "upstanding",
254
+ "vibrant",
255
+ "whimsical",
256
+ ]
257
+ nouns = [
258
+ "sunset",
259
+ "forest",
260
+ "river",
261
+ "mountain",
262
+ "breeze",
263
+ "meadow",
264
+ "ocean",
265
+ "valley",
266
+ "sky",
267
+ "field",
268
+ "cloud",
269
+ "star",
270
+ "rain",
271
+ "leaf",
272
+ "stone",
273
+ "flower",
274
+ "bird",
275
+ "tree",
276
+ "wave",
277
+ "trail",
278
+ "island",
279
+ "desert",
280
+ "hill",
281
+ "lake",
282
+ "pond",
283
+ "grove",
284
+ "canyon",
285
+ "reef",
286
+ "bay",
287
+ "peak",
288
+ "glade",
289
+ "marsh",
290
+ "cliff",
291
+ "dune",
292
+ "spring",
293
+ "brook",
294
+ "cave",
295
+ "plain",
296
+ "ridge",
297
+ "wood",
298
+ "blossom",
299
+ "petal",
300
+ "root",
301
+ "branch",
302
+ "seed",
303
+ "acorn",
304
+ "pine",
305
+ "willow",
306
+ "cedar",
307
+ "elm",
308
+ "falcon",
309
+ "eagle",
310
+ "sparrow",
311
+ "robin",
312
+ "owl",
313
+ "finch",
314
+ "heron",
315
+ "crane",
316
+ "duck",
317
+ "swan",
318
+ "fox",
319
+ "wolf",
320
+ "bear",
321
+ "deer",
322
+ "moose",
323
+ "otter",
324
+ "beaver",
325
+ "lynx",
326
+ "hare",
327
+ "badger",
328
+ "butterfly",
329
+ "bee",
330
+ "ant",
331
+ "beetle",
332
+ "dragonfly",
333
+ "firefly",
334
+ "ladybug",
335
+ "moth",
336
+ "spider",
337
+ "worm",
338
+ "coral",
339
+ "kelp",
340
+ "shell",
341
+ "pebble",
342
+ "face",
343
+ "boulder",
344
+ "cobble",
345
+ "sand",
346
+ "wavelet",
347
+ "tide",
348
+ "current",
349
+ "mist",
350
+ ]
351
+ number = 0
352
+ name = f"{adjectives[0]}-{nouns[0]}-{number}"
353
+ while name in used_names:
354
+ number += 1
355
+ adjective = adjectives[number % len(adjectives)]
356
+ noun = nouns[number % len(nouns)]
357
+ name = f"{adjective}-{noun}-{number}"
358
+ return name
359
+
360
+
361
+ def is_in_notebook():
362
+ """
363
+ Detect if code is running in a notebook environment (Jupyter, Colab, etc.).
364
+ """
365
+ try:
366
+ from IPython import get_ipython
367
+
368
+ if get_ipython() is not None:
369
+ return get_ipython().__class__.__name__ in [
370
+ "ZMQInteractiveShell", # Jupyter notebook/lab
371
+ "Shell", # IPython terminal
372
+ ] or "google.colab" in str(get_ipython())
373
+ except ImportError:
374
+ pass
375
+ return False
376
+
377
+
378
+ def block_main_thread_until_keyboard_interrupt():
379
+ try:
380
+ while True:
381
+ time.sleep(0.1)
382
+ except (KeyboardInterrupt, OSError):
383
+ print("Keyboard interruption in main thread... closing dashboard.")
384
+
385
+
386
+ def simplify_column_names(columns: list[str]) -> dict[str, str]:
387
+ """
388
+ Simplifies column names to first 10 alphanumeric or "/" characters with unique suffixes.
389
+
390
+ Args:
391
+ columns: List of original column names
392
+
393
+ Returns:
394
+ Dictionary mapping original column names to simplified names
395
+ """
396
+ simplified_names = {}
397
+ used_names = set()
398
+
399
+ for col in columns:
400
+ alphanumeric = re.sub(r"[^a-zA-Z0-9/]", "", col)
401
+ base_name = alphanumeric[:10] if alphanumeric else f"col_{len(used_names)}"
402
+
403
+ final_name = base_name
404
+ suffix = 1
405
+ while final_name in used_names:
406
+ final_name = f"{base_name}_{suffix}"
407
+ suffix += 1
408
+
409
+ simplified_names[col] = final_name
410
+ used_names.add(final_name)
411
+
412
+ return simplified_names
413
+
414
+
415
+ def print_dashboard_instructions(project: str) -> None:
416
+ """
417
+ Prints instructions for viewing the Trackio dashboard.
418
+
419
+ Args:
420
+ project: The name of the project to show dashboard for.
421
+ """
422
+ ORANGE = "\033[38;5;208m"
423
+ BOLD = "\033[1m"
424
+ RESET = "\033[0m"
425
+
426
+ print("* View dashboard by running in your terminal:")
427
+ print(f'{BOLD}{ORANGE}trackio show --project "{project}"{RESET}')
428
+ print(f'* or by running in Python: trackio.show(project="{project}")')
429
+
430
+
431
+ def preprocess_space_and_dataset_ids(
432
+ space_id: str | None,
433
+ dataset_id: str | None,
434
+ bucket_id: str | None = None,
435
+ ) -> tuple[str | None, str | None, str | None]:
436
+ """
437
+ Preprocesses the Space and Bucket names to ensure they are valid
438
+ "username/name" format. When space_id is provided and bucket_id is not
439
+ explicitly set, auto-generates a bucket_id.
440
+ """
441
+ if space_id is not None and "/" not in space_id:
442
+ username = _get_default_namespace()
443
+ space_id = f"{username}/{space_id}"
444
+ if dataset_id is not None:
445
+ warnings.warn(
446
+ "`dataset_id` is deprecated. Use `bucket_id` instead.",
447
+ DeprecationWarning,
448
+ stacklevel=3,
449
+ )
450
+ if dataset_id is not None and "/" not in dataset_id:
451
+ username = _get_default_namespace()
452
+ dataset_id = f"{username}/{dataset_id}"
453
+ if bucket_id is not None and "/" not in bucket_id:
454
+ username = _get_default_namespace()
455
+ bucket_id = f"{username}/{bucket_id}"
456
+ if space_id is not None and dataset_id is None and bucket_id is None:
457
+ bucket_id = f"{space_id}-bucket"
458
+ return space_id, dataset_id, bucket_id
459
+
460
+
461
+ def fibo():
462
+ """Generator for Fibonacci backoff: 1, 1, 2, 3, 5, 8, ..."""
463
+ a, b = 1, 1
464
+ while True:
465
+ yield a
466
+ a, b = b, a + b
467
+
468
+
469
+ def format_timestamp(timestamp_str):
470
+ """Convert ISO timestamp to human-readable format like '3 minutes ago'."""
471
+ if not timestamp_str or pd.isna(timestamp_str):
472
+ return "Unknown"
473
+
474
+ try:
475
+ created_time = datetime.fromisoformat(timestamp_str.replace("Z", "+00:00"))
476
+ if created_time.tzinfo is None:
477
+ created_time = created_time.replace(tzinfo=timezone.utc)
478
+
479
+ now = datetime.now(timezone.utc)
480
+ diff = now - created_time
481
+
482
+ seconds = int(diff.total_seconds())
483
+ if seconds < 60:
484
+ return "Just now"
485
+ elif seconds < 3600:
486
+ minutes = seconds // 60
487
+ return f"{minutes} minute{'s' if minutes != 1 else ''} ago"
488
+ elif seconds < 86400:
489
+ hours = seconds // 3600
490
+ return f"{hours} hour{'s' if hours != 1 else ''} ago"
491
+ else:
492
+ days = seconds // 86400
493
+ return f"{days} day{'s' if days != 1 else ''} ago"
494
+ except Exception:
495
+ return "Unknown"
496
+
497
+
498
+ DEFAULT_COLOR_PALETTE = [
499
+ "#A8769B",
500
+ "#E89957",
501
+ "#3B82F6",
502
+ "#10B981",
503
+ "#EF4444",
504
+ "#8B5CF6",
505
+ "#14B8A6",
506
+ "#F59E0B",
507
+ "#EC4899",
508
+ "#06B6D4",
509
+ ]
510
+
511
+
512
+ def get_color_palette() -> list[str]:
513
+ """Get the color palette from environment variable or use default."""
514
+ env_palette = os.environ.get("TRACKIO_COLOR_PALETTE")
515
+ if env_palette:
516
+ return [color.strip() for color in env_palette.split(",")]
517
+ return DEFAULT_COLOR_PALETTE
518
+
519
+
520
+ def get_color_mapping(
521
+ runs: list[str], smoothing: bool, color_palette: list[str] | None = None
522
+ ) -> dict[str, str]:
523
+ """Generate color mapping for runs, with transparency for original data when smoothing is enabled."""
524
+ if color_palette is None:
525
+ color_palette = get_color_palette()
526
+
527
+ color_map = {}
528
+
529
+ for i, run in enumerate(runs):
530
+ base_color = color_palette[i % len(color_palette)]
531
+
532
+ if smoothing:
533
+ color_map[run] = base_color + "4D"
534
+ color_map[f"{run}_smoothed"] = base_color
535
+ else:
536
+ color_map[run] = base_color
537
+
538
+ return color_map
539
+
540
+
541
+ def downsample(
542
+ df: pd.DataFrame,
543
+ x: str,
544
+ y: str,
545
+ color: str | None,
546
+ x_lim: tuple[float | None, float | None] | None = None,
547
+ ) -> tuple[pd.DataFrame, tuple[float, float] | None]:
548
+ """
549
+ Downsample the dataframe to reduce the number of points plotted.
550
+ Also updates the x-axis limits to the data min/max if either of the x-axis limits are None.
551
+
552
+ Args:
553
+ df: The dataframe to downsample.
554
+ x: The column name to use for the x-axis.
555
+ y: The column name to use for the y-axis.
556
+ color: The column name to use for the color.
557
+ x_lim: The x-axis limits to use.
558
+
559
+ Returns:
560
+ A tuple containing the downsampled dataframe and the updated x-axis limits.
561
+ """
562
+ if df.empty:
563
+ if x_lim is not None:
564
+ x_lim = (x_lim[0] or 0, x_lim[1] or 0)
565
+ return df, x_lim
566
+
567
+ columns_to_keep = [x, y]
568
+ if color is not None and color in df.columns:
569
+ columns_to_keep.append(color)
570
+ df = df[columns_to_keep].copy()
571
+
572
+ data_x_min = df[x].min()
573
+ data_x_max = df[x].max()
574
+
575
+ if x_lim is not None:
576
+ x_min, x_max = x_lim
577
+ if x_min is None:
578
+ x_min = data_x_min
579
+ if x_max is None:
580
+ x_max = data_x_max
581
+ updated_x_lim = (x_min, x_max)
582
+ else:
583
+ updated_x_lim = None
584
+
585
+ n_bins = 100
586
+
587
+ if color is not None and color in df.columns:
588
+ groups = df.groupby(color)
589
+ else:
590
+ groups = [(None, df)]
591
+
592
+ downsampled_indices = []
593
+
594
+ for _, group_df in groups:
595
+ if group_df.empty:
596
+ continue
597
+
598
+ group_df = group_df.sort_values(x)
599
+
600
+ if updated_x_lim is not None:
601
+ x_min, x_max = updated_x_lim
602
+ before_point = group_df[group_df[x] < x_min].tail(1)
603
+ after_point = group_df[group_df[x] > x_max].head(1)
604
+ group_df = group_df[(group_df[x] >= x_min) & (group_df[x] <= x_max)]
605
+ else:
606
+ before_point = after_point = None
607
+ x_min = group_df[x].min()
608
+ x_max = group_df[x].max()
609
+
610
+ if before_point is not None and not before_point.empty:
611
+ downsampled_indices.extend(before_point.index.tolist())
612
+ if after_point is not None and not after_point.empty:
613
+ downsampled_indices.extend(after_point.index.tolist())
614
+
615
+ if group_df.empty:
616
+ continue
617
+
618
+ if x_min == x_max:
619
+ min_y_idx = group_df[y].idxmin()
620
+ max_y_idx = group_df[y].idxmax()
621
+ if min_y_idx != max_y_idx:
622
+ downsampled_indices.extend([min_y_idx, max_y_idx])
623
+ else:
624
+ downsampled_indices.append(min_y_idx)
625
+ continue
626
+
627
+ if len(group_df) < 500:
628
+ downsampled_indices.extend(group_df.index.tolist())
629
+ continue
630
+
631
+ bins = np.linspace(x_min, x_max, n_bins + 1)
632
+ group_df["bin"] = pd.cut(
633
+ group_df[x], bins=bins, labels=False, include_lowest=True
634
+ )
635
+
636
+ for bin_idx in group_df["bin"].dropna().unique():
637
+ bin_data = group_df[group_df["bin"] == bin_idx]
638
+ if bin_data.empty:
639
+ continue
640
+
641
+ min_y_idx = bin_data[y].idxmin()
642
+ max_y_idx = bin_data[y].idxmax()
643
+
644
+ downsampled_indices.append(min_y_idx)
645
+ if min_y_idx != max_y_idx:
646
+ downsampled_indices.append(max_y_idx)
647
+
648
+ unique_indices = list(set(downsampled_indices))
649
+
650
+ downsampled_df = df.loc[unique_indices].copy()
651
+
652
+ if color is not None:
653
+ downsampled_df = (
654
+ downsampled_df.groupby(color, sort=False)[downsampled_df.columns]
655
+ .apply(lambda group: group.sort_values(x))
656
+ .reset_index(drop=True)
657
+ )
658
+ else:
659
+ downsampled_df = downsampled_df.sort_values(x).reset_index(drop=True)
660
+
661
+ downsampled_df = downsampled_df.drop(columns=["bin"], errors="ignore")
662
+
663
+ return downsampled_df, updated_x_lim
664
+
665
+
666
+ def sort_metrics_by_prefix(metrics: list[str]) -> list[str]:
667
+ """
668
+ Sort metrics by grouping prefixes together for dropdown/list display.
669
+ Metrics without prefixes come first, then grouped by prefix.
670
+
671
+ Args:
672
+ metrics: List of metric names
673
+
674
+ Returns:
675
+ List of metric names sorted by prefix
676
+
677
+ Example:
678
+ Input: ["train/loss", "loss", "train/acc", "val/loss"]
679
+ Output: ["loss", "train/acc", "train/loss", "val/loss"]
680
+ """
681
+ groups = group_metrics_by_prefix(metrics)
682
+ result = []
683
+
684
+ if "charts" in groups:
685
+ result.extend(groups["charts"])
686
+
687
+ for group_name in sorted(groups.keys()):
688
+ if group_name != "charts":
689
+ result.extend(groups[group_name])
690
+
691
+ return result
692
+
693
+
694
+ def group_metrics_by_prefix(metrics: list[str]) -> dict[str, list[str]]:
695
+ """
696
+ Group metrics by their prefix. Metrics without prefix go to 'charts' group.
697
+
698
+ Args:
699
+ metrics: List of metric names
700
+
701
+ Returns:
702
+ Dictionary with prefix names as keys and lists of metrics as values
703
+
704
+ Example:
705
+ Input: ["loss", "accuracy", "train/loss", "train/acc", "val/loss"]
706
+ Output: {
707
+ "charts": ["loss", "accuracy"],
708
+ "train": ["train/loss", "train/acc"],
709
+ "val": ["val/loss"]
710
+ }
711
+ """
712
+ no_prefix = []
713
+ with_prefix = []
714
+
715
+ for metric in metrics:
716
+ if "/" in metric:
717
+ with_prefix.append(metric)
718
+ else:
719
+ no_prefix.append(metric)
720
+
721
+ no_prefix.sort()
722
+
723
+ prefix_groups = {}
724
+ for metric in with_prefix:
725
+ prefix = metric.split("/")[0]
726
+ if prefix not in prefix_groups:
727
+ prefix_groups[prefix] = []
728
+ prefix_groups[prefix].append(metric)
729
+
730
+ for prefix in prefix_groups:
731
+ prefix_groups[prefix].sort()
732
+
733
+ groups = {}
734
+ if no_prefix:
735
+ groups["charts"] = no_prefix
736
+
737
+ for prefix in sorted(prefix_groups.keys()):
738
+ groups[prefix] = prefix_groups[prefix]
739
+
740
+ return groups
741
+
742
+
743
+ def get_sync_status(scheduler: "CommitScheduler | DummyCommitScheduler") -> int | None:
744
+ """Get the sync status from the CommitScheduler in an integer number of minutes, or None if not synced yet."""
745
+ if getattr(
746
+ scheduler, "last_push_time", None
747
+ ): # DummyCommitScheduler doesn't have last_push_time
748
+ time_diff = time.time() - scheduler.last_push_time
749
+ return int(time_diff / 60)
750
+ else:
751
+ return None
752
+
753
+
754
+ def generate_share_url(
755
+ project: str,
756
+ metrics: str,
757
+ selected_runs: list = None,
758
+ hide_headers: bool = False,
759
+ ) -> str:
760
+ """Generate the shareable Space URL based on current settings."""
761
+ space_host = os.environ.get("SPACE_HOST", "")
762
+ if not space_host:
763
+ return ""
764
+
765
+ params: dict[str, str] = {}
766
+
767
+ if project:
768
+ params["project"] = project
769
+
770
+ if metrics and metrics.strip():
771
+ params["metrics"] = metrics
772
+
773
+ if selected_runs:
774
+ params["runs"] = ",".join(selected_runs)
775
+
776
+ if hide_headers:
777
+ params["accordion"] = "hidden"
778
+ params["sidebar"] = "hidden"
779
+ params["navbar"] = "hidden"
780
+
781
+ query_string = urlencode(params)
782
+ return f"https://{space_host}?{query_string}"
783
+
784
+
785
+ def generate_embed_code(
786
+ project: str,
787
+ metrics: str,
788
+ selected_runs: list = None,
789
+ hide_headers: bool = False,
790
+ ) -> str:
791
+ """Generate the embed iframe code based on current settings."""
792
+ embed_url = generate_share_url(project, metrics, selected_runs, hide_headers)
793
+ if not embed_url:
794
+ return ""
795
+
796
+ return f'<iframe src="{embed_url}" style="width:1600px; height:500px; border:0;"></iframe>'
797
+
798
+
799
+ def serialize_values(metrics):
800
+ """
801
+ Serialize infinity and NaN values in metrics dict to make it JSON-compliant.
802
+ Only handles top-level float values.
803
+
804
+ Converts:
805
+ - float('inf') -> "Infinity"
806
+ - float('-inf') -> "-Infinity"
807
+ - float('nan') -> "NaN"
808
+
809
+ Example:
810
+ {"loss": float('inf'), "accuracy": 0.95} -> {"loss": "Infinity", "accuracy": 0.95}
811
+ """
812
+ if not isinstance(metrics, dict):
813
+ return metrics
814
+
815
+ result = {}
816
+ for key, value in metrics.items():
817
+ if isinstance(value, float):
818
+ if math.isinf(value):
819
+ result[key] = "Infinity" if value > 0 else "-Infinity"
820
+ elif math.isnan(value):
821
+ result[key] = "NaN"
822
+ else:
823
+ result[key] = value
824
+ elif isinstance(value, np.floating):
825
+ float_val = float(value)
826
+ if math.isinf(float_val):
827
+ result[key] = "Infinity" if float_val > 0 else "-Infinity"
828
+ elif math.isnan(float_val):
829
+ result[key] = "NaN"
830
+ else:
831
+ result[key] = float_val
832
+ else:
833
+ result[key] = value
834
+ return result
835
+
836
+
837
+ def deserialize_values(metrics):
838
+ """
839
+ Deserialize infinity and NaN string values back to their numeric forms.
840
+ Only handles top-level string values.
841
+
842
+ Converts:
843
+ - "Infinity" -> float('inf')
844
+ - "-Infinity" -> float('-inf')
845
+ - "NaN" -> float('nan')
846
+
847
+ Example:
848
+ {"loss": "Infinity", "accuracy": 0.95} -> {"loss": float('inf'), "accuracy": 0.95}
849
+ """
850
+ if not isinstance(metrics, dict):
851
+ return metrics
852
+
853
+ result = {}
854
+ for key, value in metrics.items():
855
+ if value == "Infinity":
856
+ result[key] = float("inf")
857
+ elif value == "-Infinity":
858
+ result[key] = float("-inf")
859
+ elif value == "NaN":
860
+ result[key] = float("nan")
861
+ else:
862
+ result[key] = value
863
+ return result
864
+
865
+
866
+ def get_full_url(
867
+ base_url: str, project: str | None, write_token: str, footer: bool = True
868
+ ) -> str:
869
+ params = []
870
+ if project:
871
+ params.append(f"project={project}")
872
+ params.append(f"write_token={write_token}")
873
+ if not footer:
874
+ params.append("footer=false")
875
+ return base_url + "?" + "&".join(params)
876
+
877
+
878
+ def embed_url_in_notebook(url: str) -> None:
879
+ try:
880
+ from IPython.display import HTML, display
881
+
882
+ embed_code = HTML(
883
+ f'<div><iframe src="{url}" width="100%" height="1000px" allow="autoplay; camera; microphone; clipboard-read; clipboard-write;" frameborder="0" allowfullscreen></iframe></div>'
884
+ )
885
+ display(embed_code)
886
+ except ImportError:
887
+ pass
888
+
889
+
890
+ def to_json_safe(obj):
891
+ if isinstance(obj, (str, int, float, bool, type(None))):
892
+ return obj
893
+ if isinstance(obj, np.generic):
894
+ return obj.item()
895
+ if isinstance(obj, dict):
896
+ return {str(k): to_json_safe(v) for k, v in obj.items()}
897
+ if isinstance(obj, (list, tuple, set)):
898
+ return [to_json_safe(v) for v in obj]
899
+ if hasattr(obj, "to_dict") and callable(obj.to_dict):
900
+ return to_json_safe(obj.to_dict())
901
+ if hasattr(obj, "__dict__"):
902
+ return {
903
+ str(k): to_json_safe(v)
904
+ for k, v in vars(obj).items()
905
+ if not k.startswith("_")
906
+ }
907
+ return str(obj)
908
+
909
+
910
+ def get_space() -> str | None:
911
+ """
912
+ Get the space ID ("user/space") if Trackio is running in a Space, or None if not.
913
+ """
914
+ return os.environ.get("SPACE_ID")
915
+
916
+
917
+ def ordered_subset(items: list[str], subset: list[str] | None) -> list[str]:
918
+ subset_set = set(subset or [])
919
+ return [item for item in items if item in subset_set]
920
+
921
+
922
+ def _get_default_namespace() -> str:
923
+ """Get the default namespace (username).
924
+
925
+ This function uses caching to avoid repeated API calls to /whoami-v2.
926
+ """
927
+ token = huggingface_hub.get_token()
928
+ return _cached_whoami(token)["name"]
929
+
930
+
931
+ @lru_cache(maxsize=32)
932
+ def _cached_whoami(token: str | None) -> dict:
933
+ return huggingface_hub.whoami(token=token)