File size: 8,737 Bytes
fd357f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Hugging Face Hub Client Integration for Data Transfer Operations
Uses HF Hub with Xet backend for artifact storage and management
"""

import os
import logging
from typing import Dict, List, Optional, Union
from pathlib import Path

# Try to import Hugging Face Hub - will be installed in requirements
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

try:
    from huggingface_hub import HfApi, HfFolder, snapshot_download, upload_file, create_repo
    from huggingface_hub.utils import RepositoryNotFoundError
    HF_AVAILABLE = True
except ImportError:
    HF_AVAILABLE = False
    logger.warning("huggingface_hub not available. Install with: pip install huggingface_hub")

class HuggingFaceClient:
    """Client for Hugging Face Hub operations with Xet backend"""
    
    def __init__(self, repo_id: Optional[str] = None, token: Optional[str] = None):
        """Initialize HF client with optional repo and token"""
        self.repo_id = repo_id
        self.token = token or os.getenv('HF_TOKEN') or HfFolder.get_token() if HF_AVAILABLE else None
        self.api = HfApi(token=self.token) if HF_AVAILABLE else None
    
    def is_authenticated(self) -> bool:
        """Check if authenticated with Hugging Face Hub"""
        if not HF_AVAILABLE or not self.api:
            return False
        try:
            # Test authentication by calling whoami
            self.api.whoami()
            return True
        except:
            # Some tokens may have upload permissions but fail whoami
            # Try a lightweight operation to verify token validity
            try:
                # Check if we can access repo info (lighter than whoami)
                if self.repo_id:
                    self.api.repo_info(self.repo_id)
                    return True
                # If no repo specified, assume valid for upload operations
                return True
            except:
                return False
    
    def upload_artifact(self, local_path: str, repo_path: str, repo_id: Optional[str] = None) -> bool:
        """Upload artifact to HF Hub repo (uses Xet backend transparently)"""
        if not HF_AVAILABLE:
            logger.error("huggingface_hub not available")
            return False
        
        repo_id = repo_id or self.repo_id
        if not repo_id:
            logger.error("No repository ID provided")
            return False
        
        # Xet backend restrictions: cannot upload to protected directories
        # Clean the repo_path to avoid uploading to restricted paths
        clean_repo_path = self._clean_repo_path(repo_path)
        if clean_repo_path is None:
            logger.warning(f"Skipping upload to restricted path: {repo_path}")
            return False
        
        try:
            # Check if repo exists - don't try to create if it already exists
            try:
                self.api.repo_info(repo_id)
                logger.info(f"Repository exists: {repo_id}")
            except RepositoryNotFoundError:
                logger.info(f"Creating repository: {repo_id}")
                # Determine repo type based on repository name pattern
                repo_type = "model"
                if "datasets" in repo_id.lower():
                    repo_type = "dataset"
                elif "artifacts" in repo_id.lower():
                    repo_type = "model"  # Artifacts also use model type
                self.api.create_repo(repo_id, repo_type=repo_type, private=True)
            
            # Upload file
            upload_file(
                path_or_fileobj=local_path,
                path_in_repo=clean_repo_path,
                repo_id=repo_id,
                token=self.token
            )
            
            logger.info(f"Uploaded {local_path} to {repo_id}/{clean_repo_path}")
            return True
            
        except Exception as e:
            logger.error(f"Upload failed: {e}")
            return False
    
    def _clean_repo_path(self, repo_path: str) -> Optional[str]:
        """Clean repository path to avoid Xet backend restrictions"""
        # Xet backend blocks uploads to certain protected directories
        restricted_patterns = [
            '/.cache/', '/.local/', '/.config/', '/.ssh/', '/.git/',
            '/.hg/', '/.svn/', '/node_modules/', '/venv/', '/.venv/',
            '/__pycache__/', '/.pytest_cache/', '/.mypy_cache/'
        ]
        
        # Check if path contains any restricted patterns
        for pattern in restricted_patterns:
            if pattern in repo_path:
                return None
        
        # Remove any leading path components that might cause issues
        # Extract just the filename or relative path without system directories
        if '/' in repo_path:
            # For system paths, extract just the filename
            if repo_path.startswith(('data/', 'home/', 'usr/', 'var/', 'tmp/')):
                return os.path.basename(repo_path)
            # For other paths, keep the relative structure but remove system prefixes
            clean_path = repo_path.replace('data/', '').replace('home/', '')
            return clean_path
        
        return repo_path
    
    def download_artifact(self, repo_path: str, local_path: str, repo_id: Optional[str] = None) -> bool:
        """Download artifact from HF Hub repo"""
        if not HF_AVAILABLE:
            logger.error("huggingface_hub not available")
            return False
        
        repo_id = repo_id or self.repo_id
        if not repo_id:
            logger.error("No repository ID provided")
            return False
        
        try:
            # Download specific file
            downloaded_path = snapshot_download(
                repo_id=repo_id,
                allow_patterns=repo_path,
                local_dir=os.path.dirname(local_path),
                token=self.token
            )
            
            # Move to desired location
            import shutil
            actual_file = os.path.join(downloaded_path, repo_path)
            if os.path.exists(actual_file):
                shutil.move(actual_file, local_path)
                logger.info(f"Downloaded {repo_path} to {local_path}")
                return True
            else:
                logger.error(f"File not found in download: {repo_path}")
                return False
                
        except Exception as e:
            logger.error(f"Download failed: {e}")
            return False
    
    def list_artifacts(self, repo_id: Optional[str] = None) -> List[str]:
        """List artifacts in HF Hub repo"""
        if not HF_AVAILABLE:
            logger.error("huggingface_hub not available")
            return []
        
        repo_id = repo_id or self.repo_id
        if not repo_id:
            logger.error("No repository ID provided")
            return []
        
        try:
            repo_info = self.api.repo_info(repo_id)
            return [file.rfilename for file in repo_info.siblings]
        except Exception as e:
            logger.error(f"List failed: {e}")
            return []
    
    def get_repo_info(self, repo_id: Optional[str] = None) -> Optional[Dict]:
        """Get repository information"""
        if not HF_AVAILABLE:
            return None
        
        repo_id = repo_id or self.repo_id
        if not repo_id:
            return None
        
        try:
            info = self.api.repo_info(repo_id)
            return {
                'id': info.id,
                'private': info.private,
                'size': getattr(info, 'size', None),
                'downloads': info.downloads,
                'last_modified': info.last_modified,
                'xet_enabled': getattr(info, 'xet_enabled', None),
            }
        except Exception as e:
            logger.error(f"Repo info failed: {e}")
            return None

def initialize_hf_integration():
    """Initialize Hugging Face integration for DTO framework"""
    client = HuggingFaceClient()
    
    if not HF_AVAILABLE:
        logger.warning("huggingface_hub not available. Please install: pip install huggingface_hub")
        return None
    
    if not client.is_authenticated():
        logger.warning("Not authenticated with Hugging Face Hub. Set HF_TOKEN environment variable")
        
    return client

if __name__ == "__main__":
    # Example usage
    hf_client = initialize_hf_integration()
    if hf_client and hf_client.is_authenticated():
        print("Hugging Face integration initialized successfully")
        print(f"Authenticated as: {hf_client.api.whoami()['name']}")
    else:
        print("Hugging Face integration not available or not authenticated")