hf-backend / .github /workflows /deploy.yml
IDKHowToCodeFr's picture
ci: detect HF username and create Space if missing
c1bb7cf
Raw History Blame Contribute Delete
2.18 kB
name: Deploy and Restart HF Space
on:
push:
branches:
- main
workflow_dispatch:
jobs:
sync-and-restart:
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v4
with:
fetch-depth: 0
lfs: true
- name: Sync to Hugging Face Space & Restart
env:
HF_TOKEN: ${{ secrets.HF_BACKEND_SPACE || secrets.HF_TOKEN }}
HF_SPACE: ${{ secrets.HF_SPACE }}
run: |
if [ -z "$HF_TOKEN" ]; then
echo "HF_BACKEND_SPACE secret not set. Skipping Hugging Face sync."
exit 0
fi
# Detect actual Hugging Face username from token
HF_USER=$(curl -s -H "Authorization: Bearer ${HF_TOKEN}" https://huggingface.co/api/whoami-v2 | python3 -c "import sys, json; data = json.load(sys.stdin); print(data.get('name', 'rachit-mangawa'))" 2>/dev/null || echo "rachit-mangawa")
echo "Authenticated as Hugging Face user: $HF_USER"
SPACE_REPO="${HF_SPACE:-${HF_USER}/hf-backend}"
SPACE_NAME="${SPACE_REPO#*/}"
# Check if Space exists; create it if missing
HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" -H "Authorization: Bearer ${HF_TOKEN}" "https://huggingface.co/api/spaces/${SPACE_REPO}")
if [ "$HTTP_STATUS" -eq 404 ]; then
echo "Space '${SPACE_REPO}' not found. Creating Space with Docker SDK..."
CREATE_RES=$(curl -s -X POST "https://huggingface.co/api/repos/create" \
-H "Authorization: Bearer ${HF_TOKEN}" \
-H "Content-Type: application/json" \
-d "{\"name\": \"${SPACE_NAME}\", \"type\": \"space\", \"sdk\": \"docker\"}")
echo "Create response: $CREATE_RES"
fi
echo "Syncing code to Hugging Face Space: $SPACE_REPO..."
git push "https://${HF_USER}:${HF_TOKEN}@huggingface.co/spaces/${SPACE_REPO}" main:main --force
echo "Triggering Space restart..."
curl -f -s -X POST "https://huggingface.co/api/spaces/${SPACE_REPO}/restart" \
-H "Authorization: Bearer ${HF_TOKEN}" || echo "Space restart API request sent."