#!/usr/bin/env python3 """ Xet Integration for Elizabeth Data Management """ import os import sys import json import subprocess from datetime import datetime from pathlib import Path from typing import Dict, List, Any class XetIntegration: """Xet data versioning and management integration""" def __init__(self, repo_url: str = "https://xetbeta.com/adaptnova/elizabeth-data"): self.repo_url = repo_url self.local_path = "/workspace/xet_data" self.ensure_xet_dir() def ensure_xet_dir(self): """Ensure Xet directory exists""" os.makedirs(self.local_path, exist_ok=True) def run_xet_command(self, command: List[str]) -> Dict[str, Any]: """Execute Xet command and return results""" try: result = subprocess.run( command, capture_output=True, text=True, cwd=self.local_path, timeout=300 ) return { "success": result.returncode == 0, "stdout": result.stdout, "stderr": result.stderr, "returncode": result.returncode } except subprocess.TimeoutExpired: return { "success": False, "error": "Command timed out" } except Exception as e: return { "success": False, "error": str(e) } def clone_repository(self) -> Dict[str, Any]: """Clone Xet repository""" if os.path.exists(os.path.join(self.local_path, ".git")): return {"success": True, "message": "Repository already exists"} command = ["git", "xet", "clone", self.repo_url, self.local_path] return self.run_xet_command(command) def init_xet_repo(self) -> Dict[str, Any]: """Initialize new Xet repository""" command = ["git", "xet", "init"] result = self.run_xet_command(command) if result["success"]: # Set up remote remote_cmd = ["git", "remote", "add", "origin", self.repo_url] remote_result = self.run_xet_command(remote_cmd) if remote_result["success"]: return {"success": True, "message": "Xet repository initialized"} else: return remote_result return result def upload_data(self, data_type: str, data_path: str, commit_message: str = "") -> Dict[str, Any]: """Upload data to Xet repository""" try: # Ensure data exists if not os.path.exists(data_path): return {"success": False, "error": f"Data path does not exist: {data_path}"} # Copy data to Xet directory if os.path.isfile(data_path): shutil.copy2(data_path, self.local_path) else: # For directories, copy contents for item in os.listdir(data_path): item_path = os.path.join(data_path, item) if os.path.isfile(item_path): shutil.copy2(item_path, self.local_path) # Add to Xet add_cmd = ["git", "xet", "add", "."] add_result = self.run_xet_command(add_cmd) if not add_result["success"]: return add_result # Commit commit_msg = commit_message or f"Add {data_type} data - {datetime.now().isoformat()}" commit_cmd = ["git", "xet", "commit", "-m", commit_msg] commit_result = self.run_xet_command(commit_cmd) if not commit_result["success"]: return commit_result # Push to remote push_cmd = ["git", "xet", "push", "origin", "main"] push_result = self.run_xet_command(push_cmd) return push_result except Exception as e: return { "success": False, "error": str(e) } def download_data(self, data_pattern: str = "*") -> Dict[str, Any]: """Download data from Xet repository""" try: # Pull latest changes pull_cmd = ["git", "xet", "pull", "origin", "main"] pull_result = self.run_xet_command(pull_cmd) if not pull_result["success"]: return pull_result # List downloaded files downloaded_files = [] for root, _, files in os.walk(self.local_path): for file in files: if data_pattern in file or data_pattern == "*": file_path = os.path.join(root, file) downloaded_files.append({ "name": file, "path": file_path, "size": os.path.getsize(file_path) }) return { "success": True, "downloaded_files": downloaded_files, "total_files": len(downloaded_files) } except Exception as e: return { "success": False, "error": str(e) } def upload_elizabeth_data(self) -> Dict[str, Any]: """Upload all Elizabeth data to Xet""" data_sources = [ {"type": "memory_db", "path": "/workspace/elizabeth_memory.db"}, {"type": "chroma_db", "path": "/workspace/elizabeth_chroma"}, {"type": "logs", "path": "/workspace/elizabeth_logs"}, {"type": "config", "path": "/workspace/elizabeth_config.json"} ] results = {} for source in data_sources: if os.path.exists(source["path"]): result = self.upload_data( source["type"], source["path"], f"Elizabeth {source['type']} update" ) results[source["type"]] = result else: results[source["type"]] = {"success": False, "error": "Path does not exist"} return results def get_repository_info(self) -> Dict[str, Any]: """Get Xet repository information""" try: # Get remote info remote_cmd = ["git", "remote", "-v"] remote_result = self.run_xet_command(remote_cmd) # Get status status_cmd = ["git", "xet", "status"] status_result = self.run_xet_command(status_cmd) # Get commit history log_cmd = ["git", "xet", "log", "--oneline", "-10"] log_result = self.run_xet_command(log_cmd) return { "success": True, "remote": remote_result["stdout"].strip() if remote_result["success"] else "", "status": status_result["stdout"].strip() if status_result["success"] else "", "recent_commits": log_result["stdout"].strip().split('\n') if log_result["success"] else [] } except Exception as e: return { "success": False, "error": str(e) } def main(): """Command line interface for Xet integration""" import argparse parser = argparse.ArgumentParser(description="Elizabeth Xet Integration") parser.add_argument("--init", action="store_true", help="Initialize Xet repository") parser.add_argument("--clone", action="store_true", help="Clone Xet repository") parser.add_argument("--upload", help="Upload specific file or directory") parser.add_argument("--download", help="Download data (pattern)") parser.add_argument("--upload-all", action="store_true", help="Upload all Elizabeth data") parser.add_argument("--info", action="store_true", help="Get repository info") args = parser.parse_args() xet = XetIntegration() if args.init: result = xet.init_xet_repo() print(json.dumps(result, indent=2)) elif args.clone: result = xet.clone_repository() print(json.dumps(result, indent=2)) elif args.upload: result = xet.upload_data("custom", args.upload) print(json.dumps(result, indent=2)) elif args.download: result = xet.download_data(args.download) print(json.dumps(result, indent=2)) elif args.upload_all: result = xet.upload_elizabeth_data() print(json.dumps(result, indent=2)) elif args.info: result = xet.get_repository_info() print(json.dumps(result, indent=2)) else: print("No action specified. Use --help for options.") if __name__ == "__main__": main()