Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +1 -0
- CHANGELOG.md +24 -0
- __init__.py +337 -0
- __pycache__/__init__.cpython-311.pyc +0 -0
- __pycache__/__init__.cpython-312.pyc +0 -0
- __pycache__/cli.cpython-311.pyc +0 -0
- __pycache__/cli.cpython-312.pyc +0 -0
- __pycache__/commit_scheduler.cpython-311.pyc +0 -0
- __pycache__/commit_scheduler.cpython-312.pyc +0 -0
- __pycache__/context_vars.cpython-311.pyc +0 -0
- __pycache__/context_vars.cpython-312.pyc +0 -0
- __pycache__/deploy.cpython-311.pyc +0 -0
- __pycache__/deploy.cpython-312.pyc +0 -0
- __pycache__/dummy_commit_scheduler.cpython-311.pyc +0 -0
- __pycache__/dummy_commit_scheduler.cpython-312.pyc +0 -0
- __pycache__/file_storage.cpython-311.pyc +0 -0
- __pycache__/file_storage.cpython-312.pyc +0 -0
- __pycache__/histogram.cpython-311.pyc +0 -0
- __pycache__/histogram.cpython-312.pyc +0 -0
- __pycache__/imports.cpython-311.pyc +0 -0
- __pycache__/imports.cpython-312.pyc +0 -0
- __pycache__/media.cpython-311.pyc +0 -0
- __pycache__/media.cpython-312.pyc +0 -0
- __pycache__/run.cpython-311.pyc +0 -0
- __pycache__/run.cpython-312.pyc +0 -0
- __pycache__/sqlite_storage.cpython-311.pyc +0 -0
- __pycache__/sqlite_storage.cpython-312.pyc +0 -0
- __pycache__/table.cpython-311.pyc +0 -0
- __pycache__/table.cpython-312.pyc +0 -0
- __pycache__/typehints.cpython-311.pyc +0 -0
- __pycache__/typehints.cpython-312.pyc +0 -0
- __pycache__/utils.cpython-311.pyc +0 -0
- __pycache__/utils.cpython-312.pyc +0 -0
- __pycache__/video_writer.cpython-311.pyc +0 -0
- __pycache__/video_writer.cpython-312.pyc +0 -0
- assets/trackio_logo_dark.png +0 -0
- assets/trackio_logo_light.png +0 -0
- assets/trackio_logo_old.png +3 -0
- assets/trackio_logo_type_dark.png +0 -0
- assets/trackio_logo_type_dark_transparent.png +0 -0
- assets/trackio_logo_type_light.png +0 -0
- assets/trackio_logo_type_light_transparent.png +0 -0
- cli.py +37 -0
- commit_scheduler.py +391 -0
- context_vars.py +18 -0
- deploy.py +258 -0
- dummy_commit_scheduler.py +12 -0
- file_storage.py +37 -0
- histogram.py +68 -0
- imports.py +302 -0
.gitattributes
CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
assets/trackio_logo_old.png filter=lfs diff=lfs merge=lfs -text
|
CHANGELOG.md
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# trackio
|
2 |
+
|
3 |
+
## 0.5.3
|
4 |
+
|
5 |
+
### Features
|
6 |
+
|
7 |
+
- [#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!
|
8 |
+
|
9 |
+
## 0.5.2
|
10 |
+
|
11 |
+
### Features
|
12 |
+
|
13 |
+
- [#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!
|
14 |
+
- [#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!
|
15 |
+
|
16 |
+
### Fixes
|
17 |
+
|
18 |
+
- [#291](https://github.com/gradio-app/trackio/pull/291) [`3b5adc3`](https://github.com/gradio-app/trackio/commit/3b5adc3d1f452dbab7a714d235f4974782f93730) - Fix the wheel build. Thanks @pngwn!
|
19 |
+
|
20 |
+
## 0.5.1
|
21 |
+
|
22 |
+
### Fixes
|
23 |
+
|
24 |
+
- [#278](https://github.com/gradio-app/trackio/pull/278) [`314c054`](https://github.com/gradio-app/trackio/commit/314c05438007ddfea3383e06fd19143e27468e2d) - Fix row orientation of metrics plots. Thanks @abidlabs!
|
__init__.py
ADDED
@@ -0,0 +1,337 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import hashlib
|
2 |
+
import json
|
3 |
+
import logging
|
4 |
+
import os
|
5 |
+
import warnings
|
6 |
+
import webbrowser
|
7 |
+
from pathlib import Path
|
8 |
+
from typing import Any
|
9 |
+
|
10 |
+
from gradio.blocks import BUILT_IN_THEMES
|
11 |
+
from gradio.themes import Default as DefaultTheme
|
12 |
+
from gradio.themes import ThemeClass
|
13 |
+
from gradio_client import Client
|
14 |
+
from huggingface_hub import SpaceStorage
|
15 |
+
|
16 |
+
from trackio import context_vars, deploy, utils
|
17 |
+
from trackio.histogram import Histogram
|
18 |
+
from trackio.imports import import_csv, import_tf_events
|
19 |
+
from trackio.media import TrackioImage, TrackioVideo
|
20 |
+
from trackio.run import Run
|
21 |
+
from trackio.sqlite_storage import SQLiteStorage
|
22 |
+
from trackio.table import Table
|
23 |
+
from trackio.ui.main import demo
|
24 |
+
from trackio.utils import TRACKIO_DIR, TRACKIO_LOGO_DIR
|
25 |
+
|
26 |
+
logging.getLogger("httpx").setLevel(logging.WARNING)
|
27 |
+
|
28 |
+
warnings.filterwarnings(
|
29 |
+
"ignore",
|
30 |
+
message="Empty session being created. Install gradio\\[oauth\\]",
|
31 |
+
category=UserWarning,
|
32 |
+
module="gradio.helpers",
|
33 |
+
)
|
34 |
+
|
35 |
+
__version__ = json.loads(Path(__file__).parent.joinpath("package.json").read_text())[
|
36 |
+
"version"
|
37 |
+
]
|
38 |
+
|
39 |
+
__all__ = [
|
40 |
+
"init",
|
41 |
+
"log",
|
42 |
+
"finish",
|
43 |
+
"show",
|
44 |
+
"import_csv",
|
45 |
+
"import_tf_events",
|
46 |
+
"Image",
|
47 |
+
"Video",
|
48 |
+
"Table",
|
49 |
+
"Histogram",
|
50 |
+
]
|
51 |
+
|
52 |
+
Image = TrackioImage
|
53 |
+
Video = TrackioVideo
|
54 |
+
|
55 |
+
|
56 |
+
config = {}
|
57 |
+
|
58 |
+
DEFAULT_THEME = "default"
|
59 |
+
|
60 |
+
|
61 |
+
def init(
|
62 |
+
project: str,
|
63 |
+
name: str | None = None,
|
64 |
+
group: str | None = None,
|
65 |
+
space_id: str | None = None,
|
66 |
+
space_storage: SpaceStorage | None = None,
|
67 |
+
dataset_id: str | None = None,
|
68 |
+
config: dict | None = None,
|
69 |
+
resume: str = "never",
|
70 |
+
settings: Any = None,
|
71 |
+
private: bool | None = None,
|
72 |
+
embed: bool = True,
|
73 |
+
) -> Run:
|
74 |
+
"""
|
75 |
+
Creates a new Trackio project and returns a [`Run`] object.
|
76 |
+
|
77 |
+
Args:
|
78 |
+
project (`str`):
|
79 |
+
The name of the project (can be an existing project to continue tracking or
|
80 |
+
a new project to start tracking from scratch).
|
81 |
+
name (`str`, *optional*):
|
82 |
+
The name of the run (if not provided, a default name will be generated).
|
83 |
+
group (`str`, *optional*):
|
84 |
+
The name of the group which this run belongs to in order to help organize
|
85 |
+
related runs together. You can toggle the entire group's visibilitiy in the
|
86 |
+
dashboard.
|
87 |
+
space_id (`str`, *optional*):
|
88 |
+
If provided, the project will be logged to a Hugging Face Space instead of
|
89 |
+
a local directory. Should be a complete Space name like
|
90 |
+
`"username/reponame"` or `"orgname/reponame"`, or just `"reponame"` in which
|
91 |
+
case the Space will be created in the currently-logged-in Hugging Face
|
92 |
+
user's namespace. If the Space does not exist, it will be created. If the
|
93 |
+
Space already exists, the project will be logged to it.
|
94 |
+
space_storage ([`~huggingface_hub.SpaceStorage`], *optional*):
|
95 |
+
Choice of persistent storage tier.
|
96 |
+
dataset_id (`str`, *optional*):
|
97 |
+
If a `space_id` is provided, a persistent Hugging Face Dataset will be
|
98 |
+
created and the metrics will be synced to it every 5 minutes. Specify a
|
99 |
+
Dataset with name like `"username/datasetname"` or `"orgname/datasetname"`,
|
100 |
+
or `"datasetname"` (uses currently-logged-in Hugging Face user's namespace),
|
101 |
+
or `None` (uses the same name as the Space but with the `"_dataset"`
|
102 |
+
suffix). If the Dataset does not exist, it will be created. If the Dataset
|
103 |
+
already exists, the project will be appended to it.
|
104 |
+
config (`dict`, *optional*):
|
105 |
+
A dictionary of configuration options. Provided for compatibility with
|
106 |
+
`wandb.init()`.
|
107 |
+
resume (`str`, *optional*, defaults to `"never"`):
|
108 |
+
Controls how to handle resuming a run. Can be one of:
|
109 |
+
|
110 |
+
- `"must"`: Must resume the run with the given name, raises error if run
|
111 |
+
doesn't exist
|
112 |
+
- `"allow"`: Resume the run if it exists, otherwise create a new run
|
113 |
+
- `"never"`: Never resume a run, always create a new one
|
114 |
+
private (`bool`, *optional*):
|
115 |
+
Whether to make the Space private. If None (default), the repo will be
|
116 |
+
public unless the organization's default is private. This value is ignored
|
117 |
+
if the repo already exists.
|
118 |
+
settings (`Any`, *optional*):
|
119 |
+
Not used. Provided for compatibility with `wandb.init()`.
|
120 |
+
embed (`bool`, *optional*, defaults to `True`):
|
121 |
+
If running inside a jupyter/Colab notebook, whether the dashboard should
|
122 |
+
automatically be embedded in the cell when trackio.init() is called.
|
123 |
+
|
124 |
+
Returns:
|
125 |
+
`Run`: A [`Run`] object that can be used to log metrics and finish the run.
|
126 |
+
"""
|
127 |
+
if settings is not None:
|
128 |
+
warnings.warn(
|
129 |
+
"* 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."
|
130 |
+
)
|
131 |
+
|
132 |
+
if space_id is None and dataset_id is not None:
|
133 |
+
raise ValueError("Must provide a `space_id` when `dataset_id` is provided.")
|
134 |
+
space_id, dataset_id = utils.preprocess_space_and_dataset_ids(space_id, dataset_id)
|
135 |
+
url = context_vars.current_server.get()
|
136 |
+
share_url = context_vars.current_share_server.get()
|
137 |
+
|
138 |
+
if url is None:
|
139 |
+
if space_id is None:
|
140 |
+
_, url, share_url = demo.launch(
|
141 |
+
show_api=False,
|
142 |
+
inline=False,
|
143 |
+
quiet=True,
|
144 |
+
prevent_thread_lock=True,
|
145 |
+
show_error=True,
|
146 |
+
favicon_path=TRACKIO_LOGO_DIR / "trackio_logo_light.png",
|
147 |
+
allowed_paths=[TRACKIO_LOGO_DIR, TRACKIO_DIR],
|
148 |
+
)
|
149 |
+
else:
|
150 |
+
url = space_id
|
151 |
+
share_url = None
|
152 |
+
context_vars.current_server.set(url)
|
153 |
+
context_vars.current_share_server.set(share_url)
|
154 |
+
if (
|
155 |
+
context_vars.current_project.get() is None
|
156 |
+
or context_vars.current_project.get() != project
|
157 |
+
):
|
158 |
+
print(f"* Trackio project initialized: {project}")
|
159 |
+
|
160 |
+
if dataset_id is not None:
|
161 |
+
os.environ["TRACKIO_DATASET_ID"] = dataset_id
|
162 |
+
print(
|
163 |
+
f"* Trackio metrics will be synced to Hugging Face Dataset: {dataset_id}"
|
164 |
+
)
|
165 |
+
if space_id is None:
|
166 |
+
print(f"* Trackio metrics logged to: {TRACKIO_DIR}")
|
167 |
+
if utils.is_in_notebook() and embed:
|
168 |
+
base_url = share_url + "/" if share_url else url
|
169 |
+
full_url = utils.get_full_url(
|
170 |
+
base_url, project=project, write_token=demo.write_token
|
171 |
+
)
|
172 |
+
utils.embed_url_in_notebook(full_url)
|
173 |
+
else:
|
174 |
+
utils.print_dashboard_instructions(project)
|
175 |
+
else:
|
176 |
+
deploy.create_space_if_not_exists(
|
177 |
+
space_id, space_storage, dataset_id, private
|
178 |
+
)
|
179 |
+
user_name, space_name = space_id.split("/")
|
180 |
+
space_url = deploy.SPACE_HOST_URL.format(
|
181 |
+
user_name=user_name, space_name=space_name
|
182 |
+
)
|
183 |
+
print(f"* View dashboard by going to: {space_url}")
|
184 |
+
if utils.is_in_notebook() and embed:
|
185 |
+
utils.embed_url_in_notebook(space_url)
|
186 |
+
context_vars.current_project.set(project)
|
187 |
+
|
188 |
+
client = None
|
189 |
+
if not space_id:
|
190 |
+
client = Client(url, verbose=False)
|
191 |
+
|
192 |
+
if resume == "must":
|
193 |
+
if name is None:
|
194 |
+
raise ValueError("Must provide a run name when resume='must'")
|
195 |
+
if name not in SQLiteStorage.get_runs(project):
|
196 |
+
raise ValueError(f"Run '{name}' does not exist in project '{project}'")
|
197 |
+
resumed = True
|
198 |
+
elif resume == "allow":
|
199 |
+
resumed = name is not None and name in SQLiteStorage.get_runs(project)
|
200 |
+
elif resume == "never":
|
201 |
+
if name is not None and name in SQLiteStorage.get_runs(project):
|
202 |
+
warnings.warn(
|
203 |
+
f"* Warning: resume='never' but a run '{name}' already exists in "
|
204 |
+
f"project '{project}'. Generating a new name and instead. If you want "
|
205 |
+
"to resume this run, call init() with resume='must' or resume='allow'."
|
206 |
+
)
|
207 |
+
name = None
|
208 |
+
resumed = False
|
209 |
+
else:
|
210 |
+
raise ValueError("resume must be one of: 'must', 'allow', or 'never'")
|
211 |
+
|
212 |
+
run = Run(
|
213 |
+
url=url,
|
214 |
+
project=project,
|
215 |
+
client=client,
|
216 |
+
name=name,
|
217 |
+
group=group,
|
218 |
+
config=config,
|
219 |
+
space_id=space_id,
|
220 |
+
)
|
221 |
+
|
222 |
+
if resumed:
|
223 |
+
print(f"* Resumed existing run: {run.name}")
|
224 |
+
else:
|
225 |
+
print(f"* Created new run: {run.name}")
|
226 |
+
|
227 |
+
context_vars.current_run.set(run)
|
228 |
+
globals()["config"] = run.config
|
229 |
+
return run
|
230 |
+
|
231 |
+
|
232 |
+
def log(metrics: dict, step: int | None = None) -> None:
|
233 |
+
"""
|
234 |
+
Logs metrics to the current run.
|
235 |
+
|
236 |
+
Args:
|
237 |
+
metrics (`dict`):
|
238 |
+
A dictionary of metrics to log.
|
239 |
+
step (`int`, *optional*):
|
240 |
+
The step number. If not provided, the step will be incremented
|
241 |
+
automatically.
|
242 |
+
"""
|
243 |
+
run = context_vars.current_run.get()
|
244 |
+
if run is None:
|
245 |
+
raise RuntimeError("Call trackio.init() before trackio.log().")
|
246 |
+
run.log(
|
247 |
+
metrics=metrics,
|
248 |
+
step=step,
|
249 |
+
)
|
250 |
+
|
251 |
+
|
252 |
+
def finish():
|
253 |
+
"""
|
254 |
+
Finishes the current run.
|
255 |
+
"""
|
256 |
+
run = context_vars.current_run.get()
|
257 |
+
if run is None:
|
258 |
+
raise RuntimeError("Call trackio.init() before trackio.finish().")
|
259 |
+
run.finish()
|
260 |
+
|
261 |
+
|
262 |
+
def show(
|
263 |
+
project: str | None = None,
|
264 |
+
theme: str | ThemeClass | None = None,
|
265 |
+
mcp_server: bool | None = None,
|
266 |
+
):
|
267 |
+
"""
|
268 |
+
Launches the Trackio dashboard.
|
269 |
+
|
270 |
+
Args:
|
271 |
+
project (`str`, *optional*):
|
272 |
+
The name of the project whose runs to show. If not provided, all projects
|
273 |
+
will be shown and the user can select one.
|
274 |
+
theme (`str` or `ThemeClass`, *optional*):
|
275 |
+
A Gradio Theme to use for the dashboard instead of the default Gradio theme,
|
276 |
+
can be a built-in theme (e.g. `'soft'`, `'citrus'`), a theme from the Hub
|
277 |
+
(e.g. `"gstaff/xkcd"`), or a custom Theme class. If not provided, the
|
278 |
+
`TRACKIO_THEME` environment variable will be used, or if that is not set, the
|
279 |
+
default Gradio theme will be used.
|
280 |
+
mcp_server (`bool`, *optional*):
|
281 |
+
If `True`, the Trackio dashboard will be set up as an MCP server and certain
|
282 |
+
functions will be added as MCP tools. If `None` (default behavior), then the
|
283 |
+
`GRADIO_MCP_SERVER` environment variable will be used to determine if the
|
284 |
+
MCP server should be enabled (which is `"True"` on Hugging Face Spaces).
|
285 |
+
"""
|
286 |
+
theme = theme or os.environ.get("TRACKIO_THEME", DEFAULT_THEME)
|
287 |
+
|
288 |
+
if theme != DEFAULT_THEME:
|
289 |
+
# TODO: It's a little hacky to reproduce this theme-setting logic from Gradio Blocks,
|
290 |
+
# but in Gradio 6.0, the theme will be set in `launch()` instead, which means that we
|
291 |
+
# will be able to remove this code.
|
292 |
+
if isinstance(theme, str):
|
293 |
+
if theme.lower() in BUILT_IN_THEMES:
|
294 |
+
theme = BUILT_IN_THEMES[theme.lower()]
|
295 |
+
else:
|
296 |
+
try:
|
297 |
+
theme = ThemeClass.from_hub(theme)
|
298 |
+
except Exception as e:
|
299 |
+
warnings.warn(f"Cannot load {theme}. Caught Exception: {str(e)}")
|
300 |
+
theme = DefaultTheme()
|
301 |
+
if not isinstance(theme, ThemeClass):
|
302 |
+
warnings.warn("Theme should be a class loaded from gradio.themes")
|
303 |
+
theme = DefaultTheme()
|
304 |
+
demo.theme: ThemeClass = theme
|
305 |
+
demo.theme_css = theme._get_theme_css()
|
306 |
+
demo.stylesheets = theme._stylesheets
|
307 |
+
theme_hasher = hashlib.sha256()
|
308 |
+
theme_hasher.update(demo.theme_css.encode("utf-8"))
|
309 |
+
demo.theme_hash = theme_hasher.hexdigest()
|
310 |
+
|
311 |
+
_mcp_server = (
|
312 |
+
mcp_server
|
313 |
+
if mcp_server is not None
|
314 |
+
else os.environ.get("GRADIO_MCP_SERVER", "False") == "True"
|
315 |
+
)
|
316 |
+
|
317 |
+
_, url, share_url = demo.launch(
|
318 |
+
show_api=_mcp_server,
|
319 |
+
quiet=True,
|
320 |
+
inline=False,
|
321 |
+
prevent_thread_lock=True,
|
322 |
+
favicon_path=TRACKIO_LOGO_DIR / "trackio_logo_light.png",
|
323 |
+
allowed_paths=[TRACKIO_LOGO_DIR, TRACKIO_DIR],
|
324 |
+
mcp_server=_mcp_server,
|
325 |
+
)
|
326 |
+
|
327 |
+
base_url = share_url + "/" if share_url else url
|
328 |
+
full_url = utils.get_full_url(
|
329 |
+
base_url, project=project, write_token=demo.write_token
|
330 |
+
)
|
331 |
+
|
332 |
+
if not utils.is_in_notebook():
|
333 |
+
print(f"* Trackio UI launched at: {full_url}")
|
334 |
+
webbrowser.open(full_url)
|
335 |
+
utils.block_main_thread_until_keyboard_interrupt()
|
336 |
+
else:
|
337 |
+
utils.embed_url_in_notebook(full_url)
|
__pycache__/__init__.cpython-311.pyc
ADDED
Binary file (15.7 kB). View file
|
|
__pycache__/__init__.cpython-312.pyc
ADDED
Binary file (14.7 kB). View file
|
|
__pycache__/cli.cpython-311.pyc
ADDED
Binary file (1.87 kB). View file
|
|
__pycache__/cli.cpython-312.pyc
ADDED
Binary file (1.72 kB). View file
|
|
__pycache__/commit_scheduler.cpython-311.pyc
ADDED
Binary file (20.2 kB). View file
|
|
__pycache__/commit_scheduler.cpython-312.pyc
ADDED
Binary file (18.8 kB). View file
|
|
__pycache__/context_vars.cpython-311.pyc
ADDED
Binary file (1 kB). View file
|
|
__pycache__/context_vars.cpython-312.pyc
ADDED
Binary file (921 Bytes). View file
|
|
__pycache__/deploy.cpython-311.pyc
ADDED
Binary file (11.3 kB). View file
|
|
__pycache__/deploy.cpython-312.pyc
ADDED
Binary file (10.3 kB). View file
|
|
__pycache__/dummy_commit_scheduler.cpython-311.pyc
ADDED
Binary file (1.19 kB). View file
|
|
__pycache__/dummy_commit_scheduler.cpython-312.pyc
ADDED
Binary file (1.01 kB). View file
|
|
__pycache__/file_storage.cpython-311.pyc
ADDED
Binary file (1.88 kB). View file
|
|
__pycache__/file_storage.cpython-312.pyc
ADDED
Binary file (1.63 kB). View file
|
|
__pycache__/histogram.cpython-311.pyc
ADDED
Binary file (3.15 kB). View file
|
|
__pycache__/histogram.cpython-312.pyc
ADDED
Binary file (2.97 kB). View file
|
|
__pycache__/imports.cpython-311.pyc
ADDED
Binary file (14.3 kB). View file
|
|
__pycache__/imports.cpython-312.pyc
ADDED
Binary file (13.2 kB). View file
|
|
__pycache__/media.cpython-311.pyc
ADDED
Binary file (16 kB). View file
|
|
__pycache__/media.cpython-312.pyc
ADDED
Binary file (15 kB). View file
|
|
__pycache__/run.cpython-311.pyc
ADDED
Binary file (10.2 kB). View file
|
|
__pycache__/run.cpython-312.pyc
ADDED
Binary file (9.35 kB). View file
|
|
__pycache__/sqlite_storage.cpython-311.pyc
ADDED
Binary file (37.5 kB). View file
|
|
__pycache__/sqlite_storage.cpython-312.pyc
ADDED
Binary file (31.7 kB). View file
|
|
__pycache__/table.cpython-311.pyc
ADDED
Binary file (2.52 kB). View file
|
|
__pycache__/table.cpython-312.pyc
ADDED
Binary file (2.33 kB). View file
|
|
__pycache__/typehints.cpython-311.pyc
ADDED
Binary file (1.12 kB). View file
|
|
__pycache__/typehints.cpython-312.pyc
ADDED
Binary file (908 Bytes). View file
|
|
__pycache__/utils.cpython-311.pyc
ADDED
Binary file (30.7 kB). View file
|
|
__pycache__/utils.cpython-312.pyc
ADDED
Binary file (26.9 kB). View file
|
|
__pycache__/video_writer.cpython-311.pyc
ADDED
Binary file (5.72 kB). View file
|
|
__pycache__/video_writer.cpython-312.pyc
ADDED
Binary file (5.33 kB). View file
|
|
assets/trackio_logo_dark.png
ADDED
![]() |
assets/trackio_logo_light.png
ADDED
![]() |
assets/trackio_logo_old.png
ADDED
![]() |
Git LFS Details
|
assets/trackio_logo_type_dark.png
ADDED
![]() |
assets/trackio_logo_type_dark_transparent.png
ADDED
![]() |
assets/trackio_logo_type_light.png
ADDED
![]() |
assets/trackio_logo_type_light_transparent.png
ADDED
![]() |
cli.py
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
|
3 |
+
from trackio import show
|
4 |
+
|
5 |
+
|
6 |
+
def main():
|
7 |
+
parser = argparse.ArgumentParser(description="Trackio CLI")
|
8 |
+
subparsers = parser.add_subparsers(dest="command")
|
9 |
+
|
10 |
+
ui_parser = subparsers.add_parser(
|
11 |
+
"show", help="Show the Trackio dashboard UI for a project"
|
12 |
+
)
|
13 |
+
ui_parser.add_argument(
|
14 |
+
"--project", required=False, help="Project name to show in the dashboard"
|
15 |
+
)
|
16 |
+
ui_parser.add_argument(
|
17 |
+
"--theme",
|
18 |
+
required=False,
|
19 |
+
default="citrus",
|
20 |
+
help="A Gradio Theme to use for the dashboard instead of the default, can be a built-in theme (e.g. 'soft', 'citrus'), or a theme from the Hub (e.g. 'gstaff/xkcd').",
|
21 |
+
)
|
22 |
+
ui_parser.add_argument(
|
23 |
+
"--mcp-server",
|
24 |
+
action="store_true",
|
25 |
+
help="Enable MCP server functionality. The Trackio dashboard will be set up as an MCP server and certain functions will be exposed as MCP tools.",
|
26 |
+
)
|
27 |
+
|
28 |
+
args = parser.parse_args()
|
29 |
+
|
30 |
+
if args.command == "show":
|
31 |
+
show(args.project, args.theme, args.mcp_server)
|
32 |
+
else:
|
33 |
+
parser.print_help()
|
34 |
+
|
35 |
+
|
36 |
+
if __name__ == "__main__":
|
37 |
+
main()
|
commit_scheduler.py
ADDED
@@ -0,0 +1,391 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Originally copied from https://github.com/huggingface/huggingface_hub/blob/d0a948fc2a32ed6e557042a95ef3e4af97ec4a7c/src/huggingface_hub/_commit_scheduler.py
|
2 |
+
|
3 |
+
import atexit
|
4 |
+
import logging
|
5 |
+
import os
|
6 |
+
import time
|
7 |
+
from concurrent.futures import Future
|
8 |
+
from dataclasses import dataclass
|
9 |
+
from io import SEEK_END, SEEK_SET, BytesIO
|
10 |
+
from pathlib import Path
|
11 |
+
from threading import Lock, Thread
|
12 |
+
from typing import Callable, Dict, List, Union
|
13 |
+
|
14 |
+
from huggingface_hub.hf_api import (
|
15 |
+
DEFAULT_IGNORE_PATTERNS,
|
16 |
+
CommitInfo,
|
17 |
+
CommitOperationAdd,
|
18 |
+
HfApi,
|
19 |
+
)
|
20 |
+
from huggingface_hub.utils import filter_repo_objects
|
21 |
+
|
22 |
+
logger = logging.getLogger(__name__)
|
23 |
+
|
24 |
+
|
25 |
+
@dataclass(frozen=True)
|
26 |
+
class _FileToUpload:
|
27 |
+
"""Temporary dataclass to store info about files to upload. Not meant to be used directly."""
|
28 |
+
|
29 |
+
local_path: Path
|
30 |
+
path_in_repo: str
|
31 |
+
size_limit: int
|
32 |
+
last_modified: float
|
33 |
+
|
34 |
+
|
35 |
+
class CommitScheduler:
|
36 |
+
"""
|
37 |
+
Scheduler to upload a local folder to the Hub at regular intervals (e.g. push to hub every 5 minutes).
|
38 |
+
|
39 |
+
The recommended way to use the scheduler is to use it as a context manager. This ensures that the scheduler is
|
40 |
+
properly stopped and the last commit is triggered when the script ends. The scheduler can also be stopped manually
|
41 |
+
with the `stop` method. Checkout the [upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#scheduled-uploads)
|
42 |
+
to learn more about how to use it.
|
43 |
+
|
44 |
+
Args:
|
45 |
+
repo_id (`str`):
|
46 |
+
The id of the repo to commit to.
|
47 |
+
folder_path (`str` or `Path`):
|
48 |
+
Path to the local folder to upload regularly.
|
49 |
+
every (`int` or `float`, *optional*):
|
50 |
+
The number of minutes between each commit. Defaults to 5 minutes.
|
51 |
+
path_in_repo (`str`, *optional*):
|
52 |
+
Relative path of the directory in the repo, for example: `"checkpoints/"`. Defaults to the root folder
|
53 |
+
of the repository.
|
54 |
+
repo_type (`str`, *optional*):
|
55 |
+
The type of the repo to commit to. Defaults to `model`.
|
56 |
+
revision (`str`, *optional*):
|
57 |
+
The revision of the repo to commit to. Defaults to `main`.
|
58 |
+
private (`bool`, *optional*):
|
59 |
+
Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.
|
60 |
+
token (`str`, *optional*):
|
61 |
+
The token to use to commit to the repo. Defaults to the token saved on the machine.
|
62 |
+
allow_patterns (`List[str]` or `str`, *optional*):
|
63 |
+
If provided, only files matching at least one pattern are uploaded.
|
64 |
+
ignore_patterns (`List[str]` or `str`, *optional*):
|
65 |
+
If provided, files matching any of the patterns are not uploaded.
|
66 |
+
squash_history (`bool`, *optional*):
|
67 |
+
Whether to squash the history of the repo after each commit. Defaults to `False`. Squashing commits is
|
68 |
+
useful to avoid degraded performances on the repo when it grows too large.
|
69 |
+
hf_api (`HfApi`, *optional*):
|
70 |
+
The [`HfApi`] client to use to commit to the Hub. Can be set with custom settings (user agent, token,...).
|
71 |
+
on_before_commit (`Callable[[], None]`, *optional*):
|
72 |
+
If specified, a function that will be called before the CommitScheduler lists files to create a commit.
|
73 |
+
|
74 |
+
Example:
|
75 |
+
```py
|
76 |
+
>>> from pathlib import Path
|
77 |
+
>>> from huggingface_hub import CommitScheduler
|
78 |
+
|
79 |
+
# Scheduler uploads every 10 minutes
|
80 |
+
>>> csv_path = Path("watched_folder/data.csv")
|
81 |
+
>>> CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path=csv_path.parent, every=10)
|
82 |
+
|
83 |
+
>>> with csv_path.open("a") as f:
|
84 |
+
... f.write("first line")
|
85 |
+
|
86 |
+
# Some time later (...)
|
87 |
+
>>> with csv_path.open("a") as f:
|
88 |
+
... f.write("second line")
|
89 |
+
```
|
90 |
+
|
91 |
+
Example using a context manager:
|
92 |
+
```py
|
93 |
+
>>> from pathlib import Path
|
94 |
+
>>> from huggingface_hub import CommitScheduler
|
95 |
+
|
96 |
+
>>> with CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path="watched_folder", every=10) as scheduler:
|
97 |
+
... csv_path = Path("watched_folder/data.csv")
|
98 |
+
... with csv_path.open("a") as f:
|
99 |
+
... f.write("first line")
|
100 |
+
... (...)
|
101 |
+
... with csv_path.open("a") as f:
|
102 |
+
... f.write("second line")
|
103 |
+
|
104 |
+
# Scheduler is now stopped and last commit have been triggered
|
105 |
+
```
|
106 |
+
"""
|
107 |
+
|
108 |
+
def __init__(
|
109 |
+
self,
|
110 |
+
*,
|
111 |
+
repo_id: str,
|
112 |
+
folder_path: Union[str, Path],
|
113 |
+
every: Union[int, float] = 5,
|
114 |
+
path_in_repo: str | None = None,
|
115 |
+
repo_type: str | None = None,
|
116 |
+
revision: str | None = None,
|
117 |
+
private: bool | None = None,
|
118 |
+
token: str | None = None,
|
119 |
+
allow_patterns: list[str] | str | None = None,
|
120 |
+
ignore_patterns: list[str] | str | None = None,
|
121 |
+
squash_history: bool = False,
|
122 |
+
hf_api: HfApi | None = None,
|
123 |
+
on_before_commit: Callable[[], None] | None = None,
|
124 |
+
) -> None:
|
125 |
+
self.api = hf_api or HfApi(token=token)
|
126 |
+
self.on_before_commit = on_before_commit
|
127 |
+
|
128 |
+
# Folder
|
129 |
+
self.folder_path = Path(folder_path).expanduser().resolve()
|
130 |
+
self.path_in_repo = path_in_repo or ""
|
131 |
+
self.allow_patterns = allow_patterns
|
132 |
+
|
133 |
+
if ignore_patterns is None:
|
134 |
+
ignore_patterns = []
|
135 |
+
elif isinstance(ignore_patterns, str):
|
136 |
+
ignore_patterns = [ignore_patterns]
|
137 |
+
self.ignore_patterns = ignore_patterns + DEFAULT_IGNORE_PATTERNS
|
138 |
+
|
139 |
+
if self.folder_path.is_file():
|
140 |
+
raise ValueError(
|
141 |
+
f"'folder_path' must be a directory, not a file: '{self.folder_path}'."
|
142 |
+
)
|
143 |
+
self.folder_path.mkdir(parents=True, exist_ok=True)
|
144 |
+
|
145 |
+
# Repository
|
146 |
+
repo_url = self.api.create_repo(
|
147 |
+
repo_id=repo_id, private=private, repo_type=repo_type, exist_ok=True
|
148 |
+
)
|
149 |
+
self.repo_id = repo_url.repo_id
|
150 |
+
self.repo_type = repo_type
|
151 |
+
self.revision = revision
|
152 |
+
self.token = token
|
153 |
+
|
154 |
+
self.last_uploaded: Dict[Path, float] = {}
|
155 |
+
self.last_push_time: float | None = None
|
156 |
+
|
157 |
+
if not every > 0:
|
158 |
+
raise ValueError(f"'every' must be a positive integer, not '{every}'.")
|
159 |
+
self.lock = Lock()
|
160 |
+
self.every = every
|
161 |
+
self.squash_history = squash_history
|
162 |
+
|
163 |
+
logger.info(
|
164 |
+
f"Scheduled job to push '{self.folder_path}' to '{self.repo_id}' every {self.every} minutes."
|
165 |
+
)
|
166 |
+
self._scheduler_thread = Thread(target=self._run_scheduler, daemon=True)
|
167 |
+
self._scheduler_thread.start()
|
168 |
+
atexit.register(self._push_to_hub)
|
169 |
+
|
170 |
+
self.__stopped = False
|
171 |
+
|
172 |
+
def stop(self) -> None:
|
173 |
+
"""Stop the scheduler.
|
174 |
+
|
175 |
+
A stopped scheduler cannot be restarted. Mostly for tests purposes.
|
176 |
+
"""
|
177 |
+
self.__stopped = True
|
178 |
+
|
179 |
+
def __enter__(self) -> "CommitScheduler":
|
180 |
+
return self
|
181 |
+
|
182 |
+
def __exit__(self, exc_type, exc_value, traceback) -> None:
|
183 |
+
# Upload last changes before exiting
|
184 |
+
self.trigger().result()
|
185 |
+
self.stop()
|
186 |
+
return
|
187 |
+
|
188 |
+
def _run_scheduler(self) -> None:
|
189 |
+
"""Dumb thread waiting between each scheduled push to Hub."""
|
190 |
+
while True:
|
191 |
+
self.last_future = self.trigger()
|
192 |
+
time.sleep(self.every * 60)
|
193 |
+
if self.__stopped:
|
194 |
+
break
|
195 |
+
|
196 |
+
def trigger(self) -> Future:
|
197 |
+
"""Trigger a `push_to_hub` and return a future.
|
198 |
+
|
199 |
+
This method is automatically called every `every` minutes. You can also call it manually to trigger a commit
|
200 |
+
immediately, without waiting for the next scheduled commit.
|
201 |
+
"""
|
202 |
+
return self.api.run_as_future(self._push_to_hub)
|
203 |
+
|
204 |
+
def _push_to_hub(self) -> CommitInfo | None:
|
205 |
+
if self.__stopped: # If stopped, already scheduled commits are ignored
|
206 |
+
return None
|
207 |
+
|
208 |
+
logger.info("(Background) scheduled commit triggered.")
|
209 |
+
try:
|
210 |
+
value = self.push_to_hub()
|
211 |
+
if self.squash_history:
|
212 |
+
logger.info("(Background) squashing repo history.")
|
213 |
+
self.api.super_squash_history(
|
214 |
+
repo_id=self.repo_id, repo_type=self.repo_type, branch=self.revision
|
215 |
+
)
|
216 |
+
return value
|
217 |
+
except Exception as e:
|
218 |
+
logger.error(
|
219 |
+
f"Error while pushing to Hub: {e}"
|
220 |
+
) # Depending on the setup, error might be silenced
|
221 |
+
raise
|
222 |
+
|
223 |
+
def push_to_hub(self) -> CommitInfo | None:
|
224 |
+
"""
|
225 |
+
Push folder to the Hub and return the commit info.
|
226 |
+
|
227 |
+
<Tip warning={true}>
|
228 |
+
|
229 |
+
This method is not meant to be called directly. It is run in the background by the scheduler, respecting a
|
230 |
+
queue mechanism to avoid concurrent commits. Making a direct call to the method might lead to concurrency
|
231 |
+
issues.
|
232 |
+
|
233 |
+
</Tip>
|
234 |
+
|
235 |
+
The default behavior of `push_to_hub` is to assume an append-only folder. It lists all files in the folder and
|
236 |
+
uploads only changed files. If no changes are found, the method returns without committing anything. If you want
|
237 |
+
to change this behavior, you can inherit from [`CommitScheduler`] and override this method. This can be useful
|
238 |
+
for example to compress data together in a single file before committing. For more details and examples, check
|
239 |
+
out our [integration guide](https://huggingface.co/docs/huggingface_hub/main/en/guides/upload#scheduled-uploads).
|
240 |
+
"""
|
241 |
+
# Check files to upload (with lock)
|
242 |
+
with self.lock:
|
243 |
+
if self.on_before_commit is not None:
|
244 |
+
self.on_before_commit()
|
245 |
+
|
246 |
+
logger.debug("Listing files to upload for scheduled commit.")
|
247 |
+
|
248 |
+
# List files from folder (taken from `_prepare_upload_folder_additions`)
|
249 |
+
relpath_to_abspath = {
|
250 |
+
path.relative_to(self.folder_path).as_posix(): path
|
251 |
+
for path in sorted(
|
252 |
+
self.folder_path.glob("**/*")
|
253 |
+
) # sorted to be deterministic
|
254 |
+
if path.is_file()
|
255 |
+
}
|
256 |
+
prefix = f"{self.path_in_repo.strip('/')}/" if self.path_in_repo else ""
|
257 |
+
|
258 |
+
# Filter with pattern + filter out unchanged files + retrieve current file size
|
259 |
+
files_to_upload: List[_FileToUpload] = []
|
260 |
+
for relpath in filter_repo_objects(
|
261 |
+
relpath_to_abspath.keys(),
|
262 |
+
allow_patterns=self.allow_patterns,
|
263 |
+
ignore_patterns=self.ignore_patterns,
|
264 |
+
):
|
265 |
+
local_path = relpath_to_abspath[relpath]
|
266 |
+
stat = local_path.stat()
|
267 |
+
if (
|
268 |
+
self.last_uploaded.get(local_path) is None
|
269 |
+
or self.last_uploaded[local_path] != stat.st_mtime
|
270 |
+
):
|
271 |
+
files_to_upload.append(
|
272 |
+
_FileToUpload(
|
273 |
+
local_path=local_path,
|
274 |
+
path_in_repo=prefix + relpath,
|
275 |
+
size_limit=stat.st_size,
|
276 |
+
last_modified=stat.st_mtime,
|
277 |
+
)
|
278 |
+
)
|
279 |
+
|
280 |
+
# Return if nothing to upload
|
281 |
+
if len(files_to_upload) == 0:
|
282 |
+
logger.debug("Dropping schedule commit: no changed file to upload.")
|
283 |
+
return None
|
284 |
+
|
285 |
+
# Convert `_FileToUpload` as `CommitOperationAdd` (=> compute file shas + limit to file size)
|
286 |
+
logger.debug("Removing unchanged files since previous scheduled commit.")
|
287 |
+
add_operations = [
|
288 |
+
CommitOperationAdd(
|
289 |
+
# TODO: Cap the file to its current size, even if the user append data to it while a scheduled commit is happening
|
290 |
+
# (requires an upstream fix for XET-535: `hf_xet` should support `BinaryIO` for upload)
|
291 |
+
path_or_fileobj=file_to_upload.local_path,
|
292 |
+
path_in_repo=file_to_upload.path_in_repo,
|
293 |
+
)
|
294 |
+
for file_to_upload in files_to_upload
|
295 |
+
]
|
296 |
+
|
297 |
+
# Upload files (append mode expected - no need for lock)
|
298 |
+
logger.debug("Uploading files for scheduled commit.")
|
299 |
+
commit_info = self.api.create_commit(
|
300 |
+
repo_id=self.repo_id,
|
301 |
+
repo_type=self.repo_type,
|
302 |
+
operations=add_operations,
|
303 |
+
commit_message="Scheduled Commit",
|
304 |
+
revision=self.revision,
|
305 |
+
)
|
306 |
+
|
307 |
+
for file in files_to_upload:
|
308 |
+
self.last_uploaded[file.local_path] = file.last_modified
|
309 |
+
|
310 |
+
self.last_push_time = time.time()
|
311 |
+
|
312 |
+
return commit_info
|
313 |
+
|
314 |
+
|
315 |
+
class PartialFileIO(BytesIO):
|
316 |
+
"""A file-like object that reads only the first part of a file.
|
317 |
+
|
318 |
+
Useful to upload a file to the Hub when the user might still be appending data to it. Only the first part of the
|
319 |
+
file is uploaded (i.e. the part that was available when the filesystem was first scanned).
|
320 |
+
|
321 |
+
In practice, only used internally by the CommitScheduler to regularly push a folder to the Hub with minimal
|
322 |
+
disturbance for the user. The object is passed to `CommitOperationAdd`.
|
323 |
+
|
324 |
+
Only supports `read`, `tell` and `seek` methods.
|
325 |
+
|
326 |
+
Args:
|
327 |
+
file_path (`str` or `Path`):
|
328 |
+
Path to the file to read.
|
329 |
+
size_limit (`int`):
|
330 |
+
The maximum number of bytes to read from the file. If the file is larger than this, only the first part
|
331 |
+
will be read (and uploaded).
|
332 |
+
"""
|
333 |
+
|
334 |
+
def __init__(self, file_path: Union[str, Path], size_limit: int) -> None:
|
335 |
+
self._file_path = Path(file_path)
|
336 |
+
self._file = self._file_path.open("rb")
|
337 |
+
self._size_limit = min(size_limit, os.fstat(self._file.fileno()).st_size)
|
338 |
+
|
339 |
+
def __del__(self) -> None:
|
340 |
+
self._file.close()
|
341 |
+
return super().__del__()
|
342 |
+
|
343 |
+
def __repr__(self) -> str:
|
344 |
+
return (
|
345 |
+
f"<PartialFileIO file_path={self._file_path} size_limit={self._size_limit}>"
|
346 |
+
)
|
347 |
+
|
348 |
+
def __len__(self) -> int:
|
349 |
+
return self._size_limit
|
350 |
+
|
351 |
+
def __getattribute__(self, name: str):
|
352 |
+
if name.startswith("_") or name in (
|
353 |
+
"read",
|
354 |
+
"tell",
|
355 |
+
"seek",
|
356 |
+
): # only 3 public methods supported
|
357 |
+
return super().__getattribute__(name)
|
358 |
+
raise NotImplementedError(f"PartialFileIO does not support '{name}'.")
|
359 |
+
|
360 |
+
def tell(self) -> int:
|
361 |
+
"""Return the current file position."""
|
362 |
+
return self._file.tell()
|
363 |
+
|
364 |
+
def seek(self, __offset: int, __whence: int = SEEK_SET) -> int:
|
365 |
+
"""Change the stream position to the given offset.
|
366 |
+
|
367 |
+
Behavior is the same as a regular file, except that the position is capped to the size limit.
|
368 |
+
"""
|
369 |
+
if __whence == SEEK_END:
|
370 |
+
# SEEK_END => set from the truncated end
|
371 |
+
__offset = len(self) + __offset
|
372 |
+
__whence = SEEK_SET
|
373 |
+
|
374 |
+
pos = self._file.seek(__offset, __whence)
|
375 |
+
if pos > self._size_limit:
|
376 |
+
return self._file.seek(self._size_limit)
|
377 |
+
return pos
|
378 |
+
|
379 |
+
def read(self, __size: int | None = -1) -> bytes:
|
380 |
+
"""Read at most `__size` bytes from the file.
|
381 |
+
|
382 |
+
Behavior is the same as a regular file, except that it is capped to the size limit.
|
383 |
+
"""
|
384 |
+
current = self._file.tell()
|
385 |
+
if __size is None or __size < 0:
|
386 |
+
# Read until file limit
|
387 |
+
truncated_size = self._size_limit - current
|
388 |
+
else:
|
389 |
+
# Read until file limit or __size
|
390 |
+
truncated_size = min(__size, self._size_limit - current)
|
391 |
+
return self._file.read(truncated_size)
|
context_vars.py
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import contextvars
|
2 |
+
from typing import TYPE_CHECKING
|
3 |
+
|
4 |
+
if TYPE_CHECKING:
|
5 |
+
from trackio.run import Run
|
6 |
+
|
7 |
+
current_run: contextvars.ContextVar["Run | None"] = contextvars.ContextVar(
|
8 |
+
"current_run", default=None
|
9 |
+
)
|
10 |
+
current_project: contextvars.ContextVar[str | None] = contextvars.ContextVar(
|
11 |
+
"current_project", default=None
|
12 |
+
)
|
13 |
+
current_server: contextvars.ContextVar[str | None] = contextvars.ContextVar(
|
14 |
+
"current_server", default=None
|
15 |
+
)
|
16 |
+
current_share_server: contextvars.ContextVar[str | None] = contextvars.ContextVar(
|
17 |
+
"current_share_server", default=None
|
18 |
+
)
|
deploy.py
ADDED
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import importlib.metadata
|
2 |
+
import io
|
3 |
+
import os
|
4 |
+
import time
|
5 |
+
from importlib.resources import files
|
6 |
+
from pathlib import Path
|
7 |
+
|
8 |
+
import gradio
|
9 |
+
import huggingface_hub
|
10 |
+
from gradio_client import Client, handle_file
|
11 |
+
from httpx import ReadTimeout
|
12 |
+
from huggingface_hub.errors import RepositoryNotFoundError
|
13 |
+
from requests import HTTPError
|
14 |
+
|
15 |
+
import trackio
|
16 |
+
from trackio.sqlite_storage import SQLiteStorage
|
17 |
+
|
18 |
+
SPACE_HOST_URL = "https://{user_name}-{space_name}.hf.space/"
|
19 |
+
SPACE_URL = "https://huggingface.co/spaces/{space_id}"
|
20 |
+
|
21 |
+
|
22 |
+
def _is_trackio_installed_from_source() -> bool:
|
23 |
+
"""Check if trackio is installed from source/editable install vs PyPI."""
|
24 |
+
try:
|
25 |
+
trackio_file = trackio.__file__
|
26 |
+
if "site-packages" not in trackio_file:
|
27 |
+
return True
|
28 |
+
|
29 |
+
dist = importlib.metadata.distribution("trackio")
|
30 |
+
if dist.files:
|
31 |
+
files = list(dist.files)
|
32 |
+
has_pth = any(".pth" in str(f) for f in files)
|
33 |
+
if has_pth:
|
34 |
+
return True
|
35 |
+
|
36 |
+
return False
|
37 |
+
except (
|
38 |
+
AttributeError,
|
39 |
+
importlib.metadata.PackageNotFoundError,
|
40 |
+
importlib.metadata.MetadataError,
|
41 |
+
ValueError,
|
42 |
+
TypeError,
|
43 |
+
):
|
44 |
+
return True
|
45 |
+
|
46 |
+
|
47 |
+
def deploy_as_space(
|
48 |
+
space_id: str,
|
49 |
+
space_storage: huggingface_hub.SpaceStorage | None = None,
|
50 |
+
dataset_id: str | None = None,
|
51 |
+
private: bool | None = None,
|
52 |
+
):
|
53 |
+
if (
|
54 |
+
os.getenv("SYSTEM") == "spaces"
|
55 |
+
): # in case a repo with this function is uploaded to spaces
|
56 |
+
return
|
57 |
+
|
58 |
+
trackio_path = files("trackio")
|
59 |
+
|
60 |
+
hf_api = huggingface_hub.HfApi()
|
61 |
+
|
62 |
+
try:
|
63 |
+
huggingface_hub.create_repo(
|
64 |
+
space_id,
|
65 |
+
private=private,
|
66 |
+
space_sdk="gradio",
|
67 |
+
space_storage=space_storage,
|
68 |
+
repo_type="space",
|
69 |
+
exist_ok=True,
|
70 |
+
)
|
71 |
+
except HTTPError as e:
|
72 |
+
if e.response.status_code in [401, 403]: # unauthorized or forbidden
|
73 |
+
print("Need 'write' access token to create a Spaces repo.")
|
74 |
+
huggingface_hub.login(add_to_git_credential=False)
|
75 |
+
huggingface_hub.create_repo(
|
76 |
+
space_id,
|
77 |
+
private=private,
|
78 |
+
space_sdk="gradio",
|
79 |
+
space_storage=space_storage,
|
80 |
+
repo_type="space",
|
81 |
+
exist_ok=True,
|
82 |
+
)
|
83 |
+
else:
|
84 |
+
raise ValueError(f"Failed to create Space: {e}")
|
85 |
+
|
86 |
+
with open(Path(trackio_path, "README.md"), "r") as f:
|
87 |
+
readme_content = f.read()
|
88 |
+
readme_content = readme_content.replace("{GRADIO_VERSION}", gradio.__version__)
|
89 |
+
readme_buffer = io.BytesIO(readme_content.encode("utf-8"))
|
90 |
+
hf_api.upload_file(
|
91 |
+
path_or_fileobj=readme_buffer,
|
92 |
+
path_in_repo="README.md",
|
93 |
+
repo_id=space_id,
|
94 |
+
repo_type="space",
|
95 |
+
)
|
96 |
+
|
97 |
+
# We can assume pandas, gradio, and huggingface-hub are already installed in a Gradio Space.
|
98 |
+
# Make sure necessary dependencies are installed by creating a requirements.txt.
|
99 |
+
is_source_install = _is_trackio_installed_from_source()
|
100 |
+
|
101 |
+
if is_source_install:
|
102 |
+
requirements_content = """pyarrow>=21.0
|
103 |
+
plotly>=6.0.0,<7.0.0"""
|
104 |
+
else:
|
105 |
+
requirements_content = f"""pyarrow>=21.0
|
106 |
+
trackio=={trackio.__version__}
|
107 |
+
plotly>=6.0.0,<7.0.0"""
|
108 |
+
|
109 |
+
requirements_buffer = io.BytesIO(requirements_content.encode("utf-8"))
|
110 |
+
hf_api.upload_file(
|
111 |
+
path_or_fileobj=requirements_buffer,
|
112 |
+
path_in_repo="requirements.txt",
|
113 |
+
repo_id=space_id,
|
114 |
+
repo_type="space",
|
115 |
+
)
|
116 |
+
|
117 |
+
huggingface_hub.utils.disable_progress_bars()
|
118 |
+
|
119 |
+
if is_source_install:
|
120 |
+
hf_api.upload_folder(
|
121 |
+
repo_id=space_id,
|
122 |
+
repo_type="space",
|
123 |
+
folder_path=trackio_path,
|
124 |
+
ignore_patterns=["README.md"],
|
125 |
+
)
|
126 |
+
else:
|
127 |
+
app_file_content = """import trackio
|
128 |
+
trackio.show()"""
|
129 |
+
app_file_buffer = io.BytesIO(app_file_content.encode("utf-8"))
|
130 |
+
hf_api.upload_file(
|
131 |
+
path_or_fileobj=app_file_buffer,
|
132 |
+
path_in_repo="ui/main.py",
|
133 |
+
repo_id=space_id,
|
134 |
+
repo_type="space",
|
135 |
+
)
|
136 |
+
|
137 |
+
if hf_token := huggingface_hub.utils.get_token():
|
138 |
+
huggingface_hub.add_space_secret(space_id, "HF_TOKEN", hf_token)
|
139 |
+
if dataset_id is not None:
|
140 |
+
huggingface_hub.add_space_variable(space_id, "TRACKIO_DATASET_ID", dataset_id)
|
141 |
+
|
142 |
+
if logo_light_url := os.environ.get("TRACKIO_LOGO_LIGHT_URL"):
|
143 |
+
huggingface_hub.add_space_variable(
|
144 |
+
space_id, "TRACKIO_LOGO_LIGHT_URL", logo_light_url
|
145 |
+
)
|
146 |
+
if logo_dark_url := os.environ.get("TRACKIO_LOGO_DARK_URL"):
|
147 |
+
huggingface_hub.add_space_variable(
|
148 |
+
space_id, "TRACKIO_LOGO_DARK_URL", logo_dark_url
|
149 |
+
)
|
150 |
+
|
151 |
+
if plot_order := os.environ.get("TRACKIO_PLOT_ORDER"):
|
152 |
+
huggingface_hub.add_space_variable(space_id, "TRACKIO_PLOT_ORDER", plot_order)
|
153 |
+
|
154 |
+
if theme := os.environ.get("TRACKIO_THEME"):
|
155 |
+
huggingface_hub.add_space_variable(space_id, "TRACKIO_THEME", theme)
|
156 |
+
|
157 |
+
|
158 |
+
def create_space_if_not_exists(
|
159 |
+
space_id: str,
|
160 |
+
space_storage: huggingface_hub.SpaceStorage | None = None,
|
161 |
+
dataset_id: str | None = None,
|
162 |
+
private: bool | None = None,
|
163 |
+
) -> None:
|
164 |
+
"""
|
165 |
+
Creates a new Hugging Face Space if it does not exist. If a dataset_id is provided, it will be added as a space variable.
|
166 |
+
|
167 |
+
Args:
|
168 |
+
space_id: The ID of the Space to create.
|
169 |
+
dataset_id: The ID of the Dataset to add to the Space.
|
170 |
+
private: Whether to make the Space private. If None (default), the repo will be
|
171 |
+
public unless the organization's default is private. This value is ignored if
|
172 |
+
the repo already exists.
|
173 |
+
"""
|
174 |
+
if "/" not in space_id:
|
175 |
+
raise ValueError(
|
176 |
+
f"Invalid space ID: {space_id}. Must be in the format: username/reponame or orgname/reponame."
|
177 |
+
)
|
178 |
+
if dataset_id is not None and "/" not in dataset_id:
|
179 |
+
raise ValueError(
|
180 |
+
f"Invalid dataset ID: {dataset_id}. Must be in the format: username/datasetname or orgname/datasetname."
|
181 |
+
)
|
182 |
+
try:
|
183 |
+
huggingface_hub.repo_info(space_id, repo_type="space")
|
184 |
+
print(f"* Found existing space: {SPACE_URL.format(space_id=space_id)}")
|
185 |
+
if dataset_id is not None:
|
186 |
+
huggingface_hub.add_space_variable(
|
187 |
+
space_id, "TRACKIO_DATASET_ID", dataset_id
|
188 |
+
)
|
189 |
+
if logo_light_url := os.environ.get("TRACKIO_LOGO_LIGHT_URL"):
|
190 |
+
huggingface_hub.add_space_variable(
|
191 |
+
space_id, "TRACKIO_LOGO_LIGHT_URL", logo_light_url
|
192 |
+
)
|
193 |
+
if logo_dark_url := os.environ.get("TRACKIO_LOGO_DARK_URL"):
|
194 |
+
huggingface_hub.add_space_variable(
|
195 |
+
space_id, "TRACKIO_LOGO_DARK_URL", logo_dark_url
|
196 |
+
)
|
197 |
+
|
198 |
+
if plot_order := os.environ.get("TRACKIO_PLOT_ORDER"):
|
199 |
+
huggingface_hub.add_space_variable(
|
200 |
+
space_id, "TRACKIO_PLOT_ORDER", plot_order
|
201 |
+
)
|
202 |
+
|
203 |
+
if theme := os.environ.get("TRACKIO_THEME"):
|
204 |
+
huggingface_hub.add_space_variable(space_id, "TRACKIO_THEME", theme)
|
205 |
+
return
|
206 |
+
except RepositoryNotFoundError:
|
207 |
+
pass
|
208 |
+
except HTTPError as e:
|
209 |
+
if e.response.status_code in [401, 403]: # unauthorized or forbidden
|
210 |
+
print("Need 'write' access token to create a Spaces repo.")
|
211 |
+
huggingface_hub.login(add_to_git_credential=False)
|
212 |
+
huggingface_hub.add_space_variable(
|
213 |
+
space_id, "TRACKIO_DATASET_ID", dataset_id
|
214 |
+
)
|
215 |
+
else:
|
216 |
+
raise ValueError(f"Failed to create Space: {e}")
|
217 |
+
|
218 |
+
print(f"* Creating new space: {SPACE_URL.format(space_id=space_id)}")
|
219 |
+
deploy_as_space(space_id, space_storage, dataset_id, private)
|
220 |
+
|
221 |
+
|
222 |
+
def wait_until_space_exists(
|
223 |
+
space_id: str,
|
224 |
+
) -> None:
|
225 |
+
"""
|
226 |
+
Blocks the current thread until the space exists.
|
227 |
+
May raise a TimeoutError if this takes quite a while.
|
228 |
+
|
229 |
+
Args:
|
230 |
+
space_id: The ID of the Space to wait for.
|
231 |
+
"""
|
232 |
+
delay = 1
|
233 |
+
for _ in range(10):
|
234 |
+
try:
|
235 |
+
Client(space_id, verbose=False)
|
236 |
+
return
|
237 |
+
except (ReadTimeout, ValueError):
|
238 |
+
time.sleep(delay)
|
239 |
+
delay = min(delay * 2, 30)
|
240 |
+
raise TimeoutError("Waiting for space to exist took longer than expected")
|
241 |
+
|
242 |
+
|
243 |
+
def upload_db_to_space(project: str, space_id: str) -> None:
|
244 |
+
"""
|
245 |
+
Uploads the database of a local Trackio project to a Hugging Face Space.
|
246 |
+
|
247 |
+
Args:
|
248 |
+
project: The name of the project to upload.
|
249 |
+
space_id: The ID of the Space to upload to.
|
250 |
+
"""
|
251 |
+
db_path = SQLiteStorage.get_project_db_path(project)
|
252 |
+
client = Client(space_id, verbose=False)
|
253 |
+
client.predict(
|
254 |
+
api_name="/upload_db_to_space",
|
255 |
+
project=project,
|
256 |
+
uploaded_db=handle_file(db_path),
|
257 |
+
hf_token=huggingface_hub.utils.get_token(),
|
258 |
+
)
|
dummy_commit_scheduler.py
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# A dummy object to fit the interface of huggingface_hub's CommitScheduler
|
2 |
+
class DummyCommitSchedulerLock:
|
3 |
+
def __enter__(self):
|
4 |
+
return None
|
5 |
+
|
6 |
+
def __exit__(self, exception_type, exception_value, exception_traceback):
|
7 |
+
pass
|
8 |
+
|
9 |
+
|
10 |
+
class DummyCommitScheduler:
|
11 |
+
def __init__(self):
|
12 |
+
self.lock = DummyCommitSchedulerLock()
|
file_storage.py
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from pathlib import Path
|
2 |
+
|
3 |
+
try: # absolute imports when installed
|
4 |
+
from trackio.utils import MEDIA_DIR
|
5 |
+
except ImportError: # relative imports for local execution on Spaces
|
6 |
+
from utils import MEDIA_DIR
|
7 |
+
|
8 |
+
|
9 |
+
class FileStorage:
|
10 |
+
@staticmethod
|
11 |
+
def get_project_media_path(
|
12 |
+
project: str,
|
13 |
+
run: str | None = None,
|
14 |
+
step: int | None = None,
|
15 |
+
filename: str | None = None,
|
16 |
+
) -> Path:
|
17 |
+
if filename is not None and step is None:
|
18 |
+
raise ValueError("filename requires step")
|
19 |
+
if step is not None and run is None:
|
20 |
+
raise ValueError("step requires run")
|
21 |
+
|
22 |
+
path = MEDIA_DIR / project
|
23 |
+
if run:
|
24 |
+
path /= run
|
25 |
+
if step is not None:
|
26 |
+
path /= str(step)
|
27 |
+
if filename:
|
28 |
+
path /= filename
|
29 |
+
return path
|
30 |
+
|
31 |
+
@staticmethod
|
32 |
+
def init_project_media_path(
|
33 |
+
project: str, run: str | None = None, step: int | None = None
|
34 |
+
) -> Path:
|
35 |
+
path = FileStorage.get_project_media_path(project, run, step)
|
36 |
+
path.mkdir(parents=True, exist_ok=True)
|
37 |
+
return path
|
histogram.py
ADDED
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Any
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
|
5 |
+
|
6 |
+
class Histogram:
|
7 |
+
"""
|
8 |
+
Histogram data type for Trackio, compatible with wandb.Histogram.
|
9 |
+
|
10 |
+
Example:
|
11 |
+
```python
|
12 |
+
import trackio
|
13 |
+
import numpy as np
|
14 |
+
|
15 |
+
# Create histogram from sequence
|
16 |
+
data = np.random.randn(1000)
|
17 |
+
trackio.log({"distribution": trackio.Histogram(data)})
|
18 |
+
|
19 |
+
# Create histogram from numpy histogram
|
20 |
+
hist, bins = np.histogram(data, bins=30)
|
21 |
+
trackio.log({"distribution": trackio.Histogram(np_histogram=(hist, bins))})
|
22 |
+
|
23 |
+
# Specify custom number of bins
|
24 |
+
trackio.log({"distribution": trackio.Histogram(data, num_bins=50)})
|
25 |
+
```
|
26 |
+
|
27 |
+
Args:
|
28 |
+
sequence: Optional sequence of values to create histogram from
|
29 |
+
np_histogram: Optional pre-computed numpy histogram (hist, bins) tuple
|
30 |
+
num_bins: Number of bins for the histogram (default 64, max 512)
|
31 |
+
"""
|
32 |
+
|
33 |
+
TYPE = "trackio.histogram"
|
34 |
+
|
35 |
+
def __init__(
|
36 |
+
self,
|
37 |
+
sequence: Any = None,
|
38 |
+
np_histogram: tuple | None = None,
|
39 |
+
num_bins: int = 64,
|
40 |
+
):
|
41 |
+
if sequence is None and np_histogram is None:
|
42 |
+
raise ValueError("Must provide either sequence or np_histogram")
|
43 |
+
|
44 |
+
if sequence is not None and np_histogram is not None:
|
45 |
+
raise ValueError("Cannot provide both sequence and np_histogram")
|
46 |
+
|
47 |
+
num_bins = min(num_bins, 512)
|
48 |
+
|
49 |
+
if np_histogram is not None:
|
50 |
+
self.histogram, self.bins = np_histogram
|
51 |
+
self.histogram = np.asarray(self.histogram)
|
52 |
+
self.bins = np.asarray(self.bins)
|
53 |
+
else:
|
54 |
+
data = np.asarray(sequence).flatten()
|
55 |
+
data = data[np.isfinite(data)]
|
56 |
+
if len(data) == 0:
|
57 |
+
self.histogram = np.array([])
|
58 |
+
self.bins = np.array([])
|
59 |
+
else:
|
60 |
+
self.histogram, self.bins = np.histogram(data, bins=num_bins)
|
61 |
+
|
62 |
+
def _to_dict(self) -> dict:
|
63 |
+
"""Convert histogram to dictionary for storage."""
|
64 |
+
return {
|
65 |
+
"_type": self.TYPE,
|
66 |
+
"bins": self.bins.tolist(),
|
67 |
+
"values": self.histogram.tolist(),
|
68 |
+
}
|
imports.py
ADDED
@@ -0,0 +1,302 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from pathlib import Path
|
3 |
+
|
4 |
+
import pandas as pd
|
5 |
+
|
6 |
+
from trackio import deploy, utils
|
7 |
+
from trackio.sqlite_storage import SQLiteStorage
|
8 |
+
|
9 |
+
|
10 |
+
def import_csv(
|
11 |
+
csv_path: str | Path,
|
12 |
+
project: str,
|
13 |
+
name: str | None = None,
|
14 |
+
space_id: str | None = None,
|
15 |
+
dataset_id: str | None = None,
|
16 |
+
private: bool | None = None,
|
17 |
+
) -> None:
|
18 |
+
"""
|
19 |
+
Imports a CSV file into a Trackio project. The CSV file must contain a `"step"`
|
20 |
+
column, may optionally contain a `"timestamp"` column, and any other columns will be
|
21 |
+
treated as metrics. It should also include a header row with the column names.
|
22 |
+
|
23 |
+
TODO: call init() and return a Run object so that the user can continue to log metrics to it.
|
24 |
+
|
25 |
+
Args:
|
26 |
+
csv_path (`str` or `Path`):
|
27 |
+
The str or Path to the CSV file to import.
|
28 |
+
project (`str`):
|
29 |
+
The name of the project to import the CSV file into. Must not be an existing
|
30 |
+
project.
|
31 |
+
name (`str`, *optional*):
|
32 |
+
The name of the Run to import the CSV file into. If not provided, a default
|
33 |
+
name will be generated.
|
34 |
+
name (`str`, *optional*):
|
35 |
+
The name of the run (if not provided, a default name will be generated).
|
36 |
+
space_id (`str`, *optional*):
|
37 |
+
If provided, the project will be logged to a Hugging Face Space instead of a
|
38 |
+
local directory. Should be a complete Space name like `"username/reponame"`
|
39 |
+
or `"orgname/reponame"`, or just `"reponame"` in which case the Space will
|
40 |
+
be created in the currently-logged-in Hugging Face user's namespace. If the
|
41 |
+
Space does not exist, it will be created. If the Space already exists, the
|
42 |
+
project will be logged to it.
|
43 |
+
dataset_id (`str`, *optional*):
|
44 |
+
If provided, a persistent Hugging Face Dataset will be created and the
|
45 |
+
metrics will be synced to it every 5 minutes. Should be a complete Dataset
|
46 |
+
name like `"username/datasetname"` or `"orgname/datasetname"`, or just
|
47 |
+
`"datasetname"` in which case the Dataset will be created in the
|
48 |
+
currently-logged-in Hugging Face user's namespace. If the Dataset does not
|
49 |
+
exist, it will be created. If the Dataset already exists, the project will
|
50 |
+
be appended to it. If not provided, the metrics will be logged to a local
|
51 |
+
SQLite database, unless a `space_id` is provided, in which case a Dataset
|
52 |
+
will be automatically created with the same name as the Space but with the
|
53 |
+
`"_dataset"` suffix.
|
54 |
+
private (`bool`, *optional*):
|
55 |
+
Whether to make the Space private. If None (default), the repo will be
|
56 |
+
public unless the organization's default is private. This value is ignored
|
57 |
+
if the repo already exists.
|
58 |
+
"""
|
59 |
+
if SQLiteStorage.get_runs(project):
|
60 |
+
raise ValueError(
|
61 |
+
f"Project '{project}' already exists. Cannot import CSV into existing project."
|
62 |
+
)
|
63 |
+
|
64 |
+
csv_path = Path(csv_path)
|
65 |
+
if not csv_path.exists():
|
66 |
+
raise FileNotFoundError(f"CSV file not found: {csv_path}")
|
67 |
+
|
68 |
+
df = pd.read_csv(csv_path)
|
69 |
+
if df.empty:
|
70 |
+
raise ValueError("CSV file is empty")
|
71 |
+
|
72 |
+
column_mapping = utils.simplify_column_names(df.columns.tolist())
|
73 |
+
df = df.rename(columns=column_mapping)
|
74 |
+
|
75 |
+
step_column = None
|
76 |
+
for col in df.columns:
|
77 |
+
if col.lower() == "step":
|
78 |
+
step_column = col
|
79 |
+
break
|
80 |
+
|
81 |
+
if step_column is None:
|
82 |
+
raise ValueError("CSV file must contain a 'step' or 'Step' column")
|
83 |
+
|
84 |
+
if name is None:
|
85 |
+
name = csv_path.stem
|
86 |
+
|
87 |
+
metrics_list = []
|
88 |
+
steps = []
|
89 |
+
timestamps = []
|
90 |
+
|
91 |
+
numeric_columns = []
|
92 |
+
for column in df.columns:
|
93 |
+
if column == step_column:
|
94 |
+
continue
|
95 |
+
if column == "timestamp":
|
96 |
+
continue
|
97 |
+
|
98 |
+
try:
|
99 |
+
pd.to_numeric(df[column], errors="raise")
|
100 |
+
numeric_columns.append(column)
|
101 |
+
except (ValueError, TypeError):
|
102 |
+
continue
|
103 |
+
|
104 |
+
for _, row in df.iterrows():
|
105 |
+
metrics = {}
|
106 |
+
for column in numeric_columns:
|
107 |
+
value = row[column]
|
108 |
+
if bool(pd.notna(value)):
|
109 |
+
metrics[column] = float(value)
|
110 |
+
|
111 |
+
if metrics:
|
112 |
+
metrics_list.append(metrics)
|
113 |
+
steps.append(int(row[step_column]))
|
114 |
+
|
115 |
+
if "timestamp" in df.columns and bool(pd.notna(row["timestamp"])):
|
116 |
+
timestamps.append(str(row["timestamp"]))
|
117 |
+
else:
|
118 |
+
timestamps.append("")
|
119 |
+
|
120 |
+
if metrics_list:
|
121 |
+
SQLiteStorage.bulk_log(
|
122 |
+
project=project,
|
123 |
+
run=name,
|
124 |
+
metrics_list=metrics_list,
|
125 |
+
steps=steps,
|
126 |
+
timestamps=timestamps,
|
127 |
+
)
|
128 |
+
|
129 |
+
print(
|
130 |
+
f"* Imported {len(metrics_list)} rows from {csv_path} into project '{project}' as run '{name}'"
|
131 |
+
)
|
132 |
+
print(f"* Metrics found: {', '.join(metrics_list[0].keys())}")
|
133 |
+
|
134 |
+
space_id, dataset_id = utils.preprocess_space_and_dataset_ids(space_id, dataset_id)
|
135 |
+
if dataset_id is not None:
|
136 |
+
os.environ["TRACKIO_DATASET_ID"] = dataset_id
|
137 |
+
print(f"* Trackio metrics will be synced to Hugging Face Dataset: {dataset_id}")
|
138 |
+
|
139 |
+
if space_id is None:
|
140 |
+
utils.print_dashboard_instructions(project)
|
141 |
+
else:
|
142 |
+
deploy.create_space_if_not_exists(
|
143 |
+
space_id=space_id, dataset_id=dataset_id, private=private
|
144 |
+
)
|
145 |
+
deploy.wait_until_space_exists(space_id=space_id)
|
146 |
+
deploy.upload_db_to_space(project=project, space_id=space_id)
|
147 |
+
print(
|
148 |
+
f"* View dashboard by going to: {deploy.SPACE_URL.format(space_id=space_id)}"
|
149 |
+
)
|
150 |
+
|
151 |
+
|
152 |
+
def import_tf_events(
|
153 |
+
log_dir: str | Path,
|
154 |
+
project: str,
|
155 |
+
name: str | None = None,
|
156 |
+
space_id: str | None = None,
|
157 |
+
dataset_id: str | None = None,
|
158 |
+
private: bool | None = None,
|
159 |
+
) -> None:
|
160 |
+
"""
|
161 |
+
Imports TensorFlow Events files from a directory into a Trackio project. Each
|
162 |
+
subdirectory in the log directory will be imported as a separate run.
|
163 |
+
|
164 |
+
Args:
|
165 |
+
log_dir (`str` or `Path`):
|
166 |
+
The str or Path to the directory containing TensorFlow Events files.
|
167 |
+
project (`str`):
|
168 |
+
The name of the project to import the TensorFlow Events files into. Must not
|
169 |
+
be an existing project.
|
170 |
+
name (`str`, *optional*):
|
171 |
+
The name prefix for runs (if not provided, will use directory names). Each
|
172 |
+
subdirectory will create a separate run.
|
173 |
+
space_id (`str`, *optional*):
|
174 |
+
If provided, the project will be logged to a Hugging Face Space instead of a
|
175 |
+
local directory. Should be a complete Space name like `"username/reponame"`
|
176 |
+
or `"orgname/reponame"`, or just `"reponame"` in which case the Space will
|
177 |
+
be created in the currently-logged-in Hugging Face user's namespace. If the
|
178 |
+
Space does not exist, it will be created. If the Space already exists, the
|
179 |
+
project will be logged to it.
|
180 |
+
dataset_id (`str`, *optional*):
|
181 |
+
If provided, a persistent Hugging Face Dataset will be created and the
|
182 |
+
metrics will be synced to it every 5 minutes. Should be a complete Dataset
|
183 |
+
name like `"username/datasetname"` or `"orgname/datasetname"`, or just
|
184 |
+
`"datasetname"` in which case the Dataset will be created in the
|
185 |
+
currently-logged-in Hugging Face user's namespace. If the Dataset does not
|
186 |
+
exist, it will be created. If the Dataset already exists, the project will
|
187 |
+
be appended to it. If not provided, the metrics will be logged to a local
|
188 |
+
SQLite database, unless a `space_id` is provided, in which case a Dataset
|
189 |
+
will be automatically created with the same name as the Space but with the
|
190 |
+
`"_dataset"` suffix.
|
191 |
+
private (`bool`, *optional*):
|
192 |
+
Whether to make the Space private. If None (default), the repo will be
|
193 |
+
public unless the organization's default is private. This value is ignored
|
194 |
+
if the repo already exists.
|
195 |
+
"""
|
196 |
+
try:
|
197 |
+
from tbparse import SummaryReader
|
198 |
+
except ImportError:
|
199 |
+
raise ImportError(
|
200 |
+
"The `tbparse` package is not installed but is required for `import_tf_events`. Please install trackio with the `tensorboard` extra: `pip install trackio[tensorboard]`."
|
201 |
+
)
|
202 |
+
|
203 |
+
if SQLiteStorage.get_runs(project):
|
204 |
+
raise ValueError(
|
205 |
+
f"Project '{project}' already exists. Cannot import TF events into existing project."
|
206 |
+
)
|
207 |
+
|
208 |
+
path = Path(log_dir)
|
209 |
+
if not path.exists():
|
210 |
+
raise FileNotFoundError(f"TF events directory not found: {path}")
|
211 |
+
|
212 |
+
# Use tbparse to read all tfevents files in the directory structure
|
213 |
+
reader = SummaryReader(str(path), extra_columns={"dir_name"})
|
214 |
+
df = reader.scalars
|
215 |
+
|
216 |
+
if df.empty:
|
217 |
+
raise ValueError(f"No TensorFlow events data found in {path}")
|
218 |
+
|
219 |
+
total_imported = 0
|
220 |
+
imported_runs = []
|
221 |
+
|
222 |
+
# Group by dir_name to create separate runs
|
223 |
+
for dir_name, group_df in df.groupby("dir_name"):
|
224 |
+
try:
|
225 |
+
# Determine run name based on directory name
|
226 |
+
if dir_name == "":
|
227 |
+
run_name = "main" # For files in the root directory
|
228 |
+
else:
|
229 |
+
run_name = dir_name # Use directory name
|
230 |
+
|
231 |
+
if name:
|
232 |
+
run_name = f"{name}_{run_name}"
|
233 |
+
|
234 |
+
if group_df.empty:
|
235 |
+
print(f"* Skipping directory {dir_name}: no scalar data found")
|
236 |
+
continue
|
237 |
+
|
238 |
+
metrics_list = []
|
239 |
+
steps = []
|
240 |
+
timestamps = []
|
241 |
+
|
242 |
+
for _, row in group_df.iterrows():
|
243 |
+
# Convert row values to appropriate types
|
244 |
+
tag = str(row["tag"])
|
245 |
+
value = float(row["value"])
|
246 |
+
step = int(row["step"])
|
247 |
+
|
248 |
+
metrics = {tag: value}
|
249 |
+
metrics_list.append(metrics)
|
250 |
+
steps.append(step)
|
251 |
+
|
252 |
+
# Use wall_time if present, else fallback
|
253 |
+
if "wall_time" in group_df.columns and not bool(
|
254 |
+
pd.isna(row["wall_time"])
|
255 |
+
):
|
256 |
+
timestamps.append(str(row["wall_time"]))
|
257 |
+
else:
|
258 |
+
timestamps.append("")
|
259 |
+
|
260 |
+
if metrics_list:
|
261 |
+
SQLiteStorage.bulk_log(
|
262 |
+
project=project,
|
263 |
+
run=str(run_name),
|
264 |
+
metrics_list=metrics_list,
|
265 |
+
steps=steps,
|
266 |
+
timestamps=timestamps,
|
267 |
+
)
|
268 |
+
|
269 |
+
total_imported += len(metrics_list)
|
270 |
+
imported_runs.append(run_name)
|
271 |
+
|
272 |
+
print(
|
273 |
+
f"* Imported {len(metrics_list)} scalar events from directory '{dir_name}' as run '{run_name}'"
|
274 |
+
)
|
275 |
+
print(f"* Metrics in this run: {', '.join(set(group_df['tag']))}")
|
276 |
+
|
277 |
+
except Exception as e:
|
278 |
+
print(f"* Error processing directory {dir_name}: {e}")
|
279 |
+
continue
|
280 |
+
|
281 |
+
if not imported_runs:
|
282 |
+
raise ValueError("No valid TensorFlow events data could be imported")
|
283 |
+
|
284 |
+
print(f"* Total imported events: {total_imported}")
|
285 |
+
print(f"* Created runs: {', '.join(imported_runs)}")
|
286 |
+
|
287 |
+
space_id, dataset_id = utils.preprocess_space_and_dataset_ids(space_id, dataset_id)
|
288 |
+
if dataset_id is not None:
|
289 |
+
os.environ["TRACKIO_DATASET_ID"] = dataset_id
|
290 |
+
print(f"* Trackio metrics will be synced to Hugging Face Dataset: {dataset_id}")
|
291 |
+
|
292 |
+
if space_id is None:
|
293 |
+
utils.print_dashboard_instructions(project)
|
294 |
+
else:
|
295 |
+
deploy.create_space_if_not_exists(
|
296 |
+
space_id, dataset_id=dataset_id, private=private
|
297 |
+
)
|
298 |
+
deploy.wait_until_space_exists(space_id)
|
299 |
+
deploy.upload_db_to_space(project, space_id)
|
300 |
+
print(
|
301 |
+
f"* View dashboard by going to: {deploy.SPACE_URL.format(space_id=space_id)}"
|
302 |
+
)
|