Spaces:
Running
Running
Commit ·
f9ff1a1
1
Parent(s): e7a5a81
feat: CI/CD pipeline + Docker + HuggingFace Spaces deployment
Browse files- Add Dockerfile (multi-stage: Node build + Python runtime)
- Add startup.sh (auto-downloads inswapper model on cold start)
- Add requirements-deploy.txt (CPU-only for cloud)
- Add GitHub Actions CI workflow (backend tests + React build)
- Add GitHub Actions deploy workflow (push to HF Spaces with Firebase config injection)
- Add README.md with HuggingFace Spaces metadata
- Flask PORT now reads from environment variable (7860 for HF Spaces)
- Replace emoji feature icons with SVG icons
Files changed (8)
- .github/workflows/ci.ymlAdded+71
- .github/workflows/deploy.ymlAdded+75
- DockerfileAdded+49
- README.mdAdded+73
- frontend/src/pages/LandingPage.jsx+16-7
- requirements-deploy.txtAdded+32
- startup.shAdded+47
- web_app.py+4-3
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071name: CI
on: push: branches: [main, develop] pull_request: branches: [main]
jobs: # ── Backend Tests ───────────────────────────────────────────────────────── backend: name: Backend Tests runs-on: ubuntu-latest
steps: - name: Checkout uses: actions/checkout@v4
- name: Set up Python 3.10 uses: actions/setup-python@v5 with: python-version: "3.10" cache: pip
- name: Install CI dependencies (lightweight subset) run: | pip install --upgrade pip pip install \ opencv-python-headless==4.9.0.80 \ numpy==1.26.4 \ Pillow==10.3.0 \ scipy==1.13.0 \ scikit-image==0.23.2 \ flask==3.0.3 \ flask-cors==4.0.1 \ python-dotenv==1.0.1 \ pytest==8.2.0
- name: Run tests run: python -m pytest tests/ -v --tb=short
# ── Frontend Build ──────────────────────────────────────────────────────── frontend: name: Frontend Build runs-on: ubuntu-latest
steps: - name: Checkout uses: actions/checkout@v4
- name: Set up Node 20 uses: actions/setup-node@v4 with: node-version: "20" cache: npm cache-dependency-path: frontend/package-lock.json
- name: Install dependencies working-directory: frontend run: npm ci --silent
- name: Build React app working-directory: frontend run: npm run build
- name: Upload React build artifact uses: actions/upload-artifact@v4 with: name: react-build path: static/react/ retention-days: 7123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475name: Deploy to Hugging Face Spaces
on: push: branches: [main]
jobs: # ── Wait for CI to pass first ───────────────────────────────────────────── deploy: name: Push to Hugging Face Spaces runs-on: ubuntu-latest
steps: - name: Checkout (full history) uses: actions/checkout@v4 with: fetch-depth: 0
# ── Inject Firebase config from GitHub Secrets ────────────────────── - name: Inject Firebase config into firebase.js run: | cat > frontend/src/firebase.js << 'EOF' import { initializeApp } from 'firebase/app'; import { getAuth, GoogleAuthProvider, signInWithPopup, signOut, onAuthStateChanged } from 'firebase/auth';
const firebaseConfig = { apiKey: "${{ secrets.FIREBASE_API_KEY }}", authDomain: "${{ secrets.FIREBASE_AUTH_DOMAIN }}", projectId: "${{ secrets.FIREBASE_PROJECT_ID }}", storageBucket: "${{ secrets.FIREBASE_STORAGE_BUCKET }}", messagingSenderId: "${{ secrets.FIREBASE_MESSAGING_SENDER_ID }}", appId: "${{ secrets.FIREBASE_APP_ID }}", };
const fbApp = initializeApp(firebaseConfig); const auth = getAuth(fbApp); const googleProvider = new GoogleAuthProvider();
export { auth, googleProvider, signInWithPopup, signOut, onAuthStateChanged }; EOF
# ── Build React with real Firebase config ──────────────────────────── - name: Set up Node 20 uses: actions/setup-node@v4 with: node-version: "20" cache: npm cache-dependency-path: frontend/package-lock.json
- name: Install frontend dependencies working-directory: frontend run: npm ci --silent
- name: Build React app (with real Firebase config) working-directory: frontend run: npm run build
# ── Push to Hugging Face Spaces ────────────────────────────────────── - name: Configure git for HF push run: | git config user.email "adivid198986@gmail.com" git config user.name "ADiTyaRaj8969"
- name: Add built React to commit run: | git add static/react/ -f git add frontend/src/firebase.js -f git diff --cached --quiet || git commit -m "ci: build React with Firebase config [skip ci]"
- name: Push to Hugging Face Spaces env: HF_TOKEN: ${{ secrets.HF_TOKEN }} run: | git remote add hf https://ADiTyaRaj8969:${HF_TOKEN}@huggingface.co/spaces/ADiTyaRaj8969/FaceSwap || true git push hf main --force12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849# ── Stage 1: Build React frontend ────────────────────────────────────────────FROM node:20-slim AS frontend-builder
WORKDIR /appCOPY frontend/package*.json frontend/RUN cd frontend && npm ci --silentCOPY frontend/ frontend/RUN mkdir -p static/reactRUN cd frontend && npm run build# Output is at /app/static/react (vite outDir: ../static/react)
# ── Stage 2: Python runtime ───────────────────────────────────────────────────FROM python:3.10-slim
# System libs required by OpenCV and MediaPipeRUN apt-get update && apt-get install -y --no-install-recommends \ libgl1-mesa-glx \ libglib2.0-0 \ libsm6 \ libxrender1 \ libxext6 \ wget \ git \ && rm -rf /var/lib/apt/lists/*
WORKDIR /app
# Install Python dependencies (CPU-only for cloud deployment)COPY requirements-deploy.txt .RUN pip install --no-cache-dir -r requirements-deploy.txt
# Copy React build from stage 1COPY --from=frontend-builder /app/static/react ./static/react
# Copy application codeCOPY . .
# Create runtime directoriesRUN mkdir -p models uploads/temp outputs/results
# HuggingFace Spaces listens on 7860ENV PORT=7860EXPOSE 7860
# Make startup script executableRUN chmod +x startup.sh
CMD ["./startup.sh"]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273---title: DeepFace StudiocolorFrom: greencolorTo: yellowsdk: dockerapp_port: 7860pinned: falselicense: mit---
# DeepFace Studio
AI-powered face swap web application with seamless hair-to-neck blending, skin tone matching, and Firebase authentication.
## Features- Live camera capture or image upload for source face- Upload target face image- Deep face swap using InsightFace inswapper model- Hair-to-neck seamless blending (Laplacian + Poisson)- Skin tone matching (CIE LAB colour transfer)- Quality metrics after every swap- Firebase Google Sign-in with 10-day session- GPU + CPU support (auto-detected)
## Local Setup
### Requirements- Python 3.10+- Node.js 20+
### Installation```bash# Install Python dependenciespip install -r requirements.txt
# Download the face swap model (~528 MB)python scripts/download_models.py
# Build the React frontendcd frontendnpm installnpm run buildcd ..
# Start the apppython web_app.py```
Open http://localhost:5000
### Firebase Setup1. Go to https://console.firebase.google.com2. Create a new project3. Add a Web App4. Enable Google Sign-In under Authentication5. Copy the config into `frontend/src/firebase.js`6. Rebuild the frontend: `cd frontend && npm run build`
## Deployment (HuggingFace Spaces)The app deploys automatically via GitHub Actions on every push to `main`.The inswapper model is downloaded automatically at container startup.
## Tech Stack- **Frontend**: React 18 + Vite + TailwindCSS + Framer Motion- **Backend**: Python + Flask- **AI Models**: InsightFace (inswapper_128), MediaPipe, OpenCV- **Auth**: Firebase Google Sign-In
## NoteThis tool is for educational purposes only. Use responsibly and only with images you own or have explicit consent to use.
---© Aditya Raj 202610 unmodified lines11121314151617181920212223169 unmodified lines19319419519619719819910 unmodified linesimport Magnet from '../components/ui/Magnet';import ShinyText from '../components/ui/ShinyText';const FEATURES = [{ icon: '📸', title: 'Live Camera + Upload', desc: 'Capture from webcam or upload any image. Instant face detection with bounding box feedback.' },{ icon: '🌿', title: 'Hair to Neck Blending', desc: 'Seamless multi-layer mask blending from hairline through face to neck using Poisson cloning.' },{ icon: '✨', title: 'Skin Tone Matching', desc: 'CIE LAB colour transfer adapts the swapped face to match target skin across all skin types.' },{ icon: '📊', title: 'Quality Metrics', desc: 'Alignment score, blend quality, colour Delta E, and naturalness score after every swap.' },{ icon: '⚡', title: 'GPU Accelerated', desc: 'CUDA optimised InsightFace with ONNX Runtime for sub 2s inference on supported hardware.' },{ icon: '🔒', title: 'Fully Private', desc: 'All processing runs on your own machine. No images are uploaded to any external server.' },];const PIPELINE = ['Detect', 'Align', 'Swap', 'Tone Match', 'Blend', 'Enhance', 'Output'];169 unmodified lines{FEATURES.map((f, i) => (<AnimatedContent key={f.title} delay={i * 0.07} direction="up"><SpotlightCard className="bg-bg3 border border-forest rounded-2xl p-5 sm:p-7 h-full hover:border-olive hover:-translate-y-1 transition-all duration-200"><div className="w-10 h-10 sm:w-11 sm:h-11 bg-olive/20 border border-olive/40 rounded-xl flex items-center justify-center text-lg sm:text-xl mb-3 sm:mb-4">{f.icon}</div><h3 className="text-lime font-bold mb-1.5 text-sm sm:text-base">{f.title}</h3>10 unmodified lines11121314151617181920212223242526272829303132169 unmodified lines20220320420520620720810 unmodified linesimport Magnet from '../components/ui/Magnet';import ShinyText from '../components/ui/ShinyText';const FEATURE_ICONS = {camera: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.5} className="w-5 h-5"><path d="M23 7l-7 5 7 5V7z"/><rect x="1" y="5" width="15" height="14" rx="2" ry="2"/></svg>,layers: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.5} className="w-5 h-5"><polygon points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/></svg>,palette: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.5} className="w-5 h-5"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="10" r="3"/><path d="M12 13v2"/><circle cx="9" cy="17" r="1" fill="currentColor" stroke="none"/><circle cx="12" cy="18" r="1" fill="currentColor" stroke="none"/><circle cx="15" cy="17" r="1" fill="currentColor" stroke="none"/></svg>,chart: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.5} className="w-5 h-5"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></svg>,zap: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.5} className="w-5 h-5"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>,lock: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.5} className="w-5 h-5"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>,};const FEATURES = [{ icon: FEATURE_ICONS.camera, title: 'Live Camera + Upload', desc: 'Capture from webcam or upload any image. Instant face detection with bounding box feedback.' },{ icon: FEATURE_ICONS.layers, title: 'Hair to Neck Blending', desc: 'Seamless multi-layer mask blending from hairline through face to neck using Poisson cloning.' },{ icon: FEATURE_ICONS.palette, title: 'Skin Tone Matching', desc: 'CIE LAB colour transfer adapts the swapped face to match target skin across all skin types.' },{ icon: FEATURE_ICONS.chart, title: 'Quality Metrics', desc: 'Alignment score, blend quality, colour Delta E, and naturalness score after every swap.' },{ icon: FEATURE_ICONS.zap, title: 'GPU + CPU Support', desc: 'CUDA optimised InsightFace on GPU, automatic CPU fallback. Same output quality on both.' },{ icon: FEATURE_ICONS.lock, title: 'Fully Private', desc: 'All processing runs on your own machine. No images are uploaded to any external server.' },];const PIPELINE = ['Detect', 'Align', 'Swap', 'Tone Match', 'Blend', 'Enhance', 'Output'];169 unmodified lines{FEATURES.map((f, i) => (<AnimatedContent key={f.title} delay={i * 0.07} direction="up"><SpotlightCard className="bg-bg3 border border-forest rounded-2xl p-5 sm:p-7 h-full hover:border-olive hover:-translate-y-1 transition-all duration-200"><div className="w-10 h-10 sm:w-11 sm:h-11 bg-olive/20 border border-olive/40 rounded-xl flex items-center justify-center text-lime mb-3 sm:mb-4">{f.icon}</div><h3 className="text-lime font-bold mb-1.5 text-sm sm:text-base">{f.title}</h3>
1234567891011121314151617181920212223242526272829303132# requirements-deploy.txt# CPU-only deployment (HuggingFace Spaces / Render / Railway)# GPU version: swap onnxruntime -> onnxruntime-gpu and torch CPU -> CUDA build
# Core webflask==3.0.3flask-cors==4.0.1
# Image processingopencv-python-headless==4.9.0.80numpy==1.26.4Pillow==10.3.0scipy==1.13.0scikit-image==0.23.2imageio==2.34.1
# Face detection and landmarksinsightface==0.7.3onnxruntime==1.18.0mediapipe==0.10.14
# PyTorch CPU-only (much smaller than CUDA build)torch==2.3.0+cputorchvision==0.18.0+cpu--extra-index-url https://download.pytorch.org/whl/cpu
# Color and utilscolormath==3.0.0python-dotenv==1.0.1requests==2.32.2tqdm==4.66.4pyyaml==6.0.11234567891011121314151617181920212223242526272829303132333435363738394041424344454647#!/bin/bashset -e
echo ""echo "======================================"echo " DeepFace Studio — Starting Up"echo "======================================"echo ""
# Download inswapper_128.onnx if not already presentMODEL_PATH="models/inswapper_128.onnx"MODEL_URL="https://huggingface.co/ezioruan/inswapper_128.onnx/resolve/main/inswapper_128.onnx"MODEL_SIZE_MB=528
if [ ! -f "$MODEL_PATH" ]; then echo "Downloading face swap model (~${MODEL_SIZE_MB} MB)..." mkdir -p models python3 - <<'PYEOF'import os, requests, sys
url = "https://huggingface.co/ezioruan/inswapper_128.onnx/resolve/main/inswapper_128.onnx"dest = "models/inswapper_128.onnx"
resp = requests.get(url, stream=True, timeout=300)total = int(resp.headers.get("content-length", 0))done = 0
with open(dest, "wb") as f: for chunk in resp.iter_content(chunk_size=4 * 1024 * 1024): f.write(chunk) done += len(chunk) if total: pct = done * 100 // total mb = done // 1024 // 1024 print(f"\r {mb} / {total // 1024 // 1024} MB ({pct}%)", end="", flush=True)
print("\n Model downloaded successfully.")PYEOFelse echo "Model already present — skipping download."fi
echo ""echo "Starting Flask server on port ${PORT:-7860}..."echo ""
exec python web_app.py229 unmodified lines230231232233234235229 unmodified linesif __name__ == "__main__":print("Starting Face Swap Web App...")print("Open http://localhost:5000 in your browser")app.run(debug=True, host="0.0.0.0", port=5000)229 unmodified lines230231232233234235236229 unmodified linesif __name__ == "__main__":port = int(os.environ.get("PORT", 5000))debug = os.environ.get("FLASK_DEBUG", "true").lower() == "true"print(f"Starting Face Swap Web App on port {port}...")app.run(debug=debug, host="0.0.0.0", port=port)
.github/workflows/ci.ymlAdded+71
.github/workflows/deploy.ymlAdded+75
DockerfileAdded+49
README.mdAdded+73
frontend/src/pages/LandingPage.jsx+16-7
requirements-deploy.txtAdded+32
startup.shAdded+47
web_app.py+4-3