Brain-Tumor-AI / push_to_hf_final.py
StillWorking's picture
Upload folder using huggingface_hub (part 13)
1f2e262 verified
Raw History Blame Contribute Delete
5.34 kB
#!/usr/bin/env python3
"""
Final script to push entire project to Hugging Face using git commands
Uses the correct HF username from the login
"""
import os
import subprocess
import shutil
from pathlib import Path
# Get the actual HF username from the API
from huggingface_hub import whoami
current_user = whoami()
HF_USERNAME = current_user['name']
REPO_NAME = "Brain-Tumor-AI"
HF_REPO_ID = f"{HF_USERNAME}/{REPO_NAME}"
LOCAL_PATH = r"e:\Brain"
TEMP_HF_PATH = r"e:\Brain_hf_push"
print(f"Current HF user: {HF_USERNAME}")
def run_command(cmd, cwd=None):
"""Run shell command and return output"""
print(f" $ {cmd}")
result = subprocess.run(cmd, shell=True, cwd=cwd, capture_output=True, text=True)
if result.stdout:
print(result.stdout)
if result.stderr and result.returncode != 0:
print(f" ❌ Error: {result.stderr}")
return result.returncode == 0, result.stdout, result.stderr
def main():
print("\n" + "="*60)
print("🚀 Pushing to Hugging Face (Dataset)")
print("="*60)
print(f"📦 Repository: {HF_REPO_ID}")
print(f"📁 Local Path: {LOCAL_PATH}\n")
# Create temp directory
if os.path.exists(TEMP_HF_PATH):
print(f"🧹 Removing existing temp directory...")
shutil.rmtree(TEMP_HF_PATH, ignore_errors=True)
print(f"📁 Creating temp directory: {TEMP_HF_PATH}")
os.makedirs(TEMP_HF_PATH)
# Initialize git repo in temp directory
print("\n🔧 Initializing git repository...")
run_command("git init", cwd=TEMP_HF_PATH)
run_command("git config user.email 'ujjwalathub@gmail.com'", cwd=TEMP_HF_PATH)
run_command("git config user.name 'Ujjwal'", cwd=TEMP_HF_PATH)
# Configure Git LFS
print("\n📦 Configuring Git LFS for large files...")
run_command("git lfs install", cwd=TEMP_HF_PATH)
# Create .gitattributes for LFS
gitattributes_path = os.path.join(TEMP_HF_PATH, ".gitattributes")
with open(gitattributes_path, 'w') as f:
f.write("""# Binary files for LFS
*.pth filter=lfs diff=lfs merge=lfs -text
*.npy filter=lfs diff=lfs merge=lfs -text
*.onnx filter=lfs diff=lfs merge=lfs -text
*.csv filter=lfs diff=lfs merge=lfs -text
*.pkl filter=lfs diff=lfs merge=lfs -text
*.pickle filter=lfs diff=lfs merge=lfs -text
*.tar filter=lfs diff=lfs merge=lfs -text
*.gz filter=lfs diff=lfs merge=lfs -text
*.zip filter=lfs diff=lfs merge=lfs -text
""")
print(f"✅ Created .gitattributes with LFS config")
# Copy all files from Brain directory
print(f"\n📋 Copying files from {LOCAL_PATH}...\n")
file_count = 0
for item in os.listdir(LOCAL_PATH):
src_path = os.path.join(LOCAL_PATH, item)
dst_path = os.path.join(TEMP_HF_PATH, item)
# Skip git and push scripts
if item in ['.git', 'push_to_hf.py', 'push_to_hf_simple.py', 'push_to_hf_final.py', 'Brain_hf_push']:
continue
if os.path.isdir(src_path):
print(f" 📁 {item}/")
shutil.copytree(src_path, dst_path, ignore=shutil.ignore_patterns('.git'))
file_count += len(list(Path(dst_path).rglob('*')))
else:
print(f" 📄 {item}")
shutil.copy2(src_path, dst_path)
file_count += 1
print(f"\n✅ All files copied! ({file_count} items)")
# Add all files
print("\n➕ Adding files to git...")
run_command("git add .", cwd=TEMP_HF_PATH)
# Check what's being tracked
print("\n📊 Getting file statistics...")
success, output, _ = run_command("git status --short | wc -l", cwd=TEMP_HF_PATH)
# Commit
print("\n💾 Creating commit...")
success, output, _ = run_command(
'git commit -m "Initial commit: Brain Tumor MRI Classifier with complete dataset and models"',
cwd=TEMP_HF_PATH
)
if not success:
print("⚠️ Commit failed")
return
# Add Hugging Face remote with authentication
print("\n🔗 Adding Hugging Face remote...")
hf_url = f"https://huggingface.co/datasets/{HF_REPO_ID}"
run_command(f'git remote add origin "{hf_url}"', cwd=TEMP_HF_PATH)
# Rename branch to main
print("\n🌿 Renaming branch to main...")
run_command("git branch -M main", cwd=TEMP_HF_PATH)
# Push to Hugging Face
print("\n⬆️ Pushing to Hugging Face...")
print("⏳ This may take several minutes depending on file sizes...\n")
success, output, error = run_command(
"git push -u origin main --force",
cwd=TEMP_HF_PATH
)
if success:
print("\n" + "="*60)
print("✅ SUCCESS! Project pushed to Hugging Face!")
print("="*60)
print(f"🔗 Repository URL:")
print(f" {hf_url}")
print("\nYou can access your dataset at:")
print(f" https://huggingface.co/datasets/{HF_REPO_ID}")
print("\n✨ All code, data, and models are now on Hugging Face!")
else:
print("\n❌ Push failed!")
print(f"Error: {error}")
# Cleanup
print("\n🧹 Cleaning up temporary files...")
try:
shutil.rmtree(TEMP_HF_PATH, ignore_errors=True)
print("✅ Cleanup complete!")
except Exception as e:
print(f"⚠️ Cleanup warning: {e}")
if __name__ == "__main__":
main()