AI_Game / safe_upload.py
ducnguyen1978's picture
Upload folder using huggingface_hub
815d041 verified
#!/usr/bin/env python3
"""
Safe Upload Script for Hugging Face Spaces
==========================================
This script safely uploads only necessary files to Hugging Face Spaces,
excluding sensitive files like .env, __pycache__, etc.
Usage:
python safe_upload.py your_username/your_space_name
Requirements:
pip install huggingface_hub
"""
import os
import sys
from pathlib import Path
from huggingface_hub import HfApi
# Files to upload (whitelist approach - safer)
ALLOWED_FILES = [
"AI_Talk_Gradio.py",
"requirements.txt",
".gitignore",
"README_Deploy.md"
]
# Files/folders to NEVER upload (blacklist - extra safety)
BLOCKED_PATTERNS = [
".env",
"__pycache__",
".gradio",
"*.pyc",
"*.pyo",
"*.pyd",
"*.pem",
"*.key",
"*.crt",
"flagged",
".vscode",
".idea"
]
def is_safe_file(file_path):
"""Check if file is safe to upload"""
file_name = os.path.basename(file_path)
# Check whitelist
if file_name not in ALLOWED_FILES:
return False
# Extra check - ensure no blocked patterns
for pattern in BLOCKED_PATTERNS:
if pattern in file_path.lower():
return False
return True
def safe_upload_to_hf(repo_id):
"""Safely upload files to Hugging Face Space"""
api = HfApi()
print(f"πŸš€ Starting safe upload to {repo_id}")
print("πŸ“‹ Files to be uploaded:")
current_dir = Path(".")
files_to_upload = []
# Collect safe files
for file_name in ALLOWED_FILES:
file_path = current_dir / file_name
if file_path.exists() and is_safe_file(str(file_path)):
files_to_upload.append(file_path)
print(f" βœ… {file_name}")
else:
print(f" ⚠️ {file_name} (not found or blocked)")
if not files_to_upload:
print("❌ No safe files found to upload!")
return False
print(f"\nπŸ“€ Uploading {len(files_to_upload)} files...")
try:
for file_path in files_to_upload:
print(f" Uploading {file_path.name}...")
api.upload_file(
path_or_fileobj=str(file_path),
path_in_repo=file_path.name,
repo_id=repo_id,
repo_type="space"
)
print(f" βœ… {file_path.name} uploaded successfully")
print(f"\nπŸŽ‰ Upload completed successfully!")
print(f"🌐 Your Space: https://huggingface.co/spaces/{repo_id}")
print("\nπŸ“ Next steps:")
print("1. Go to your Space settings")
print("2. Add API keys as Repository secrets:")
print(" - GROQ_API_KEY")
print(" - GOOGLE_API_KEY")
print("3. Your Space will auto-deploy!")
return True
except Exception as e:
print(f"❌ Upload failed: {e}")
return False
def main():
if len(sys.argv) != 2:
print("Usage: python safe_upload.py username/space_name")
print("Example: python safe_upload.py ducnguyen1978/AI_Game")
sys.exit(1)
repo_id = sys.argv[1]
# Validate repo_id format
if "/" not in repo_id:
print("❌ Invalid repo_id. Use format: username/space_name")
sys.exit(1)
print("πŸ”’ Safe Upload for Hugging Face Spaces")
print("=" * 40)
print(f"Target Space: {repo_id}")
print()
success = safe_upload_to_hf(repo_id)
if not success:
sys.exit(1)
if __name__ == "__main__":
main()