File size: 4,398 Bytes
2f7c2cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""

Fixed deployment script for TEC application to Hugging Face Spaces

"""

import os
import subprocess
import sys
from pathlib import Path

def run_command(cmd, cwd=None):
    """Run a command and return the result"""
    try:
        result = subprocess.run(cmd, shell=True, cwd=cwd, capture_output=True, text=True)
        if result.returncode != 0:
            print(f"Error running command: {cmd}")
            print(f"Error output: {result.stderr}")
            return False
        print(f"Success: {cmd}")
        if result.stdout:
            print(result.stdout)
        return True
    except Exception as e:
        print(f"Exception running command {cmd}: {e}")
        return False

def check_files():
    """Check if required files exist"""
    required_files = ['app.py', 'requirements.txt', 'Dockerfile']
    missing_files = []
    
    for file in required_files:
        if not Path(file).exists():
            missing_files.append(file)
    
    if missing_files:
        print(f"Missing required files: {missing_files}")
        return False
    
    print("All required files found")
    return True

def get_hf_username(token):
    """Get the Hugging Face username from the token"""
    try:
        from huggingface_hub import HfApi
        api = HfApi(token=token)
        user_info = api.whoami()
        return user_info['name']
    except Exception as e:
        print(f"Could not get username: {e}")
        return None

def deploy_to_hf():
    """Deploy to Hugging Face Spaces"""
    if not check_files():
        return False
    
    # Check if we have HF token
    hf_token = os.getenv('HF_TOKEN')
    if not hf_token:
        print("HF_TOKEN environment variable not set")
        print("Please run: deploy_with_token.bat")
        print("Or manually set: set HF_TOKEN=your_token_here")
        return False
    
    print("Starting deployment to Hugging Face Spaces...")
    
    # Install huggingface_hub if not available
    print("Installing huggingface_hub...")
    if not run_command("pip install huggingface_hub"):
        return False
    
    # Get username
    print("Getting your Hugging Face username...")
    username = get_hf_username(hf_token)
    if not username:
        username = input("Enter your HF username: ").strip()
        if not username:
            print("Error: Username is required")
            return False
    else:
        print(f"Found username: {username}")
    
    # Get space name
    space_name = input(f"Enter space name (default: tec-app): ").strip()
    if not space_name:
        space_name = "tec-app"
    
    repo_id = f"{username}/{space_name}"
    print(f"Will create space: {repo_id}")
    
    # Create deployment script
    deploy_script = f'''

from huggingface_hub import HfApi

import os



api = HfApi(token="{hf_token}")

repo_id = "{repo_id}"



try:

    print(f"Creating space: {{repo_id}}")

    

    # Create the space first

    api.create_repo(

        repo_id=repo_id,

        repo_type="space",

        space_sdk="docker",

        exist_ok=True,

        private=False

    )

    

    print("Space created successfully!")

    print("Uploading files...")

    

    # Upload files

    api.upload_folder(

        folder_path=".",

        repo_id=repo_id,

        repo_type="space",

        ignore_patterns=[".git", "__pycache__", "*.pyc", "temp_deploy.py", "deploy_fixed.py"]

    )

    

    print(f"Successfully deployed to https://huggingface.co/spaces/{{repo_id}}")

    print("Your app will be available in a few minutes!")

    print("Note: It may take 2-3 minutes for the Docker container to build and start.")

    

except Exception as e:

    print(f"Deployment failed: {{e}}")

    import traceback

    traceback.print_exc()

'''
    
    with open('temp_deploy.py', 'w') as f:
        f.write(deploy_script)
    
    success = run_command("python temp_deploy.py")
    
    # Cleanup
    if Path('temp_deploy.py').exists():
        Path('temp_deploy.py').unlink()
    
    return success

if __name__ == "__main__":
    print("TEC Application Deployment Script (Fixed)")
    print("=" * 45)
    
    if deploy_to_hf():
        print("Deployment completed successfully!")
    else:
        print("Deployment failed!")
        sys.exit(1)