File size: 5,057 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
#!/usr/bin/env python3
"""
Xet Client Integration for Data Transfer Operations
Handles heavy artifact storage and synchronization with Xet repositories
"""

import os
import subprocess
import json
import logging
from typing import Dict, List, Optional
import requests

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class XetClient:
    """Client for Xet repository operations and artifact management"""
    
    def __init__(self, repo_url: str, auth_token: Optional[str] = None):
        self.repo_url = repo_url
        self.auth_token = auth_token
        self.base_dir = "/mnt/xet"
        
    def check_xet_installed(self) -> bool:
        """Check if Xet CLI is installed and available"""
        try:
            result = subprocess.run(["xet", "--version"], 
                                 capture_output=True, text=True, timeout=10)
            return result.returncode == 0
        except (FileNotFoundError, subprocess.TimeoutExpired):
            return False
    
    def clone_repository(self, target_dir: str) -> bool:
        """Clone Xet repository to local directory"""
        try:
            cmd = ["xet", "clone", self.repo_url, target_dir]
            if self.auth_token:
                cmd.extend(["--token", self.auth_token])
            
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
            if result.returncode == 0:
                logger.info(f"Successfully cloned Xet repository to {target_dir}")
                return True
            else:
                logger.error(f"Xet clone failed: {result.stderr}")
                return False
        except Exception as e:
            logger.error(f"Xet clone error: {e}")
            return False
    
    def upload_artifact(self, local_path: str, xet_path: str) -> bool:
        """Upload artifact to Xet repository"""
        try:
            if not os.path.exists(local_path):
                logger.error(f"Local path does not exist: {local_path}")
                return False
            
            # Ensure target directory exists in Xet repo
            target_dir = os.path.dirname(xet_path)
            if target_dir:
                os.makedirs(os.path.join(self.base_dir, target_dir), exist_ok=True)
            
            # Copy file to Xet working directory
            import shutil
            shutil.copy2(local_path, os.path.join(self.base_dir, xet_path))
            
            # Add and commit to Xet
            subprocess.run(["xet", "add", xet_path], cwd=self.base_dir, check=True)
            commit_msg = f"Add artifact: {xet_path}"
            subprocess.run(["xet", "commit", "-m", commit_msg], cwd=self.base_dir, check=True)
            subprocess.run(["xet", "push"], cwd=self.base_dir, check=True)
            
            logger.info(f"Successfully uploaded {local_path} to Xet as {xet_path}")
            return True
            
        except Exception as e:
            logger.error(f"Xet upload error: {e}")
            return False
    
    def download_artifact(self, xet_path: str, local_path: str) -> bool:
        """Download artifact from Xet repository"""
        try:
            # Pull latest changes
            subprocess.run(["xet", "pull"], cwd=self.base_dir, check=True)
            
            # Copy file from Xet working directory
            source_path = os.path.join(self.base_dir, xet_path)
            if not os.path.exists(source_path):
                logger.error(f"Xet path does not exist: {xet_path}")
                return False
            
            import shutil
            shutil.copy2(source_path, local_path)
            
            logger.info(f"Successfully downloaded {xet_path} to {local_path}")
            return True
            
        except Exception as e:
            logger.error(f"Xet download error: {e}")
            return False
    
    def list_artifacts(self, path: str = "") -> List[str]:
        """List artifacts in Xet repository"""
        try:
            result = subprocess.run(["xet", "ls", path], 
                                 cwd=self.base_dir, capture_output=True, text=True)
            if result.returncode == 0:
                return result.stdout.strip().split('\n')
            return []
        except Exception as e:
            logger.error(f"Xet list error: {e}")
            return []

def initialize_xet_integration():
    """Initialize Xet integration for DTO framework"""
    # Check if Xet is available
    client = XetClient("https://xet.example.com/adaptai/artifacts")
    
    if not client.check_xet_installed():
        logger.warning("Xet CLI not found. Please install Xet for artifact management.")
        return None
    
    # Create Xet working directory
    os.makedirs(client.base_dir, exist_ok=True)
    
    return client

if __name__ == "__main__":
    # Example usage
    xet_client = initialize_xet_integration()
    if xet_client:
        print("Xet integration initialized successfully")
    else:
        print("Xet integration not available")