File size: 2,120 Bytes
9fbf50e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from huggingface_hub import HfApi, create_repo
from typing import Dict, Optional
import tempfile
import os

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.

    """
    if not token:
        raise ValueError("Hugging Face Token is required.")

    api = HfApi(token=token)
    
    # Authenticate and get user
    try:
        user_info = api.whoami()
        if not username:
            username = user_info['name']
    except Exception as e:
        raise ValueError(f"Invalid Token: {str(e)}")

    repo_id = f"{username}/{space_name}"

    # Create Repo if not exists
    try:
        api.create_repo(
            repo_id=repo_id,
            repo_type="space",
            space_sdk="gradio",
            exist_ok=True,
            private=False # Default to public, can be changed
        )
    except Exception as e:
        print(f"Repo creation/check status: {e}")

    # Prepare files for upload
    operations = []
    
    # Create a temporary directory to write files to upload
    # Note: api.upload_file or upload_folder can be used.
    # We will use upload_file loop for simplicity with in-memory strings
    
    # Ideally we use commit_operations for atomicity but simple upload loop is fine for MVP
    # Let's use upload_file content directly
    
    try:
        for filename, content in files.items():
            # Convert string content to bytes
            content_bytes = content.encode('utf-8')
            
            api.upload_file(
                path_or_fileobj=content_bytes,
                path_in_repo=filename,
                repo_id=repo_id,
                repo_type="space",
                commit_message=f"Update {filename} via Agent"
            )
            
        return f"https://huggingface.co/spaces/{repo_id}"
        
    except Exception as e:
        raise RuntimeError(f"Deployment Failed: {str(e)}")