File size: 6,487 Bytes
02ff59a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Smart sync script that automatically handles both GitHub and Hugging Face uploads
based on file types and sizes.
"""

import os
import subprocess
import argparse
from pathlib import Path
import json

def get_file_size_mb(filepath):
    """Get file size in MB."""
    return os.path.getsize(filepath) / (1024 * 1024)

def classify_files(dataset_dir):
    """Classify files for GitHub vs Hugging Face upload."""
    github_files = []  # Small files (< 50MB)
    hf_files = []      # Large files (>= 50MB)

    for root, dirs, files in os.walk(dataset_dir):
        for file in files:
            filepath = os.path.join(root, file)
            size_mb = get_file_size_mb(filepath)

            # Classification rules
            if (file.endswith(('.npy', '.npz')) and size_mb >= 50) or size_mb >= 100:
                hf_files.append(filepath)
            else:
                github_files.append(filepath)

    return github_files, hf_files

def sync_to_github(project_dir, commit_message):
    """Sync code and small files to GitHub."""
    print("📡 Syncing to GitHub...")

    os.chdir(project_dir)

    # Add files (excluding large data files)
    subprocess.run(["git", "add", "."], check=True)

    # Create .gitignore for large files if not exists
    gitignore_path = Path(".gitignore")
    if not gitignore_path.exists():
        with open(gitignore_path, 'w') as f:
            f.write("""# Large data files (synced to Hugging Face)
dataset/**/*.npy
dataset/**/*.npz
dataset/**/autoencoder_stage1/weight/*.pt
dataset/**/autoencoder_stage1/infer_result/

# Python
__pycache__/
*.pyc
*.pyo
*.egg-info/

# IDE
.vscode/
.idea/
*.swp
*.swo

# OS
.DS_Store
Thumbs.db
""")
        subprocess.run(["git", "add", ".gitignore"], check=True)

    # Commit and push
    try:
        subprocess.run(["git", "commit", "-m", commit_message], check=True)
        subprocess.run(["git", "push"], check=True)
        print("✅ GitHub sync completed")
        return True
    except subprocess.CalledProcessError as e:
        print(f"⚠️  GitHub sync failed: {e}")
        return False

def sync_to_huggingface(dataset_dir, hf_repo, commit_message):
    """Sync large files to Hugging Face."""
    print("🤗 Syncing to Hugging Face...")

    # Use the existing upload script
    upload_script = os.path.join(dataset_dir, "upload_to_hf.py")
    if os.path.exists(upload_script):
        cmd = [
            "python", upload_script,
            "--repo-name", hf_repo,
            "--commit-message", commit_message,
            "--dataset-path", dataset_dir
        ]

        try:
            subprocess.run(cmd, check=True)
            print("✅ Hugging Face sync completed")
            return True
        except subprocess.CalledProcessError as e:
            print(f"⚠️  Hugging Face sync failed: {e}")
            return False
    else:
        print(f"❌ Upload script not found: {upload_script}")
        return False

def create_deployment_info(project_dir, github_repo, hf_dataset):
    """Create deployment information file."""
    deployment_info = {
        "github_repo": github_repo,
        "hf_dataset": hf_dataset,
        "quick_setup_command": f"python setup_environment.py --hf-dataset {hf_dataset} --github-repo {github_repo}",
        "description": "Use the quick_setup_command to recreate this environment on any server"
    }

    info_path = os.path.join(project_dir, "DEPLOYMENT.json")
    with open(info_path, 'w') as f:
        json.dump(deployment_info, f, indent=2)

    # Also create a README for deployment
    readme_path = os.path.join(project_dir, "DEPLOYMENT.md")
    with open(readme_path, 'w') as f:
        f.write(f"""# STAMP Project Deployment

## Quick Setup on New Server

```bash
# 1. Download setup script
wget https://raw.githubusercontent.com/your-username/STAMP/main/setup_environment.py

# 2. Run setup (auto-downloads everything)
python setup_environment.py --hf-dataset {hf_dataset} --github-repo {github_repo}

# 3. Start working
cd STAMP
python check_environment.py
bash quick_train.sh
```

## Manual Setup

1. **Clone Code**: `git clone {github_repo}`
2. **Download Dataset**: Use Hugging Face CLI or datasets library
3. **Install Dependencies**: `pip install torch torchvision numpy tqdm huggingface_hub datasets`

## Repository Structure

- **GitHub**: Code, configs, small files (< 100MB)
- **Hugging Face**: Large datasets, model weights (unlimited)

## Available Scripts

- `quick_train.sh` - Interactive training
- `quick_inference.sh` - Interactive inference
- `check_environment.py` - Environment verification
""")

    print(f"✅ Deployment info created: {info_path}")

def main():
    parser = argparse.ArgumentParser(description="Smart sync to GitHub and Hugging Face")
    parser.add_argument("--github-repo", type=str, required=True,
                       help="GitHub repository name")
    parser.add_argument("--hf-dataset", type=str, required=True,
                       help="Hugging Face dataset name")
    parser.add_argument("--commit-message", type=str,
                       default="Auto-sync project",
                       help="Commit message")
    parser.add_argument("--project-dir", type=str, default=".",
                       help="Project directory")

    args = parser.parse_args()

    print("🔄 Smart Sync: GitHub + Hugging Face")
    print("=" * 40)

    project_dir = os.path.abspath(args.project_dir)
    dataset_dir = os.path.join(project_dir, "dataset")

    # Create deployment info
    create_deployment_info(project_dir, args.github_repo, args.hf_dataset)

    # Sync to GitHub (code + small files)
    github_success = sync_to_github(project_dir, args.commit_message)

    # Sync to Hugging Face (large files)
    hf_success = sync_to_huggingface(dataset_dir, args.hf_dataset, args.commit_message)

    # Summary
    print("\n📊 Sync Summary:")
    print(f"GitHub: {'✅' if github_success else '❌'}")
    print(f"Hugging Face: {'✅' if hf_success else '❌'}")

    if github_success and hf_success:
        print("\n🎉 Complete sync successful!")
        print(f"🌐 GitHub: https://github.com/{args.github_repo}")
        print(f"🤗 Hugging Face: https://huggingface.co/datasets/{args.hf_dataset}")
        print(f"\n📋 Quick setup command for new servers:")
        print(f"python setup_environment.py --hf-dataset {args.hf_dataset} --github-repo https://github.com/{args.github_repo}.git")

if __name__ == "__main__":
    main()