|
| 1 | +"""S3 Bucket data loader with local caching (HuggingFace-style).""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import hashlib |
| 6 | +import logging |
| 7 | +import shutil |
| 8 | +from pathlib import Path |
| 9 | +from typing import Optional, Union |
| 10 | +from urllib.parse import quote |
| 11 | + |
| 12 | +logger = logging.getLogger(__name__) |
| 13 | + |
| 14 | + |
| 15 | +class DataLoader: |
| 16 | + DEFAULT_BUCKET = "cache-datasets" |
| 17 | + DEFAULT_CACHE_DIR = Path.home() / ".cache/libcachesim_hub" |
| 18 | + |
| 19 | + def __init__( |
| 20 | + self, |
| 21 | + bucket_name: str = DEFAULT_BUCKET, |
| 22 | + cache_dir: Optional[Union[str, Path]] = None, |
| 23 | + use_auth: bool = False |
| 24 | + ): |
| 25 | + self.bucket_name = bucket_name |
| 26 | + self.cache_dir = Path(cache_dir) if cache_dir else self.DEFAULT_CACHE_DIR |
| 27 | + self.use_auth = use_auth |
| 28 | + self._s3_client = None |
| 29 | + self._ensure_cache_dir() |
| 30 | + |
| 31 | + def _ensure_cache_dir(self) -> None: |
| 32 | + (self.cache_dir / self.bucket_name).mkdir(parents=True, exist_ok=True) |
| 33 | + |
| 34 | + @property |
| 35 | + def s3_client(self): |
| 36 | + if self._s3_client is None: |
| 37 | + try: |
| 38 | + import boto3 |
| 39 | + from botocore.config import Config |
| 40 | + from botocore import UNSIGNED |
| 41 | + |
| 42 | + self._s3_client = boto3.client( |
| 43 | + 's3', |
| 44 | + config=None if self.use_auth else Config(signature_version=UNSIGNED) |
| 45 | + ) |
| 46 | + except ImportError: |
| 47 | + raise ImportError("Install boto3: pip install boto3") |
| 48 | + return self._s3_client |
| 49 | + |
| 50 | + def _cache_path(self, key: str) -> Path: |
| 51 | + safe_name = hashlib.sha256(key.encode()).hexdigest()[:16] + "_" + quote(key, safe='') |
| 52 | + return self.cache_dir / self.bucket_name / safe_name |
| 53 | + |
| 54 | + def _download(self, key: str, dest: Path) -> None: |
| 55 | + temp = dest.with_suffix(dest.suffix + '.tmp') |
| 56 | + temp.parent.mkdir(parents=True, exist_ok=True) |
| 57 | + |
| 58 | + try: |
| 59 | + logger.info(f"Downloading s3://{self.bucket_name}/{key}") |
| 60 | + obj = self.s3_client.get_object(Bucket=self.bucket_name, Key=key) |
| 61 | + with open(temp, 'wb') as f: |
| 62 | + f.write(obj['Body'].read()) |
| 63 | + shutil.move(str(temp), str(dest)) |
| 64 | + logger.info(f"Saved to: {dest}") |
| 65 | + except Exception as e: |
| 66 | + if temp.exists(): |
| 67 | + temp.unlink() |
| 68 | + raise RuntimeError(f"Download failed for s3://{self.bucket_name}/{key}: {e}") |
| 69 | + |
| 70 | + def load(self, key: str, force: bool = False, mode: str = 'rb') -> Union[bytes, str]: |
| 71 | + path = self._cache_path(key) |
| 72 | + if not path.exists() or force: |
| 73 | + self._download(key, path) |
| 74 | + with open(path, mode) as f: |
| 75 | + return f.read() |
| 76 | + |
| 77 | + def is_cached(self, key: str) -> bool: |
| 78 | + return self._cache_path(key).exists() |
| 79 | + |
| 80 | + def get_cache_path(self, key: str) -> Path: |
| 81 | + return self._cache_path(key).as_posix() |
| 82 | + |
| 83 | + def clear_cache(self, key: Optional[str] = None) -> None: |
| 84 | + if key: |
| 85 | + path = self._cache_path(key) |
| 86 | + if path.exists(): |
| 87 | + path.unlink() |
| 88 | + logger.info(f"Cleared: {path}") |
| 89 | + else: |
| 90 | + shutil.rmtree(self.cache_dir, ignore_errors=True) |
| 91 | + logger.info(f"Cleared entire cache: {self.cache_dir}") |
| 92 | + |
| 93 | + def list_cached_files(self) -> list[str]: |
| 94 | + if not self.cache_dir.exists(): |
| 95 | + return [] |
| 96 | + return [ |
| 97 | + str(p) for p in self.cache_dir.rglob('*') |
| 98 | + if p.is_file() and not p.name.endswith('.tmp') |
| 99 | + ] |
| 100 | + |
| 101 | + def get_cache_size(self) -> int: |
| 102 | + return sum( |
| 103 | + p.stat().st_size for p in self.cache_dir.rglob('*') if p.is_file() |
| 104 | + ) |
| 105 | + |
| 106 | + def list_s3_objects(self, prefix: str = "", delimiter: str = "/") -> dict: |
| 107 | + """ |
| 108 | + List S3 objects and pseudo-folders under a prefix. |
| 109 | +
|
| 110 | + Args: |
| 111 | + prefix: The S3 prefix to list under (like folder path) |
| 112 | + delimiter: Use "/" to simulate folder structure |
| 113 | +
|
| 114 | + Returns: |
| 115 | + A dict with two keys: |
| 116 | + - "folders": list of sub-prefixes (folders) |
| 117 | + - "files": list of object keys (files) |
| 118 | + """ |
| 119 | + paginator = self.s3_client.get_paginator('list_objects_v2') |
| 120 | + result = {"folders": [], "files": []} |
| 121 | + |
| 122 | + for page in paginator.paginate( |
| 123 | + Bucket=self.bucket_name, |
| 124 | + Prefix=prefix, |
| 125 | + Delimiter=delimiter |
| 126 | + ): |
| 127 | + # CommonPrefixes are like subdirectories |
| 128 | + result["folders"].extend(cp["Prefix"] for cp in page.get("CommonPrefixes", [])) |
| 129 | + result["files"].extend(obj["Key"] for obj in page.get("Contents", [])) |
| 130 | + |
| 131 | + return result |
0 commit comments