hf-space-creator / main.py
Guillaume Raille
Add project configuration and deployment scripts
a3a85c9 unverified
import gradio as gr
from huggingface_hub import HfApi, login, create_repo
from huggingface_hub.utils import RepositoryNotFoundError
def create_user_space(token: str, space_name: str) -> str:
"""Create a private Hugging Face space for the user."""
try:
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 create_interface():
"""Create the Gradio interface."""
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.")
# State to store the token
token_state = gr.State()
# Login section
with gr.Row():
token_input = gr.Textbox(
label="Hugging Face Token",
placeholder="Enter your HF token (get it from https://huggingface.co/settings/tokens)",
type="password"
)
login_btn = gr.Button("Login", variant="primary")
login_status = 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 handle_login(token):
"""Handle user login."""
try:
# Verify the token by getting user info
api = HfApi(token=token)
user_info = api.whoami()
username = user_info["name"]
return (
token, # Store token in state
f"βœ… Logged in as **{username}**", # Update status
gr.update(visible=True), # Show create section
gr.update(visible=False), # Hide token input
gr.update(visible=False) # Hide login button
)
except Exception as e:
return (
None, # Clear token state
f"❌ Login failed: {str(e)}", # Update status
gr.update(visible=False), # Keep create section hidden
gr.update(visible=True), # Keep token input visible
gr.update(visible=True) # Keep login button visible
)
# Login button click
login_btn.click(
fn=handle_login,
inputs=[token_input],
outputs=[token_state, login_status, create_section, token_input, login_btn]
)
# Create space button click
create_btn.click(
fn=create_user_space,
inputs=[token_state, space_name_input],
outputs=[create_status]
)
return demo
def main():
demo = create_interface()
demo.launch()
if __name__ == "__main__":
main()