File size: 2,255 Bytes
fcd463d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Deployment logic for Hugging Face Spaces
"""

import re
from typing import Dict, Optional
from huggingface_hub import HfApi


def deploy_to_space(
    token: str,
    space_name: str,
    files: Dict[str, str],
    username: Optional[str] = None
) -> str:
    """
    Deploys the given files to a Hugging Face Space.
    Returns the URL of the deployed space.
    """
    
    # Validate inputs
    if not token:
        raise ValueError("Hugging Face Token is required.")
    
    if not token.startswith('hf_'):
        raise ValueError("Invalid Hugging Face token. Should start with 'hf_'")
    
    if not space_name:
        raise ValueError("Space name is required.")
    
    # Validate space name format
    if not re.match(r'^[a-z0-9-]{3,30}$', space_name):
        raise ValueError(
            "Space name must be 3-30 characters, lowercase letters, numbers, and hyphens only."
        )
    
    # Initialize Hugging Face API
    api = HfApi(token=token)
    
    try:
        # Get user information
        user_info = api.whoami()
        if not username:
            username = user_info['name']
    except Exception as e:
        raise ValueError(f"Invalid Token: {str(e)}")
    
    # Create repository ID
    repo_id = f"{username}/{space_name}"
    
    try:
        # Create or update the Space
        api.create_repo(
            repo_id=repo_id,
            repo_type="space",
            space_sdk="gradio",
            exist_ok=True,
            private=False
        )
    except Exception as e:
        print(f"Note: {e}")
    
    try:
        # Upload files
        for filename, content in files.items():
            # Ensure app.py is clean
            if filename == "app.py":
                if '```' in content:
                    content = content.replace('```', '')
            
            api.upload_file(
                path_or_fileobj=content.encode('utf-8'),
                path_in_repo=filename,
                repo_id=repo_id,
                repo_type="space",
                commit_message=f"Add {filename} via Space Creator"
            )
        
        return f"https://huggingface.co/spaces/{repo_id}"
        
    except Exception as e:
        raise RuntimeError(f"Deployment failed: {str(e)}")