Spaces:
Paused
Paused
File size: 11,408 Bytes
24ea486 |
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 |
#!/usr/bin/env python3
"""
Runtime artifact fetcher for Dressify.
Downloads pre-processed artifacts from Hugging Face Hub to avoid reprocessing.
"""
import os
import json
import shutil
import tarfile
import zipfile
from pathlib import Path
from typing import Dict, List, Any, Optional
from huggingface_hub import hf_hub_download, snapshot_download
class RuntimeArtifactFetcher:
"""Fetches artifacts from HF Hub at runtime to avoid reprocessing."""
def __init__(self, base_dir: str = "/home/user/app"):
self.base_dir = base_dir
self.data_dir = os.path.join(base_dir, "data/Polyvore")
self.splits_dir = os.path.join(self.data_dir, "splits")
self.export_dir = os.getenv("EXPORT_DIR", "models/exports")
# Default HF repositories - updated to use your specific repos
self.default_repos = {
"splits": "Stylique/Dressify-Helper",
"models": "Stylique/dressify-models",
"metadata": "Stylique/Dressify-Helper"
}
def check_artifacts_needed(self) -> Dict[str, Any]:
"""Check what artifacts need to be fetched."""
needs = {
"splits": False,
"models": False,
"metadata": False,
"total_size_mb": 0
}
# Check splits
if not os.path.exists(self.splits_dir) or not self._has_complete_splits():
needs["splits"] = True
needs["total_size_mb"] += 50 # Estimate splits size
# Check models
if not os.path.exists(self.export_dir) or not self._has_trained_models():
needs["models"] = True
needs["total_size_mb"] += 200 # Estimate models size
# Check metadata
if not self._has_complete_metadata():
needs["metadata"] = True
needs["total_size_mb"] += 100 # Estimate metadata size
return needs
def _has_complete_splits(self) -> bool:
"""Check if complete splits are available."""
required_files = [
"train.json", "valid.json", "test.json",
"outfit_triplets_train.json", "outfit_triplets_valid.json", "outfit_triplets_test.json"
]
for file in required_files:
if not os.path.exists(os.path.join(self.splits_dir, file)):
return False
return True
def _has_trained_models(self) -> bool:
"""Check if trained models are available."""
required_files = [
"resnet_item_embedder_best.pth",
"vit_outfit_model_best.pth"
]
for file in required_files:
if not os.path.exists(os.path.join(self.export_dir, file)):
return False
return True
def _has_complete_metadata(self) -> bool:
"""Check if complete metadata is available."""
required_files = [
"polyvore_item_metadata.json",
"polyvore_outfit_titles.json",
"categories.csv"
]
for file in required_files:
if not os.path.exists(os.path.join(self.data_dir, file)):
return False
return True
def fetch_splits_from_hf(self, repo: str = None, token: str = None) -> bool:
"""Fetch dataset splits from HF Hub."""
if repo is None:
repo = self.default_repos["splits"]
try:
print(f"π Fetching splits from {repo}...")
# Create splits directory
os.makedirs(self.splits_dir, exist_ok=True)
# Download splits files
split_files = [
"train.json", "valid.json", "test.json",
"outfits_train.json", "outfits_valid.json", "outfits_test.json",
"outfit_triplets_train.json", "outfit_triplets_valid.json", "outfit_triplets_test.json"
]
for file in split_files:
try:
local_path = hf_hub_download(
repo_id=repo,
filename=f"splits/{file}",
local_dir=self.splits_dir,
token=token
)
print(f"β
Downloaded: {file}")
except Exception as e:
print(f"β οΈ Failed to download {file}: {e}")
print(f"β
Splits fetched successfully to {self.splits_dir}")
return True
except Exception as e:
print(f"β Failed to fetch splits: {e}")
return False
def fetch_models_from_hf(self, repo: str = None, token: str = None) -> bool:
"""Fetch trained models from HF Hub."""
if repo is None:
repo = self.default_repos["models"]
try:
print(f"π Fetching models from {repo}...")
# Create export directory
os.makedirs(self.export_dir, exist_ok=True)
# Download model files
model_files = [
"resnet_item_embedder_best.pth",
"vit_outfit_model_best.pth",
"resnet_metrics.json",
"vit_metrics.json"
]
for file in model_files:
try:
local_path = hf_hub_download(
repo_id=repo,
filename=file,
local_dir=self.export_dir,
token=token
)
print(f"β
Downloaded: {file}")
except Exception as e:
print(f"β οΈ Failed to download {file}: {e}")
print(f"β
Models fetched successfully to {self.export_dir}")
return True
except Exception as e:
print(f"β Failed to fetch models: {e}")
return False
def fetch_metadata_from_hf(self, repo: str = None, token: str = None) -> bool:
"""Fetch metadata from HF Hub."""
if repo is None:
repo = self.default_repos["metadata"]
try:
print(f"π Fetching metadata from {repo}...")
# Create data directory
os.makedirs(self.data_dir, exist_ok=True)
# Download metadata files
metadata_files = [
"polyvore_item_metadata.json",
"polyvore_outfit_titles.json",
"categories.csv"
]
for file in metadata_files:
try:
local_path = hf_hub_download(
repo_id=repo,
filename=f"metadata/{file}",
local_dir=self.data_dir,
token=token
)
print(f"β
Downloaded: {file}")
except Exception as e:
print(f"β οΈ Failed to download {file}: {e}")
print(f"β
Metadata fetched successfully to {self.data_dir}")
return True
except Exception as e:
print(f"β Failed to fetch metadata: {e}")
return False
def fetch_everything_from_hf(self, splits_repo: str = None, models_repo: str = None,
metadata_repo: str = None, token: str = None) -> Dict[str, bool]:
"""Fetch all artifacts from HF Hub."""
results = {}
print("π Starting comprehensive artifact fetch from HF Hub...")
# Fetch splits
results["splits"] = self.fetch_splits_from_hf(splits_repo, token)
# Fetch models
results["models"] = self.fetch_models_from_hf(models_repo, token)
# Fetch metadata
results["metadata"] = self.fetch_metadata_from_hf(metadata_repo, token)
# Summary
success_count = sum(results.values())
total_count = len(results)
print(f"\nπ Fetch Summary: {success_count}/{total_count} successful")
for artifact, success in results.items():
status = "β
" if success else "β"
print(f" {status} {artifact}")
return results
def download_and_extract_package(self, package_path: str, extract_to: str = None) -> bool:
"""Download and extract a package from HF Hub."""
try:
if extract_to is None:
extract_to = self.base_dir
print(f"π Downloading and extracting package: {package_path}")
# Download the package
local_path = hf_hub_download(
repo_id="Stylique/Dressify-Helper",
filename=f"packages/{os.path.basename(package_path)}",
local_dir=extract_to,
token=None
)
# Extract based on file type
if package_path.endswith(".tar.gz"):
with tarfile.open(local_path, 'r:gz') as tar:
tar.extractall(extract_to)
elif package_path.endswith(".zip"):
with zipfile.ZipFile(local_path, 'r') as zipf:
zipf.extractall(extract_to)
print(f"β
Package extracted to {extract_to}")
return True
except Exception as e:
print(f"β Failed to download/extract package: {e}")
return False
def get_fetch_status(self) -> Dict[str, Any]:
"""Get current fetch status."""
return {
"splits_available": self._has_complete_splits(),
"models_available": self._has_trained_models(),
"metadata_available": self._has_complete_metadata(),
"artifacts_needed": self.check_artifacts_needed(),
"base_dir": self.base_dir,
"splits_dir": self.splits_dir,
"export_dir": self.export_dir,
"hf_repos": self.default_repos
}
def create_runtime_fetcher() -> RuntimeArtifactFetcher:
"""Create a runtime fetcher instance."""
return RuntimeArtifactFetcher()
def auto_fetch_if_needed(token: str = None) -> Dict[str, bool]:
"""Automatically fetch artifacts if they're needed."""
fetcher = create_runtime_fetcher()
# Check what's needed
needs = fetcher.check_artifacts_needed()
if not any([needs["splits"], needs["models"], needs["metadata"]]):
print("β
All artifacts are already available - no fetching needed")
return {"splits": True, "models": True, "metadata": True}
print(f"π Auto-fetching needed artifacts (estimated size: {needs['total_size_mb']} MB)")
# Fetch what's needed
results = {}
if needs["splits"]:
results["splits"] = fetcher.fetch_splits_from_hf(token=token)
if needs["models"]:
results["models"] = fetcher.fetch_models_from_hf(token=token)
if needs["metadata"]:
results["metadata"] = fetcher.fetch_metadata_from_hf(token=token)
return results
if __name__ == "__main__":
# Test the fetcher
fetcher = create_runtime_fetcher()
status = fetcher.get_fetch_status()
print("Current fetch status:", json.dumps(status, indent=2))
|