Spaces:
Running
Running
File size: 24,361 Bytes
7af9e82 9c0055f 7af9e82 9c0055f 7af9e82 9c0055f 7af9e82 9c0055f 7af9e82 9c0055f 7af9e82 9c0055f 7af9e82 9c0055f 7af9e82 9c0055f 7af9e82 9c0055f 7af9e82 9c0055f 7af9e82 9c0055f 7af9e82 9c0055f 7af9e82 9c0055f 7af9e82 9c0055f 7af9e82 9c0055f 7af9e82 9c0055f 7af9e82 9c0055f 7af9e82 9c0055f 7af9e82 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 | """
HuggingFace Storage Service
Stores user artifacts (datasets, models, plots, reports) directly to the user's
HuggingFace account, enabling:
1. Persistent storage at no cost
2. Easy model deployment
3. User ownership of data
4. Version control via Git
"""
import os
import json
import gzip
import tempfile
from pathlib import Path
from typing import Optional, Dict, Any, List, BinaryIO, Union
from datetime import datetime
import logging
logger = logging.getLogger(__name__)
# Optional: huggingface_hub for HF operations
try:
from huggingface_hub import HfApi, upload_folder
from huggingface_hub.utils import RepositoryNotFoundError
HF_AVAILABLE = True
except ImportError:
HF_AVAILABLE = False
logger.warning("huggingface_hub not installed. Install with: pip install huggingface_hub")
class HuggingFaceStorage:
"""
Manages file storage on HuggingFace for user artifacts.
Storage structure on HuggingFace:
- Datasets repo: {username}/ds-agent-data
- /datasets/{session_id}/cleaned_data.csv.gz
- /datasets/{session_id}/encoded_data.csv.gz
- Models repo: {username}/ds-agent-models
- /models/{session_id}/{model_name}.pkl
- /models/{session_id}/model_config.json
- Spaces repo (for reports/plots): {username}/ds-agent-outputs
- /plots/{session_id}/correlation_heatmap.json
- /reports/{session_id}/eda_report.html.gz
"""
def __init__(self, hf_token: Optional[str] = None):
"""
Initialize HuggingFace storage.
Args:
hf_token: HuggingFace API token with write permissions
"""
if not HF_AVAILABLE:
raise ImportError("huggingface_hub is required. Install with: pip install huggingface_hub")
self.token = hf_token or os.environ.get("HF_TOKEN")
if not self.token:
raise ValueError("HuggingFace token is required")
self.api = HfApi(token=self.token)
self._username: Optional[str] = None
# Repo names
self.DATA_REPO_SUFFIX = "ds-agent-data"
self.MODELS_REPO_SUFFIX = "ds-agent-models"
self.OUTPUTS_REPO_SUFFIX = "ds-agent-outputs"
@property
def username(self) -> str:
"""Get the authenticated user's username."""
if self._username is None:
user_info = self.api.whoami()
self._username = user_info["name"]
return self._username
def _get_repo_id(self, repo_type: str) -> str:
"""Get the full repo ID for a given type."""
suffix_map = {
"data": self.DATA_REPO_SUFFIX,
"models": self.MODELS_REPO_SUFFIX,
"outputs": self.OUTPUTS_REPO_SUFFIX
}
suffix = suffix_map.get(repo_type, self.OUTPUTS_REPO_SUFFIX)
return f"{self.username}/{suffix}"
def _ensure_repo_exists(self, repo_type: str, repo_kind: str = "dataset") -> str:
"""
Ensure the repository exists, create if not.
Args:
repo_type: "data", "models", or "outputs"
repo_kind: "dataset", "model", or "space"
Returns:
The repo ID
"""
repo_id = self._get_repo_id(repo_type)
try:
self.api.repo_info(repo_id=repo_id, repo_type=repo_kind)
logger.info(f"Repo {repo_id} exists")
except RepositoryNotFoundError:
logger.info(f"Creating repo {repo_id}")
self.api.create_repo(
repo_id=repo_id,
repo_type=repo_kind,
private=True, # Default to private
exist_ok=True # Don't fail if already exists
)
return repo_id
def upload_dataset(
self,
file_path: str,
session_id: str,
file_name: Optional[str] = None,
compress: bool = True,
metadata: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
"""
Upload a dataset (CSV, Parquet) to user's HuggingFace.
Args:
file_path: Local path to the file
session_id: Session ID for organizing files
file_name: Optional custom filename
compress: Whether to gzip compress the file
metadata: Optional metadata to store alongside
Returns:
Dict with upload info (url, path, size, etc.)
"""
repo_id = self._ensure_repo_exists("data", "dataset")
original_path = Path(file_path)
file_name = file_name or original_path.name
# Compress if requested and not already compressed
if compress and not file_name.endswith('.gz'):
with tempfile.NamedTemporaryFile(suffix='.gz', delete=False) as tmp:
with open(file_path, 'rb') as f_in:
with gzip.open(tmp.name, 'wb') as f_out:
f_out.write(f_in.read())
upload_path = tmp.name
file_name = f"{file_name}.gz"
else:
upload_path = file_path
# Upload to HuggingFace
path_in_repo = f"datasets/{session_id}/{file_name}"
try:
result = self.api.upload_file(
path_or_fileobj=upload_path,
path_in_repo=path_in_repo,
repo_id=repo_id,
repo_type="dataset",
commit_message=f"Add dataset: {file_name}"
)
# Upload metadata if provided
if metadata:
metadata_path = f"datasets/{session_id}/{file_name}.meta.json"
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as tmp:
json.dump({
**metadata,
"uploaded_at": datetime.now().isoformat(),
"original_name": original_path.name,
"compressed": compress
}, tmp)
tmp.flush()
self.api.upload_file(
path_or_fileobj=tmp.name,
path_in_repo=metadata_path,
repo_id=repo_id,
repo_type="dataset",
commit_message=f"Add metadata for {file_name}"
)
file_size = os.path.getsize(upload_path)
return {
"success": True,
"repo_id": repo_id,
"path": path_in_repo,
"url": f"https://huggingface.co/datasets/{repo_id}/blob/main/{path_in_repo}",
"download_url": f"https://huggingface.co/datasets/{repo_id}/resolve/main/{path_in_repo}",
"size_bytes": file_size,
"compressed": compress
}
except Exception as e:
logger.error(f"Failed to upload dataset: {e}")
return {
"success": False,
"error": str(e)
}
finally:
# Clean up temp file if we created one
if compress and upload_path != file_path:
try:
os.unlink(upload_path)
except:
pass
def upload_model(
self,
model_path: str,
session_id: str,
model_name: str,
model_type: str = "sklearn",
metrics: Optional[Dict[str, float]] = None,
feature_names: Optional[List[str]] = None,
target_column: Optional[str] = None
) -> Dict[str, Any]:
"""
Upload a trained model to user's HuggingFace.
Args:
model_path: Local path to the model file (.pkl, .joblib, .pt, etc.)
session_id: Session ID
model_name: Name for the model
model_type: Type of model (sklearn, xgboost, pytorch, etc.)
metrics: Model performance metrics
feature_names: List of feature names the model expects
target_column: Target column name
Returns:
Dict with upload info
"""
repo_id = self._ensure_repo_exists("models", "model")
path_in_repo = f"models/{session_id}/{model_name}"
model_file_name = Path(model_path).name
try:
# Upload the model file
self.api.upload_file(
path_or_fileobj=model_path,
path_in_repo=f"{path_in_repo}/{model_file_name}",
repo_id=repo_id,
repo_type="model",
commit_message=f"Add model: {model_name}"
)
# Create and upload model card
model_card = self._generate_model_card(
model_name=model_name,
model_type=model_type,
metrics=metrics,
feature_names=feature_names,
target_column=target_column
)
with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False) as tmp:
tmp.write(model_card)
tmp.flush()
self.api.upload_file(
path_or_fileobj=tmp.name,
path_in_repo=f"{path_in_repo}/README.md",
repo_id=repo_id,
repo_type="model",
commit_message=f"Add model card for {model_name}"
)
# Upload config
config = {
"model_name": model_name,
"model_type": model_type,
"model_file": model_file_name,
"metrics": metrics or {},
"feature_names": feature_names or [],
"target_column": target_column,
"created_at": datetime.now().isoformat(),
"session_id": session_id
}
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as tmp:
json.dump(config, tmp, indent=2)
tmp.flush()
self.api.upload_file(
path_or_fileobj=tmp.name,
path_in_repo=f"{path_in_repo}/config.json",
repo_id=repo_id,
repo_type="model",
commit_message=f"Add config for {model_name}"
)
return {
"success": True,
"repo_id": repo_id,
"path": path_in_repo,
"url": f"https://huggingface.co/{repo_id}/tree/main/{path_in_repo}",
"model_type": model_type,
"metrics": metrics
}
except Exception as e:
logger.error(f"Failed to upload model: {e}")
return {
"success": False,
"error": str(e)
}
def upload_plot(
self,
plot_data: Union[str, Dict],
session_id: str,
plot_name: str,
plot_type: str = "plotly"
) -> Dict[str, Any]:
"""
Upload plot data (as JSON) to user's HuggingFace.
For Plotly charts, we store the JSON data and render client-side,
which is much smaller than storing full HTML.
Args:
plot_data: Either JSON string or dict of plot data
session_id: Session ID
plot_name: Name for the plot
plot_type: Type of plot (plotly, matplotlib, etc.)
Returns:
Dict with upload info
"""
repo_id = self._ensure_repo_exists("outputs", "dataset")
# Ensure we have JSON string
if isinstance(plot_data, dict):
plot_json = json.dumps(plot_data)
else:
plot_json = plot_data
path_in_repo = f"plots/{session_id}/{plot_name}.json"
try:
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as tmp:
tmp.write(plot_json)
tmp.flush()
self.api.upload_file(
path_or_fileobj=tmp.name,
path_in_repo=path_in_repo,
repo_id=repo_id,
repo_type="dataset",
commit_message=f"Add plot: {plot_name}"
)
return {
"success": True,
"repo_id": repo_id,
"path": path_in_repo,
"url": f"https://huggingface.co/datasets/{repo_id}/blob/main/{path_in_repo}",
"download_url": f"https://huggingface.co/datasets/{repo_id}/resolve/main/{path_in_repo}",
"plot_type": plot_type,
"size_bytes": len(plot_json.encode())
}
except Exception as e:
logger.error(f"Failed to upload plot: {e}")
return {
"success": False,
"error": str(e)
}
def upload_report(
self,
report_path: str,
session_id: str,
report_name: str,
compress: bool = True
) -> Dict[str, Any]:
"""
Upload an HTML report to user's HuggingFace.
Args:
report_path: Local path to the HTML report
session_id: Session ID
report_name: Name for the report
compress: Whether to gzip compress
Returns:
Dict with upload info
"""
repo_id = self._ensure_repo_exists("outputs", "dataset")
file_name = f"{report_name}.html"
# Compress if requested
if compress:
with tempfile.NamedTemporaryFile(suffix='.html.gz', delete=False) as tmp:
with open(report_path, 'rb') as f_in:
with gzip.open(tmp.name, 'wb') as f_out:
f_out.write(f_in.read())
upload_path = tmp.name
file_name = f"{file_name}.gz"
else:
upload_path = report_path
path_in_repo = f"reports/{session_id}/{file_name}"
try:
self.api.upload_file(
path_or_fileobj=upload_path,
path_in_repo=path_in_repo,
repo_id=repo_id,
repo_type="dataset",
commit_message=f"Add report: {report_name}"
)
file_size = os.path.getsize(upload_path)
return {
"success": True,
"repo_id": repo_id,
"path": path_in_repo,
"url": f"https://huggingface.co/datasets/{repo_id}/blob/main/{path_in_repo}",
"download_url": f"https://huggingface.co/datasets/{repo_id}/resolve/main/{path_in_repo}",
"size_bytes": file_size,
"compressed": compress
}
except Exception as e:
logger.error(f"Failed to upload report: {e}")
return {
"success": False,
"error": str(e)
}
finally:
if compress and upload_path != report_path:
try:
os.unlink(upload_path)
except:
pass
def upload_generic_file(
self,
file_path: str,
session_id: str,
subfolder: str = "files"
) -> Dict[str, Any]:
"""
Upload any file to user's HuggingFace outputs repo.
Args:
file_path: Local path to the file
session_id: Session ID
subfolder: Subfolder within outputs (e.g., "plots", "images", "files")
Returns:
Dict with upload info
"""
repo_id = self._ensure_repo_exists("outputs", "dataset")
file_name = Path(file_path).name
path_in_repo = f"{subfolder}/{session_id}/{file_name}"
try:
self.api.upload_file(
path_or_fileobj=file_path,
path_in_repo=path_in_repo,
repo_id=repo_id,
repo_type="dataset",
commit_message=f"Add {subfolder}: {file_name}"
)
file_size = os.path.getsize(file_path)
return {
"success": True,
"repo_id": repo_id,
"path": path_in_repo,
"url": f"https://huggingface.co/datasets/{repo_id}/blob/main/{path_in_repo}",
"download_url": f"https://huggingface.co/datasets/{repo_id}/resolve/main/{path_in_repo}",
"size_bytes": file_size
}
except Exception as e:
logger.error(f"Failed to upload file: {e}")
return {
"success": False,
"error": str(e)
}
def list_user_files(
self,
session_id: Optional[str] = None,
file_type: Optional[str] = None
) -> Dict[str, List[Dict[str, Any]]]:
"""
List all files for the user, optionally filtered by session or type.
Args:
session_id: Optional session ID to filter by
file_type: Optional type ("datasets", "models", "plots", "reports")
Returns:
Dict with lists of files by type
"""
result = {
"datasets": [],
"models": [],
"plots": [],
"reports": []
}
try:
# List datasets
if file_type is None or file_type == "datasets":
repo_id = self._get_repo_id("data")
try:
files = self.api.list_repo_files(repo_id=repo_id, repo_type="dataset")
for f in files:
if f.startswith("datasets/") and not f.endswith(".meta.json"):
if session_id is None or f"/{session_id}/" in f:
result["datasets"].append({
"path": f,
"name": Path(f).name,
"session_id": f.split("/")[1] if len(f.split("/")) > 1 else None,
"download_url": f"https://huggingface.co/datasets/{repo_id}/resolve/main/{f}"
})
except:
pass
# List models
if file_type is None or file_type == "models":
repo_id = self._get_repo_id("models")
try:
files = self.api.list_repo_files(repo_id=repo_id, repo_type="model")
for f in files:
if f.startswith("models/") and f.endswith("config.json"):
if session_id is None or f"/{session_id}/" in f:
model_path = "/".join(f.split("/")[:-1])
result["models"].append({
"path": model_path,
"name": f.split("/")[-2] if len(f.split("/")) > 2 else None,
"session_id": f.split("/")[1] if len(f.split("/")) > 1 else None,
"url": f"https://huggingface.co/{repo_id}/tree/main/{model_path}"
})
except:
pass
# List plots and reports
if file_type is None or file_type in ["plots", "reports"]:
repo_id = self._get_repo_id("outputs")
try:
files = self.api.list_repo_files(repo_id=repo_id, repo_type="dataset")
for f in files:
if f.startswith("plots/"):
if session_id is None or f"/{session_id}/" in f:
result["plots"].append({
"path": f,
"name": Path(f).stem,
"session_id": f.split("/")[1] if len(f.split("/")) > 1 else None,
"download_url": f"https://huggingface.co/datasets/{repo_id}/resolve/main/{f}"
})
elif f.startswith("reports/"):
if session_id is None or f"/{session_id}/" in f:
result["reports"].append({
"path": f,
"name": Path(f).stem.replace(".html", ""),
"session_id": f.split("/")[1] if len(f.split("/")) > 1 else None,
"download_url": f"https://huggingface.co/datasets/{repo_id}/resolve/main/{f}"
})
except:
pass
except Exception as e:
logger.error(f"Failed to list files: {e}")
return result
def _generate_model_card(
self,
model_name: str,
model_type: str,
metrics: Optional[Dict[str, float]] = None,
feature_names: Optional[List[str]] = None,
target_column: Optional[str] = None
) -> str:
"""Generate a HuggingFace model card."""
metrics_str = ""
if metrics:
metrics_str = "\n".join([f"- **{k}**: {v:.4f}" for k, v in metrics.items()])
features_str = ""
if feature_names:
features_str = ", ".join(f"`{f}`" for f in feature_names[:20])
if len(feature_names) > 20:
features_str += f" ... and {len(feature_names) - 20} more"
return f"""---
license: apache-2.0
tags:
- tabular
- {model_type}
- ds-agent
---
# {model_name}
This model was trained using [DS Agent](https://huggingface.co/spaces/Pulastya0/Data-Science-Agent),
an AI-powered data science assistant.
## Model Details
- **Model Type**: {model_type}
- **Target Column**: {target_column or "Not specified"}
- **Created**: {datetime.now().strftime("%Y-%m-%d %H:%M")}
## Performance Metrics
{metrics_str or "No metrics recorded"}
## Features
{features_str or "Feature names not recorded"}
## Usage
```python
import joblib
# Load the model
model = joblib.load("model.pkl")
# Make predictions
predictions = model.predict(X_new)
```
## Training
This model was automatically trained using DS Agent's ML pipeline which includes:
- Automated data cleaning
- Feature engineering
- Hyperparameter optimization with Optuna
- Cross-validation
---
*Generated by DS Agent*
"""
def get_user_storage_stats(self) -> Dict[str, Any]:
"""Get storage statistics for the user."""
stats = {
"datasets_count": 0,
"models_count": 0,
"plots_count": 0,
"reports_count": 0,
"total_files": 0
}
files = self.list_user_files()
stats["datasets_count"] = len(files["datasets"])
stats["models_count"] = len(files["models"])
stats["plots_count"] = len(files["plots"])
stats["reports_count"] = len(files["reports"])
stats["total_files"] = sum(stats.values()) - stats["total_files"]
return stats
# Convenience function for creating storage instance
def get_hf_storage(token: str) -> Optional[HuggingFaceStorage]:
"""
Create a HuggingFace storage instance.
Args:
token: HuggingFace API token
Returns:
HuggingFaceStorage instance or None if not available
"""
if not HF_AVAILABLE:
logger.error("huggingface_hub not installed")
return None
try:
return HuggingFaceStorage(hf_token=token)
except Exception as e:
logger.error(f"Failed to create HF storage: {e}")
return None
|