File size: 5,103 Bytes
d749752
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7f43d5
ef8f1a7
 
8ff459e
 
 
 
58cc748
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
#!/usr/bin/env python3
"""
ColorCraft SDXL Space Deployment Script
Helps deploy your SDXL pipeline to HuggingFace Spaces
"""

import os
import subprocess
import sys
from pathlib import Path

def check_dependencies():
    """Check if required tools are installed"""
    try:
        import huggingface_hub
        print("βœ… huggingface_hub is installed")
    except ImportError:
        print("❌ Installing huggingface_hub...")
        subprocess.check_call([sys.executable, "-m", "pip", "install", "huggingface_hub"])
    
    try:
        subprocess.run(["git", "--version"], capture_output=True, check=True)
        print("βœ… Git is available")
    except (subprocess.CalledProcessError, FileNotFoundError):
        print("❌ Git is required. Please install Git first.")
        sys.exit(1)

def setup_space(username, space_name, hf_token):
    """Create and setup HuggingFace Space"""
    from huggingface_hub import HfApi, create_repo
    
    # Initialize HF API
    api = HfApi(token=hf_token)
    
    # Create repository
    repo_id = f"{username}/{space_name}"
    
    try:
        print(f"πŸš€ Creating HuggingFace Space: {repo_id}")
        create_repo(
            repo_id=repo_id,
            token=hf_token,
            repo_type="space",
            space_sdk="gradio",
            space_hardware="t4-medium",  # GPU for SDXL
            private=False
        )
        print(f"βœ… Space created successfully!")
    except Exception as e:
        if "already exists" in str(e):
            print(f"ℹ️ Space {repo_id} already exists, updating...")
        else:
            print(f"❌ Error creating space: {e}")
            sys.exit(1)
    
    return repo_id

def deploy_files(repo_id, hf_token):
    """Deploy files to HuggingFace Space"""
    from huggingface_hub import HfApi
    
    api = HfApi(token=hf_token)
    space_dir = Path(__file__).parent
    
    files_to_upload = [
        ("app.py", "app.py"),
        ("requirements.txt", "requirements.txt"), 
        ("README.md", "README.md")
    ]
    
    print("πŸ“ Uploading files to Space...")
    
    for local_file, remote_file in files_to_upload:
        local_path = space_dir / local_file
        if local_path.exists():
            print(f"  πŸ“€ Uploading {local_file}...")
            api.upload_file(
                path_or_fileobj=str(local_path),
                path_in_repo=remote_file,
                repo_id=repo_id,
                repo_type="space",
                token=hf_token
            )
        else:
            print(f"  ⚠️ File not found: {local_file}")
    
    print("βœ… All files uploaded successfully!")

def update_backend_config(repo_id):
    """Update backend to use the deployed Space"""
    backend_dir = Path(__file__).parent.parent
    hf_client_path = backend_dir / "app" / "huggingface_client.py"
    
    if hf_client_path.exists():
        print("πŸ”§ Updating backend configuration...")
        
        # Read current file
        with open(hf_client_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # Replace placeholder URL with actual Space URL
        space_url = f"https://{repo_id.replace('/', '-')}.hf.space/api/predict"
        content = content.replace(
            "https://YOUR_USERNAME-colorcraft-sdxl.hf.space/api/predict",
            space_url
        )
        
        # Write back
        with open(hf_client_path, 'w', encoding='utf-8') as f:
            f.write(content)
        
        print(f"βœ… Backend updated to use: {space_url}")
    else:
        print("⚠️ Backend HuggingFace client not found")

def main():
    print("🎨 ColorCraft SDXL Space Deployment")
    print("=" * 50)
    
    # Check dependencies
    check_dependencies()
    
    # Get user input
    print("\nπŸ“ Configuration:")
    username = input("Enter your HuggingFace username: ").strip()
    space_name = input("Enter Space name (e.g., 'colorcraft-sdxl'): ").strip()
    hf_token = input("Enter your HuggingFace token: ").strip()
    
    if not all([username, space_name, hf_token]):
        print("❌ All fields are required!")
        sys.exit(1)
    
    # Setup and deploy
    try:
        repo_id = setup_space(username, space_name, hf_token)
        deploy_files(repo_id, hf_token)
        update_backend_config(repo_id)
        
        space_url = f"https://{repo_id.replace('/', '-')}.hf.space"
        
        print("\nπŸŽ‰ Deployment Complete!")
        print("=" * 50)
        print(f"🌐 Space URL: {space_url}")
        print(f"πŸ“Š Space Dashboard: https://huggingface.co/spaces/{repo_id}")
        print("\nπŸ“‹ Next Steps:")
        print("1. Visit your Space URL to verify it's working")
        print("2. Wait for the Space to build (5-10 minutes)")
        print("3. Test image processing through the interface")
        print("4. Your backend will now use SDXL quality!")
        print("\nπŸš€ Your ColorCraft app now has cloud SDXL processing!")
        
    except Exception as e:
        print(f"❌ Deployment failed: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()