abersbail's picture
Upload deploy.py with huggingface_hub
35438e9 verified
#!/usr/bin/env python3
"""
One-click deploy script for Hugging Face Spaces.
Usage:
python deploy.py
This script will:
1. Install required dependencies
2. Create a Hugging Face Space
3. Push all files to the Space
4. Provide the Space URL
"""
import os
import sys
from pathlib import Path
from huggingface_hub import HfApi, create_repo
# Hugging Face token - read from environment variable or user input
HF_TOKEN = os.environ.get("HF_TOKEN")
if not HF_TOKEN:
print("Error: HF_TOKEN environment variable not set.")
print("Please set it before running this script.")
sys.exit(1)
def main():
api = HfApi()
# Get user info
try:
whoami = api.whoami(token=HF_TOKEN)
username = whoami["name"]
print(f"Logged in as: {username}")
except Exception as e:
print(f"Error authenticating with Hugging Face: {e}")
sys.exit(1)
repo_name = "wheat-disease-classifier"
repo_id = f"{username}/{repo_name}"
print(f"\nCreating Space: {repo_id}")
try:
# Create the Space
create_repo(
repo_id=repo_id,
repo_type="space",
space_sdk="gradio",
token=HF_TOKEN,
exist_ok=True,
)
print(f"✓ Space created/exists: {repo_id}")
# Files to upload
files_to_upload = []
# Root files
for f in Path(".").glob("*.py"):
files_to_upload.append(f)
for f in Path(".").glob("*.txt"):
files_to_upload.append(f)
for f in Path(".").glob("*.md"):
files_to_upload.append(f)
for f in Path(".").glob("*.sh"):
files_to_upload.append(f)
for f in Path(".").glob("*.yaml"):
files_to_upload.append(f)
# Package files
for pkg in ["dipauglib", "dipaugnet", "tests", "configs"]:
pkg_path = Path(pkg)
if pkg_path.exists():
for f in pkg_path.rglob("*.py"):
files_to_upload.append(f)
for f in pkg_path.rglob("*.yaml"):
files_to_upload.append(f)
# Upload all files
print(f"\nUploading {len(files_to_upload)} files...")
for file_path in files_to_upload:
try:
# Calculate path in repo
path_in_repo = str(file_path)
api.upload_file(
path_or_fileobj=str(file_path),
path_in_repo=path_in_repo,
repo_id=repo_id,
repo_type="space",
token=HF_TOKEN,
)
print(f" ✓ {file_path}")
except Exception as e:
print(f" ✗ {file_path}: {e}")
print(f"\n{'='*60}")
print(f"✓ DEPLOYMENT COMPLETE!")
print(f"{'='*60}")
print(f"\nView your Space at:")
print(f"https://huggingface.co/spaces/{repo_id}")
print(f"\nThe Space will build automatically. You can check the status at:")
print(f"https://huggingface.co/spaces/{repo_id}/tree/main")
except Exception as e:
print(f"Error: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
if __name__ == "__main__":
main()