ds-agent-cli 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/ds-agent.js +451 -0
- package/ds_agent/__init__.py +8 -0
- package/package.json +28 -0
- package/requirements.txt +126 -0
- package/setup.py +35 -0
- package/src/__init__.py +7 -0
- package/src/_compress_tool_result.py +118 -0
- package/src/api/__init__.py +4 -0
- package/src/api/app.py +1626 -0
- package/src/cache/__init__.py +5 -0
- package/src/cache/cache_manager.py +561 -0
- package/src/cli.py +2886 -0
- package/src/dynamic_prompts.py +281 -0
- package/src/orchestrator.py +4799 -0
- package/src/progress_manager.py +139 -0
- package/src/reasoning/__init__.py +332 -0
- package/src/reasoning/business_summary.py +431 -0
- package/src/reasoning/data_understanding.py +356 -0
- package/src/reasoning/model_explanation.py +383 -0
- package/src/reasoning/reasoning_trace.py +239 -0
- package/src/registry/__init__.py +3 -0
- package/src/registry/tools_registry.py +3 -0
- package/src/session_memory.py +448 -0
- package/src/session_store.py +370 -0
- package/src/storage/__init__.py +19 -0
- package/src/storage/artifact_store.py +620 -0
- package/src/storage/helpers.py +116 -0
- package/src/storage/huggingface_storage.py +694 -0
- package/src/storage/r2_storage.py +0 -0
- package/src/storage/user_files_service.py +288 -0
- package/src/tools/__init__.py +335 -0
- package/src/tools/advanced_analysis.py +823 -0
- package/src/tools/advanced_feature_engineering.py +708 -0
- package/src/tools/advanced_insights.py +578 -0
- package/src/tools/advanced_preprocessing.py +549 -0
- package/src/tools/advanced_training.py +906 -0
- package/src/tools/agent_tool_mapping.py +326 -0
- package/src/tools/auto_pipeline.py +420 -0
- package/src/tools/autogluon_training.py +1480 -0
- package/src/tools/business_intelligence.py +860 -0
- package/src/tools/cloud_data_sources.py +581 -0
- package/src/tools/code_interpreter.py +390 -0
- package/src/tools/computer_vision.py +614 -0
- package/src/tools/data_cleaning.py +614 -0
- package/src/tools/data_profiling.py +593 -0
- package/src/tools/data_type_conversion.py +268 -0
- package/src/tools/data_wrangling.py +433 -0
- package/src/tools/eda_reports.py +284 -0
- package/src/tools/enhanced_feature_engineering.py +241 -0
- package/src/tools/feature_engineering.py +302 -0
- package/src/tools/matplotlib_visualizations.py +1327 -0
- package/src/tools/model_training.py +520 -0
- package/src/tools/nlp_text_analytics.py +761 -0
- package/src/tools/plotly_visualizations.py +497 -0
- package/src/tools/production_mlops.py +852 -0
- package/src/tools/time_series.py +507 -0
- package/src/tools/tools_registry.py +2133 -0
- package/src/tools/visualization_engine.py +559 -0
- package/src/utils/__init__.py +42 -0
- package/src/utils/error_recovery.py +313 -0
- package/src/utils/parallel_executor.py +402 -0
- package/src/utils/polars_helpers.py +248 -0
- package/src/utils/schema_extraction.py +132 -0
- package/src/utils/semantic_layer.py +392 -0
- package/src/utils/token_budget.py +411 -0
- package/src/utils/validation.py +377 -0
- package/src/workflow_state.py +154 -0
|
@@ -0,0 +1,620 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Artifact Storage Abstraction Layer
|
|
3
|
+
|
|
4
|
+
Provides unified interface for saving models, plots, reports, and data files
|
|
5
|
+
to either local filesystem or Google Cloud Storage (GCS).
|
|
6
|
+
|
|
7
|
+
Design Principles:
|
|
8
|
+
- Backend chosen via environment variable (ARTIFACT_BACKEND=local|gcs)
|
|
9
|
+
- Tools never know which backend is used (clean separation)
|
|
10
|
+
- GCS paths versioned with timestamps for reproducibility
|
|
11
|
+
- Consistent return format: local paths or GCS URIs
|
|
12
|
+
- Graceful fallback to local if GCS unavailable
|
|
13
|
+
|
|
14
|
+
Architecture:
|
|
15
|
+
Tool → ArtifactStore → LocalBackend / GCSBackend
|
|
16
|
+
|
|
17
|
+
Usage:
|
|
18
|
+
from storage import get_artifact_store
|
|
19
|
+
|
|
20
|
+
store = get_artifact_store()
|
|
21
|
+
|
|
22
|
+
# Save model
|
|
23
|
+
path = store.save_model("model.pkl", metadata={"accuracy": 0.95})
|
|
24
|
+
|
|
25
|
+
# Save plot
|
|
26
|
+
path = store.save_plot("correlation_heatmap.html")
|
|
27
|
+
|
|
28
|
+
# Save report
|
|
29
|
+
path = store.save_report("eda_report.html")
|
|
30
|
+
|
|
31
|
+
# Save data file
|
|
32
|
+
path = store.save_data("cleaned_data.csv")
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
import os
|
|
36
|
+
import json
|
|
37
|
+
from pathlib import Path
|
|
38
|
+
from datetime import datetime
|
|
39
|
+
from typing import Dict, Any, Optional, Union
|
|
40
|
+
from abc import ABC, abstractmethod
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class StorageBackend(ABC):
|
|
44
|
+
"""Abstract base class for storage backends."""
|
|
45
|
+
|
|
46
|
+
@abstractmethod
|
|
47
|
+
def save_file(
|
|
48
|
+
self,
|
|
49
|
+
local_path: Union[str, Path],
|
|
50
|
+
artifact_type: str,
|
|
51
|
+
metadata: Optional[Dict[str, Any]] = None
|
|
52
|
+
) -> str:
|
|
53
|
+
"""
|
|
54
|
+
Save file to backend storage.
|
|
55
|
+
|
|
56
|
+
Args:
|
|
57
|
+
local_path: Path to local file to save
|
|
58
|
+
artifact_type: Type of artifact (model, plot, report, data)
|
|
59
|
+
metadata: Optional metadata to save alongside artifact
|
|
60
|
+
|
|
61
|
+
Returns:
|
|
62
|
+
Storage path or URI where file was saved
|
|
63
|
+
"""
|
|
64
|
+
pass
|
|
65
|
+
|
|
66
|
+
@abstractmethod
|
|
67
|
+
def list_artifacts(self, artifact_type: str) -> list[str]:
|
|
68
|
+
"""List all artifacts of given type."""
|
|
69
|
+
pass
|
|
70
|
+
|
|
71
|
+
@abstractmethod
|
|
72
|
+
def get_artifact_path(self, artifact_type: str, filename: str) -> str:
|
|
73
|
+
"""Get full path/URI for an artifact."""
|
|
74
|
+
pass
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class LocalBackend(StorageBackend):
|
|
78
|
+
"""
|
|
79
|
+
Local filesystem storage backend.
|
|
80
|
+
|
|
81
|
+
Preserves existing behavior - saves to ./outputs/ directory structure.
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
def __init__(self, base_dir: str = "./outputs"):
|
|
85
|
+
"""
|
|
86
|
+
Initialize local backend.
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
base_dir: Base directory for all artifacts (default: ./outputs)
|
|
90
|
+
"""
|
|
91
|
+
self.base_dir = Path(base_dir)
|
|
92
|
+
|
|
93
|
+
# Create subdirectories
|
|
94
|
+
self.subdirs = {
|
|
95
|
+
"model": self.base_dir / "models",
|
|
96
|
+
"plot": self.base_dir / "plots",
|
|
97
|
+
"report": self.base_dir / "reports",
|
|
98
|
+
"data": self.base_dir / "data",
|
|
99
|
+
"code": self.base_dir / "code"
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
for subdir in self.subdirs.values():
|
|
103
|
+
subdir.mkdir(parents=True, exist_ok=True)
|
|
104
|
+
|
|
105
|
+
def save_file(
|
|
106
|
+
self,
|
|
107
|
+
local_path: Union[str, Path],
|
|
108
|
+
artifact_type: str,
|
|
109
|
+
metadata: Optional[Dict[str, Any]] = None
|
|
110
|
+
) -> str:
|
|
111
|
+
"""
|
|
112
|
+
Save file to local filesystem.
|
|
113
|
+
|
|
114
|
+
Args:
|
|
115
|
+
local_path: Path to source file
|
|
116
|
+
artifact_type: Type (model, plot, report, data, code)
|
|
117
|
+
metadata: Optional metadata (saved as JSON sidecar)
|
|
118
|
+
|
|
119
|
+
Returns:
|
|
120
|
+
Absolute path where file was saved
|
|
121
|
+
"""
|
|
122
|
+
local_path = Path(local_path)
|
|
123
|
+
|
|
124
|
+
if not local_path.exists():
|
|
125
|
+
raise FileNotFoundError(f"Source file not found: {local_path}")
|
|
126
|
+
|
|
127
|
+
# Determine target directory
|
|
128
|
+
target_dir = self.subdirs.get(artifact_type)
|
|
129
|
+
if target_dir is None:
|
|
130
|
+
raise ValueError(
|
|
131
|
+
f"Unknown artifact type: {artifact_type}. "
|
|
132
|
+
f"Must be one of: {list(self.subdirs.keys())}"
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
# Preserve filename
|
|
136
|
+
target_path = target_dir / local_path.name
|
|
137
|
+
|
|
138
|
+
# Copy file (if not already in target location)
|
|
139
|
+
if local_path.resolve() != target_path.resolve():
|
|
140
|
+
import shutil
|
|
141
|
+
shutil.copy2(local_path, target_path)
|
|
142
|
+
|
|
143
|
+
# Save metadata if provided
|
|
144
|
+
if metadata:
|
|
145
|
+
metadata_path = target_path.with_suffix(target_path.suffix + ".meta.json")
|
|
146
|
+
with open(metadata_path, "w") as f:
|
|
147
|
+
json.dump({
|
|
148
|
+
"artifact_type": artifact_type,
|
|
149
|
+
"filename": local_path.name,
|
|
150
|
+
"timestamp": datetime.utcnow().isoformat(),
|
|
151
|
+
"backend": "local",
|
|
152
|
+
**metadata
|
|
153
|
+
}, f, indent=2)
|
|
154
|
+
|
|
155
|
+
return str(target_path.resolve())
|
|
156
|
+
|
|
157
|
+
def list_artifacts(self, artifact_type: str) -> list[str]:
|
|
158
|
+
"""List all artifacts of given type in local storage."""
|
|
159
|
+
# Validate artifact type
|
|
160
|
+
valid_types = ["model", "plot", "report", "data", "code"]
|
|
161
|
+
if artifact_type not in valid_types:
|
|
162
|
+
raise ValueError(
|
|
163
|
+
f"Invalid artifact type: {artifact_type}. "
|
|
164
|
+
f"Must be one of: {', '.join(valid_types)}"
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
target_dir = self.subdirs.get(artifact_type)
|
|
168
|
+
if target_dir is None or not target_dir.exists():
|
|
169
|
+
return []
|
|
170
|
+
|
|
171
|
+
# Exclude metadata files
|
|
172
|
+
return [
|
|
173
|
+
str(f.resolve())
|
|
174
|
+
for f in target_dir.iterdir()
|
|
175
|
+
if f.is_file() and not f.name.endswith(".meta.json")
|
|
176
|
+
]
|
|
177
|
+
|
|
178
|
+
def get_artifact_path(self, artifact_type: str, filename: str) -> str:
|
|
179
|
+
"""Get full local path for artifact."""
|
|
180
|
+
target_dir = self.subdirs.get(artifact_type)
|
|
181
|
+
if target_dir is None:
|
|
182
|
+
raise ValueError(f"Unknown artifact type: {artifact_type}")
|
|
183
|
+
|
|
184
|
+
return str((target_dir / filename).resolve())
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
class GCSBackend(StorageBackend):
|
|
188
|
+
"""
|
|
189
|
+
Google Cloud Storage backend.
|
|
190
|
+
|
|
191
|
+
Saves artifacts to GCS bucket with versioned paths.
|
|
192
|
+
"""
|
|
193
|
+
|
|
194
|
+
def __init__(
|
|
195
|
+
self,
|
|
196
|
+
bucket_name: Optional[str] = None,
|
|
197
|
+
project_id: Optional[str] = None,
|
|
198
|
+
base_prefix: str = "artifacts"
|
|
199
|
+
):
|
|
200
|
+
"""
|
|
201
|
+
Initialize GCS backend.
|
|
202
|
+
|
|
203
|
+
Args:
|
|
204
|
+
bucket_name: GCS bucket name (from env: GCS_BUCKET_NAME)
|
|
205
|
+
project_id: GCP project ID (from env: GCP_PROJECT_ID)
|
|
206
|
+
base_prefix: Base prefix for all artifacts (default: artifacts)
|
|
207
|
+
"""
|
|
208
|
+
try:
|
|
209
|
+
from google.cloud import storage
|
|
210
|
+
from google.auth import default as gcp_default
|
|
211
|
+
except ImportError:
|
|
212
|
+
raise ImportError(
|
|
213
|
+
"GCS backend requires google-cloud-storage. "
|
|
214
|
+
"Install with: pip install google-cloud-storage"
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
# Get configuration from environment
|
|
218
|
+
self.bucket_name = bucket_name or os.getenv("GCS_BUCKET_NAME")
|
|
219
|
+
self.project_id = project_id or os.getenv("GCP_PROJECT_ID")
|
|
220
|
+
self.base_prefix = base_prefix
|
|
221
|
+
|
|
222
|
+
if not self.bucket_name:
|
|
223
|
+
raise ValueError(
|
|
224
|
+
"GCS bucket name not specified. "
|
|
225
|
+
"Set GCS_BUCKET_NAME environment variable or pass bucket_name."
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
# Initialize GCS client
|
|
229
|
+
try:
|
|
230
|
+
if self.project_id:
|
|
231
|
+
self.client = storage.Client(project=self.project_id)
|
|
232
|
+
else:
|
|
233
|
+
# Use default credentials
|
|
234
|
+
credentials, project = gcp_default()
|
|
235
|
+
self.client = storage.Client(credentials=credentials, project=project)
|
|
236
|
+
self.project_id = project
|
|
237
|
+
except Exception as e:
|
|
238
|
+
raise RuntimeError(
|
|
239
|
+
f"Failed to initialize GCS client: {e}\n"
|
|
240
|
+
"Ensure credentials are configured (GOOGLE_APPLICATION_CREDENTIALS "
|
|
241
|
+
"or gcloud auth application-default login)"
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
# Get bucket
|
|
245
|
+
try:
|
|
246
|
+
self.bucket = self.client.bucket(self.bucket_name)
|
|
247
|
+
# Verify bucket exists
|
|
248
|
+
if not self.bucket.exists():
|
|
249
|
+
raise ValueError(f"Bucket '{self.bucket_name}' does not exist")
|
|
250
|
+
except Exception as e:
|
|
251
|
+
raise RuntimeError(f"Failed to access bucket '{self.bucket_name}': {e}")
|
|
252
|
+
|
|
253
|
+
def _get_versioned_path(self, artifact_type: str, filename: str) -> str:
|
|
254
|
+
"""
|
|
255
|
+
Generate versioned GCS path.
|
|
256
|
+
|
|
257
|
+
Format: artifacts/{type}/{YYYY-MM-DD}/{timestamp}_{filename}
|
|
258
|
+
|
|
259
|
+
Example: artifacts/models/2025-12-23/20251223_143052_model.pkl
|
|
260
|
+
"""
|
|
261
|
+
timestamp = datetime.utcnow()
|
|
262
|
+
date_str = timestamp.strftime("%Y-%m-%d")
|
|
263
|
+
time_str = timestamp.strftime("%Y%m%d_%H%M%S")
|
|
264
|
+
|
|
265
|
+
versioned_filename = f"{time_str}_{filename}"
|
|
266
|
+
|
|
267
|
+
return f"{self.base_prefix}/{artifact_type}/{date_str}/{versioned_filename}"
|
|
268
|
+
|
|
269
|
+
def save_file(
|
|
270
|
+
self,
|
|
271
|
+
local_path: Union[str, Path],
|
|
272
|
+
artifact_type: str,
|
|
273
|
+
metadata: Optional[Dict[str, Any]] = None
|
|
274
|
+
) -> str:
|
|
275
|
+
"""
|
|
276
|
+
Upload file to GCS with versioned path.
|
|
277
|
+
|
|
278
|
+
Args:
|
|
279
|
+
local_path: Path to local file to upload
|
|
280
|
+
artifact_type: Type (model, plot, report, data, code)
|
|
281
|
+
metadata: Optional metadata (stored as blob metadata)
|
|
282
|
+
|
|
283
|
+
Returns:
|
|
284
|
+
GCS URI (gs://bucket/path)
|
|
285
|
+
"""
|
|
286
|
+
local_path = Path(local_path)
|
|
287
|
+
|
|
288
|
+
if not local_path.exists():
|
|
289
|
+
raise FileNotFoundError(f"Source file not found: {local_path}")
|
|
290
|
+
|
|
291
|
+
# Generate versioned path
|
|
292
|
+
gcs_path = self._get_versioned_path(artifact_type, local_path.name)
|
|
293
|
+
|
|
294
|
+
# Create blob
|
|
295
|
+
blob = self.bucket.blob(gcs_path)
|
|
296
|
+
|
|
297
|
+
# Set metadata
|
|
298
|
+
if metadata:
|
|
299
|
+
blob.metadata = {
|
|
300
|
+
"artifact_type": artifact_type,
|
|
301
|
+
"filename": local_path.name,
|
|
302
|
+
"timestamp": datetime.utcnow().isoformat(),
|
|
303
|
+
"backend": "gcs",
|
|
304
|
+
**{k: str(v) for k, v in metadata.items()} # Convert all to strings
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
# Upload file
|
|
308
|
+
try:
|
|
309
|
+
blob.upload_from_filename(str(local_path))
|
|
310
|
+
except Exception as e:
|
|
311
|
+
raise RuntimeError(f"Failed to upload to GCS: {e}")
|
|
312
|
+
|
|
313
|
+
# Return GCS URI
|
|
314
|
+
gcs_uri = f"gs://{self.bucket_name}/{gcs_path}"
|
|
315
|
+
|
|
316
|
+
return gcs_uri
|
|
317
|
+
|
|
318
|
+
def list_artifacts(self, artifact_type: str) -> list[str]:
|
|
319
|
+
"""List all artifacts of given type in GCS."""
|
|
320
|
+
# Validate artifact type
|
|
321
|
+
valid_types = ["model", "plot", "report", "data", "code"]
|
|
322
|
+
if artifact_type not in valid_types:
|
|
323
|
+
raise ValueError(
|
|
324
|
+
f"Invalid artifact type: {artifact_type}. "
|
|
325
|
+
f"Must be one of: {', '.join(valid_types)}"
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
prefix = f"{self.base_prefix}/{artifact_type}/"
|
|
329
|
+
|
|
330
|
+
try:
|
|
331
|
+
blobs = self.client.list_blobs(self.bucket, prefix=prefix)
|
|
332
|
+
return [f"gs://{self.bucket_name}/{blob.name}" for blob in blobs]
|
|
333
|
+
except Exception as e:
|
|
334
|
+
raise RuntimeError(f"Failed to list GCS artifacts: {e}")
|
|
335
|
+
|
|
336
|
+
def get_artifact_path(self, artifact_type: str, filename: str) -> str:
|
|
337
|
+
"""Get latest GCS path for artifact (most recent version)."""
|
|
338
|
+
artifacts = self.list_artifacts(artifact_type)
|
|
339
|
+
|
|
340
|
+
# Filter by filename (strip timestamp prefix)
|
|
341
|
+
matching = [
|
|
342
|
+
uri for uri in artifacts
|
|
343
|
+
if uri.endswith(f"_{filename}") or uri.endswith(f"/{filename}")
|
|
344
|
+
]
|
|
345
|
+
|
|
346
|
+
if not matching:
|
|
347
|
+
raise FileNotFoundError(
|
|
348
|
+
f"No artifact found with filename '{filename}' in type '{artifact_type}'"
|
|
349
|
+
)
|
|
350
|
+
|
|
351
|
+
# Return most recent (last in sorted list)
|
|
352
|
+
return sorted(matching)[-1]
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
class ArtifactStore:
|
|
356
|
+
"""
|
|
357
|
+
Unified interface for artifact storage.
|
|
358
|
+
|
|
359
|
+
Automatically routes to correct backend based on configuration.
|
|
360
|
+
Tools use this class and never directly interact with backends.
|
|
361
|
+
"""
|
|
362
|
+
|
|
363
|
+
def __init__(self, backend: Optional[StorageBackend] = None):
|
|
364
|
+
"""
|
|
365
|
+
Initialize artifact store with backend.
|
|
366
|
+
|
|
367
|
+
Args:
|
|
368
|
+
backend: Storage backend (auto-detected if None)
|
|
369
|
+
"""
|
|
370
|
+
if backend is None:
|
|
371
|
+
backend = self._detect_backend()
|
|
372
|
+
|
|
373
|
+
self.backend = backend
|
|
374
|
+
|
|
375
|
+
def _detect_backend(self) -> StorageBackend:
|
|
376
|
+
"""
|
|
377
|
+
Detect and initialize appropriate backend.
|
|
378
|
+
|
|
379
|
+
Detection logic:
|
|
380
|
+
1. Check ARTIFACT_BACKEND env var (local|gcs)
|
|
381
|
+
2. If GCS, check for GCS_BUCKET_NAME
|
|
382
|
+
3. Fall back to local if anything fails
|
|
383
|
+
|
|
384
|
+
Returns:
|
|
385
|
+
Initialized storage backend
|
|
386
|
+
"""
|
|
387
|
+
backend_type = os.getenv("ARTIFACT_BACKEND", "local").lower()
|
|
388
|
+
|
|
389
|
+
if backend_type == "gcs":
|
|
390
|
+
try:
|
|
391
|
+
# Try to initialize GCS
|
|
392
|
+
bucket_name = os.getenv("GCS_BUCKET_NAME")
|
|
393
|
+
if not bucket_name:
|
|
394
|
+
print("⚠️ GCS backend requested but GCS_BUCKET_NAME not set. Falling back to local.")
|
|
395
|
+
return LocalBackend()
|
|
396
|
+
|
|
397
|
+
print(f"🔵 Initializing GCS backend (bucket: {bucket_name})")
|
|
398
|
+
return GCSBackend(bucket_name=bucket_name)
|
|
399
|
+
|
|
400
|
+
except Exception as e:
|
|
401
|
+
print(f"⚠️ GCS backend initialization failed: {e}")
|
|
402
|
+
print(" Falling back to local storage.")
|
|
403
|
+
return LocalBackend()
|
|
404
|
+
|
|
405
|
+
elif backend_type == "local":
|
|
406
|
+
print("📁 Using local filesystem backend")
|
|
407
|
+
return LocalBackend()
|
|
408
|
+
|
|
409
|
+
else:
|
|
410
|
+
print(f"⚠️ Unknown ARTIFACT_BACKEND: {backend_type}. Using local.")
|
|
411
|
+
return LocalBackend()
|
|
412
|
+
|
|
413
|
+
def save_model(
|
|
414
|
+
self,
|
|
415
|
+
local_path: Union[str, Path],
|
|
416
|
+
metadata: Optional[Dict[str, Any]] = None
|
|
417
|
+
) -> str:
|
|
418
|
+
"""
|
|
419
|
+
Save machine learning model.
|
|
420
|
+
|
|
421
|
+
Args:
|
|
422
|
+
local_path: Path to model file (e.g., model.pkl)
|
|
423
|
+
metadata: Optional metadata (accuracy, hyperparameters, etc.)
|
|
424
|
+
|
|
425
|
+
Returns:
|
|
426
|
+
Storage path or URI where model was saved
|
|
427
|
+
|
|
428
|
+
Example:
|
|
429
|
+
store = ArtifactStore()
|
|
430
|
+
path = store.save_model(
|
|
431
|
+
"model.pkl",
|
|
432
|
+
metadata={"accuracy": 0.95, "model_type": "RandomForest"}
|
|
433
|
+
)
|
|
434
|
+
"""
|
|
435
|
+
return self.backend.save_file(local_path, "model", metadata)
|
|
436
|
+
|
|
437
|
+
def save_plot(
|
|
438
|
+
self,
|
|
439
|
+
local_path: Union[str, Path],
|
|
440
|
+
metadata: Optional[Dict[str, Any]] = None
|
|
441
|
+
) -> str:
|
|
442
|
+
"""
|
|
443
|
+
Save visualization plot.
|
|
444
|
+
|
|
445
|
+
Args:
|
|
446
|
+
local_path: Path to plot file (e.g., plot.html, plot.png)
|
|
447
|
+
metadata: Optional metadata (plot type, columns, etc.)
|
|
448
|
+
|
|
449
|
+
Returns:
|
|
450
|
+
Storage path or URI where plot was saved
|
|
451
|
+
|
|
452
|
+
Example:
|
|
453
|
+
store = ArtifactStore()
|
|
454
|
+
path = store.save_plot(
|
|
455
|
+
"correlation_heatmap.html",
|
|
456
|
+
metadata={"plot_type": "heatmap", "columns": ["age", "income"]}
|
|
457
|
+
)
|
|
458
|
+
"""
|
|
459
|
+
return self.backend.save_file(local_path, "plot", metadata)
|
|
460
|
+
|
|
461
|
+
def save_report(
|
|
462
|
+
self,
|
|
463
|
+
local_path: Union[str, Path],
|
|
464
|
+
metadata: Optional[Dict[str, Any]] = None
|
|
465
|
+
) -> str:
|
|
466
|
+
"""
|
|
467
|
+
Save analysis report.
|
|
468
|
+
|
|
469
|
+
Args:
|
|
470
|
+
local_path: Path to report file (e.g., report.html)
|
|
471
|
+
metadata: Optional metadata (report type, dataset, etc.)
|
|
472
|
+
|
|
473
|
+
Returns:
|
|
474
|
+
Storage path or URI where report was saved
|
|
475
|
+
|
|
476
|
+
Example:
|
|
477
|
+
store = ArtifactStore()
|
|
478
|
+
path = store.save_report(
|
|
479
|
+
"eda_report.html",
|
|
480
|
+
metadata={"report_type": "ydata_profiling", "dataset": "titanic"}
|
|
481
|
+
)
|
|
482
|
+
"""
|
|
483
|
+
return self.backend.save_file(local_path, "report", metadata)
|
|
484
|
+
|
|
485
|
+
def save_data(
|
|
486
|
+
self,
|
|
487
|
+
local_path: Union[str, Path],
|
|
488
|
+
metadata: Optional[Dict[str, Any]] = None
|
|
489
|
+
) -> str:
|
|
490
|
+
"""
|
|
491
|
+
Save processed data file.
|
|
492
|
+
|
|
493
|
+
Args:
|
|
494
|
+
local_path: Path to data file (e.g., cleaned.csv)
|
|
495
|
+
metadata: Optional metadata (transformation steps, row count, etc.)
|
|
496
|
+
|
|
497
|
+
Returns:
|
|
498
|
+
Storage path or URI where data was saved
|
|
499
|
+
|
|
500
|
+
Example:
|
|
501
|
+
store = ArtifactStore()
|
|
502
|
+
path = store.save_data(
|
|
503
|
+
"cleaned_data.csv",
|
|
504
|
+
metadata={"rows": 1000, "columns": 20, "transformations": ["drop_na", "encode"]}
|
|
505
|
+
)
|
|
506
|
+
"""
|
|
507
|
+
return self.backend.save_file(local_path, "data", metadata)
|
|
508
|
+
|
|
509
|
+
def save_code(
|
|
510
|
+
self,
|
|
511
|
+
local_path: Union[str, Path],
|
|
512
|
+
metadata: Optional[Dict[str, Any]] = None
|
|
513
|
+
) -> str:
|
|
514
|
+
"""
|
|
515
|
+
Save code interpreter output.
|
|
516
|
+
|
|
517
|
+
Args:
|
|
518
|
+
local_path: Path to code output file
|
|
519
|
+
metadata: Optional metadata (execution time, etc.)
|
|
520
|
+
|
|
521
|
+
Returns:
|
|
522
|
+
Storage path or URI where file was saved
|
|
523
|
+
"""
|
|
524
|
+
return self.backend.save_file(local_path, "code", metadata)
|
|
525
|
+
|
|
526
|
+
def list_artifacts(self, artifact_type: str) -> list[str]:
|
|
527
|
+
"""
|
|
528
|
+
List all artifacts of a specific type.
|
|
529
|
+
|
|
530
|
+
Args:
|
|
531
|
+
artifact_type: Type of artifact (model, plot, report, data, code)
|
|
532
|
+
|
|
533
|
+
Returns:
|
|
534
|
+
List of artifact paths or URIs
|
|
535
|
+
|
|
536
|
+
Example:
|
|
537
|
+
store = ArtifactStore()
|
|
538
|
+
models = store.list_artifacts("model")
|
|
539
|
+
plots = store.list_artifacts("plot")
|
|
540
|
+
"""
|
|
541
|
+
return self.backend.list_artifacts(artifact_type)
|
|
542
|
+
|
|
543
|
+
def list_models(self) -> list[str]:
|
|
544
|
+
"""List all saved models."""
|
|
545
|
+
return self.backend.list_artifacts("model")
|
|
546
|
+
|
|
547
|
+
def list_plots(self) -> list[str]:
|
|
548
|
+
"""List all saved plots."""
|
|
549
|
+
return self.backend.list_artifacts("plot")
|
|
550
|
+
|
|
551
|
+
def list_reports(self) -> list[str]:
|
|
552
|
+
"""List all saved reports."""
|
|
553
|
+
return self.backend.list_artifacts("report")
|
|
554
|
+
|
|
555
|
+
def list_data_files(self) -> list[str]:
|
|
556
|
+
"""List all saved data files."""
|
|
557
|
+
return self.backend.list_artifacts("data")
|
|
558
|
+
|
|
559
|
+
def get_backend_info(self) -> Dict[str, Any]:
|
|
560
|
+
"""
|
|
561
|
+
Get information about current backend.
|
|
562
|
+
|
|
563
|
+
Returns:
|
|
564
|
+
Backend configuration details
|
|
565
|
+
"""
|
|
566
|
+
if isinstance(self.backend, LocalBackend):
|
|
567
|
+
return {
|
|
568
|
+
"type": "local",
|
|
569
|
+
"base_path": str(self.backend.base_dir.resolve()),
|
|
570
|
+
"base_dir": str(self.backend.base_dir.resolve()),
|
|
571
|
+
"subdirs": {k: str(v) for k, v in self.backend.subdirs.items()}
|
|
572
|
+
}
|
|
573
|
+
elif isinstance(self.backend, GCSBackend):
|
|
574
|
+
return {
|
|
575
|
+
"type": "gcs",
|
|
576
|
+
"base_path": f"gs://{self.backend.bucket_name}/{self.backend.base_prefix}",
|
|
577
|
+
"bucket": self.backend.bucket_name,
|
|
578
|
+
"project": self.backend.project_id,
|
|
579
|
+
"base_prefix": self.backend.base_prefix
|
|
580
|
+
}
|
|
581
|
+
else:
|
|
582
|
+
return {"type": "unknown", "base_path": "unknown"}
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
# Singleton instance
|
|
586
|
+
_artifact_store_instance: Optional[ArtifactStore] = None
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
def get_artifact_store(backend: Optional[StorageBackend] = None) -> ArtifactStore:
|
|
590
|
+
"""
|
|
591
|
+
Get singleton instance of ArtifactStore.
|
|
592
|
+
|
|
593
|
+
This ensures all tools use the same backend configuration.
|
|
594
|
+
|
|
595
|
+
Args:
|
|
596
|
+
backend: Optional backend (for testing or custom configuration)
|
|
597
|
+
|
|
598
|
+
Returns:
|
|
599
|
+
Singleton ArtifactStore instance
|
|
600
|
+
|
|
601
|
+
Example:
|
|
602
|
+
from storage import get_artifact_store
|
|
603
|
+
|
|
604
|
+
store = get_artifact_store()
|
|
605
|
+
path = store.save_model("model.pkl", metadata={"accuracy": 0.95})
|
|
606
|
+
"""
|
|
607
|
+
global _artifact_store_instance
|
|
608
|
+
|
|
609
|
+
if _artifact_store_instance is None or backend is not None:
|
|
610
|
+
_artifact_store_instance = ArtifactStore(backend=backend)
|
|
611
|
+
|
|
612
|
+
return _artifact_store_instance
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def reset_artifact_store():
|
|
616
|
+
"""
|
|
617
|
+
Reset singleton instance (useful for testing).
|
|
618
|
+
"""
|
|
619
|
+
global _artifact_store_instance
|
|
620
|
+
_artifact_store_instance = None
|