File size: 6,157 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
#!/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:
            return False
        try:
            return self.api.is_authenticated
        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
        
        try:
            # Ensure repo exists
            try:
                self.api.repo_info(repo_id)
            except RepositoryNotFoundError:
                logger.info(f"Creating repository: {repo_id}")
                self.api.create_repo(repo_id, repo_type="model", private=True)
            
            # Upload file
            upload_file(
                path_or_fileobj=local_path,
                path_in_repo=repo_path,
                repo_id=repo_id,
                token=self.token
            )
            
            logger.info(f"Uploaded {local_path} to {repo_id}/{repo_path}")
            return True
            
        except Exception as e:
            logger.error(f"Upload failed: {e}")
            return False
    
    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")