File size: 4,754 Bytes
e138257
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74d172e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e138257
 
 
bf6b98a
 
e138257
 
 
 
 
 
 
 
 
 
 
 
 
74d172e
e138257
 
74d172e
e138257
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
from huggingface_hub import HfApi, create_repo
from huggingface_hub.utils import RepositoryNotFoundError
import os


def create_interface():
    """Create the Gradio interface with OAuth login."""
    
    with gr.Blocks(title="HF Space Creator") as demo:
        gr.Markdown("# Hugging Face Space Creator")
        gr.Markdown("Login with your Hugging Face account to create a private space.")
        
        # OAuth login
        login_btn = gr.LoginButton()
        
        # User info display
        user_info = gr.Markdown("")
        
        # Space creation section (initially hidden)
        with gr.Column(visible=False) as create_section:
            gr.Markdown("### Create a New Private Space")
            space_name_input = gr.Textbox(
                label="Space Name",
                placeholder="my-awesome-space",
                info="Enter a name for your new private space (lowercase, no spaces)"
            )
            create_btn = gr.Button("Create Private Space", variant="primary")
            create_status = gr.Markdown("")
        
        def create_user_space(space_name: str, oauth_token: gr.OAuthToken | None) -> str:
            """Create a private Hugging Face space for the user."""
            if not oauth_token:
                return "❌ Please login first!"
            
            try:
                # Use the OAuth token
                token = oauth_token.token
                if not token:
                    return "❌ No access token found. Please login again."
                    
                api = HfApi(token=token)
                
                # Get the current user's username
                user_info = api.whoami()
                username = user_info["name"]
                
                # Create a private space repository
                repo_id = f"{username}/{space_name}"
                
                # Check if the space already exists
                try:
                    api.repo_info(repo_id, repo_type="space")
                    return f"❌ Space '{repo_id}' already exists!"
                except RepositoryNotFoundError:
                    # Space doesn't exist, we can create it
                    pass
                
                # Create the space
                url = create_repo(
                    repo_id=repo_id,
                    repo_type="space",
                    space_sdk="gradio",
                    private=True,
                    token=token
                )
                
                # Create a simple app.py file for the new space
                app_content = '''import gradio as gr

def greet(name):
    return f"Hello {name}! This is your private space."

demo = gr.Interface(fn=greet, inputs="text", outputs="text")

if __name__ == "__main__":
    demo.launch()
'''
                
                api.upload_file(
                    path_or_fileobj=app_content.encode(),
                    path_in_repo="app.py",
                    repo_id=repo_id,
                    repo_type="space",
                    token=token
                )
                
                return f"βœ… Successfully created private space: {url}"
                
            except Exception as e:
                return f"❌ Error creating space: {str(e)}"
        
        def update_ui(profile: gr.OAuthProfile | None) -> tuple:
            """Update UI based on login status."""
            if profile:
                # OAuthProfile has username attribute
                username = profile.username
                return (
                    f"βœ… Logged in as **{username}**",
                    gr.update(visible=True)
                )
            else:
                return (
                    "",
                    gr.update(visible=False)
                )
        
        # Update UI when login state changes
        demo.load(update_ui, inputs=None, outputs=[user_info, create_section])
        
        # Create space button click - use oauth_token parameter
        create_btn.click(
            fn=create_user_space,
            inputs=[space_name_input],
            outputs=[create_status]
        )
    
    return demo


def main():
    # Check if running in Hugging Face Spaces
    if os.getenv("SPACE_ID"):
        # Running in Spaces, launch with appropriate settings
        demo = create_interface()
        demo.launch()
    else:
        # Running locally, note that OAuth won't work
        print("Note: OAuth login only works when deployed to Hugging Face Spaces.")
        print("To test locally, deploy this as a Space with hf_oauth: true in README.md")
        demo = create_interface()
        demo.launch()


if __name__ == "__main__":
    main()