File size: 5,503 Bytes
0919d5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Direct upload script to Hugging Face Spaces.
This script will guide you through creating and uploading your Memory Chat application.
"""

import os
import sys
import subprocess
import webbrowser
from pathlib import Path

def check_prerequisites():
    """Check if prerequisites are installed."""
    print("πŸ” Checking prerequisites...")

    # Check if git is installed
    try:
        result = subprocess.run(['git', '--version'], capture_output=True, text=True)
        if result.returncode == 0:
            print("βœ… Git is installed")
        else:
            print("❌ Git is not installed. Please install Git first.")
            return False
    except FileNotFoundError:
        print("❌ Git is not installed. Please install Git first.")
        return False

    # Check if files exist
    required_files = [
        'app.py',
        'memory_manager.py',
        'chat_interface.py',
        'config.py',
        'requirements.txt',
        'README.md'
    ]

    missing_files = []
    for file in required_files:
        if not os.path.exists(file):
            missing_files.append(file)

    if missing_files:
        print(f"❌ Missing files: {', '.join(missing_files)}")
        print("Please ensure all required files are in the current directory.")
        return False
    else:
        print("βœ… All required files found")

    return True

def create_space():
    """Guide user through creating a Space on Hugging Face."""
    print("\n🌐 Creating Hugging Face Space...")

    print("1. Open your web browser and go to: https://huggingface.co/spaces")
    print("2. Sign in to your Hugging Face account")
    print("3. Click 'Create new Space' (top right)")
    print("4. Choose a Space name (e.g., 'your-username/memory-chat')")
    print("5. Select 'Gradio' as the Space type")
    print("6. Choose 'Public' visibility")
    print("7. Click 'Create Space'")

    input("\nPress Enter after you've created your Space...")

def get_space_url():
    """Get the Space URL from user."""
    print("\nπŸ“ Please enter your Space URL:")
    print("It should look like: https://huggingface.co/spaces/your-username/your-space-name")
    space_url = input("Space URL: ").strip()

    if not space_url.startswith("https://huggingface.co/spaces/"):
        print("❌ Invalid URL format. Please enter a valid Hugging Face Space URL.")
        return get_space_url()

    return space_url

def clone_space_repo(space_url):
    """Clone the Space repository."""
    print(f"\nπŸ“₯ Cloning Space repository: {space_url}")

    # Extract the repo name from URL
    repo_name = space_url.split('/')[-1]
    username = space_url.split('/')[-2]

    clone_url = f"https://huggingface.co/spaces/{username}/{repo_name}"

    try:
        subprocess.run(['git', 'clone', clone_url], check=True)
        return repo_name
    except subprocess.CalledProcessError as e:
        print(f"❌ Failed to clone repository: {e}")
        return None

def copy_files_to_repo(repo_name):
    """Copy files to the cloned repository."""
    print(f"\nπŸ“ Copying files to {repo_name}...")

    files_to_copy = [
        ('app.py', 'app.py'),
        ('memory_manager.py', 'memory_manager.py'),
        ('chat_interface.py', 'chat_interface.py'),
        ('config.py', 'config.py'),
        ('requirements.txt', 'requirements.txt'),
        ('README.md', 'README.md')
    ]

    for src, dst in files_to_copy:
        try:
            subprocess.run(['cp', src, f"{repo_name}/{dst}"], check=True)
            print(f"βœ… Copied {src} -> {repo_name}/{dst}")
        except subprocess.CalledProcessError as e:
            print(f"❌ Failed to copy {src}: {e}")
            return False

    return True

def commit_and_push(repo_name, username):
    """Commit and push changes to the Space."""
    print(f"\nπŸš€ Committing and pushing changes...")

    try:
        # Change to repo directory
        os.chdir(repo_name)

        # Add files
        subprocess.run(['git', 'add', '.'], check=True)

        # Commit
        subprocess.run(['git', 'commit', '-m', 'Initial commit: Memory Chat application'], check=True)

        # Push
        subprocess.run(['git', 'push', 'origin', 'main'], check=True)

        print("βœ… Successfully pushed to Hugging Face Spaces!")
        print(f"🌐 Your Space will be available at: https://huggingface.co/spaces/{username}/{repo_name}")

        return True

    except subprocess.CalledProcessError as e:
        print(f"❌ Failed to commit/push: {e}")
        return False

def main():
    """Main deployment function."""
    print("πŸš€ Memory Chat - Hugging Face Spaces Deployment")
    print("=" * 50)

    # Check prerequisites
    if not check_prerequisites():
        sys.exit(1)

    # Create Space on Hugging Face
    create_space()

    # Get Space URL
    space_url = get_space_url()
    username = space_url.split('/')[-2]

    # Clone the Space repository
    repo_name = clone_space_repo(space_url)
    if not repo_name:
        sys.exit(1)

    # Copy files
    if not copy_files_to_repo(repo_name):
        sys.exit(1)

    # Commit and push
    if commit_and_push(repo_name, username):
        print("\nπŸŽ‰ Deployment successful!")
        print("Your Space will build automatically and be available shortly.")
        print("Check the 'Logs' tab in your Space for build status.")
    else:
        print("\n❌ Deployment failed. Please check the error messages above.")

if __name__ == "__main__":
    main()