# โšก Quick Start - Deploy MedSAM to HuggingFace Space ## ๐ŸŽฏ Goal Deploy your MedSAM model as an API that you can call from your backend. ## ๐Ÿ“ฆ What's in This Folder ``` huggingface_space/ โ”œโ”€โ”€ app.py # Gradio app (upload to HF Space) โ”œโ”€โ”€ requirements.txt # Dependencies (upload to HF Space) โ”œโ”€โ”€ README.md # Space description (upload to HF Space) โ”œโ”€โ”€ .gitattributes # Git LFS config (upload to HF Space) โ”œโ”€โ”€ DEPLOYMENT_GUIDE.md # Detailed deployment steps โ”œโ”€โ”€ integration_example.py # How to use in your backend โ”œโ”€โ”€ test_space.py # Test script after deployment โ””โ”€โ”€ QUICKSTART.md # This file ``` ## ๐Ÿš€ Deploy in 5 Steps ### Step 1: Create Space (2 min) 1. Go to: https://huggingface.co/new-space 2. Fill in: - Space name: `medsam-inference` - SDK: **Gradio** - Hardware: **CPU basic** (free) or **T4 small** (GPU, $0.60/hr) 3. Click **Create Space** ### Step 2: Upload Files (3 min) **Option A: Via Web (Easiest)** 1. In your Space, click **Files** โ†’ **Add file** โ†’ **Upload files** 2. Upload these 4 files: - `app.py` - `requirements.txt` - `README.md` - `.gitattributes` **Option B: Via Git** ```bash # Clone your Space git clone https://huggingface.co/spaces/YOUR_USERNAME/medsam-inference cd medsam-inference # Copy files cp app.py requirements.txt README.md .gitattributes . # Commit git add . git commit -m "Initial commit" git push ``` ### Step 3: Upload Model (2 min) **Download your model:** Go to: https://huggingface.co/Aniketg6/Fine-Tuned-MedSAM Download: `medsam_vit_b.pth` (375 MB) **Upload to Space:** - Via web: **Files** โ†’ **Add file** โ†’ **Upload file** โ†’ Upload `medsam_vit_b.pth` - Via git: ```bash # Make sure Git LFS is installed git lfs install git lfs track "*.pth" # Copy your model cp /path/to/medsam_vit_b.pth . # Commit (will use LFS for large file) git add .gitattributes medsam_vit_b.pth git commit -m "Add MedSAM model" git push ``` ### Step 4: Wait for Build (3-5 min) - HuggingFace will build your Space automatically - Check **Logs** tab to see progress - When done, you'll see "Running" status โœ… ### Step 5: Test It! (1 min) 1. Visit your Space: `https://huggingface.co/spaces/YOUR_USERNAME/medsam-inference` 2. Click **Simple Interface** tab 3. Upload a test image 4. Enter X, Y coordinates (e.g., 200, 150) 5. Click **Segment** 6. You should see a mask! ๐ŸŽ‰ ## โœ… Your API is Ready! **Endpoint:** `https://YOUR_USERNAME-medsam-inference.hf.space/api/predict` --- ## ๐Ÿ”— Use in Your Backend ### Quick Integration 1. **Create client file:** ```bash cd backend nano medsam_space_client.py ``` 2. **Add this code:** ```python import requests import json import base64 from io import BytesIO from PIL import Image import numpy as np SPACE_URL = "https://YOUR_USERNAME-medsam-inference.hf.space/api/predict" class MedSAMSpacePredictor: def __init__(self, space_url): self.space_url = space_url self.image_array = None def set_image(self, image): self.image_array = image def predict(self, point_coords, point_labels, multimask_output=True, **kwargs): # Convert to base64 img = Image.fromarray(self.image_array) buf = BytesIO() img.save(buf, format="PNG") img_b64 = base64.b64encode(buf.getvalue()).decode() # Call API points_json = json.dumps({ "coords": point_coords.tolist(), "labels": point_labels.tolist(), "multimask_output": multimask_output }) resp = requests.post( self.space_url, json={"data": [f"data:image/png;base64,{img_b64}", points_json]}, timeout=120 ) result = json.loads(resp.json()["data"][0]) masks = np.array([np.array(m["mask_data"], dtype=bool) for m in result["masks"]]) scores = np.array(result["scores"]) return masks, scores, None ``` 3. **Update app.py:** ```python # Add import from medsam_space_client import MedSAMSpacePredictor # Replace this: # sam_predictor = SamPredictor(sam) # With this: sam_predictor = MedSAMSpacePredictor( "https://YOUR_USERNAME-medsam-inference.hf.space/api/predict" ) # Everything else stays the same! # sam_predictor.set_image(image_array) # masks, scores, _ = sam_predictor.predict(...) ``` 4. **Done!** Your backend now uses the HF Space API โœ… --- ## ๐Ÿงช Test Your Integration ```bash cd backend/huggingface_space # Update SPACE_URL in test_space.py first nano test_space.py # Run test python test_space.py path/to/test/image.jpg 200 150 ``` Should see: ``` โœ… TEST PASSED! Your Space is working correctly! ``` --- ## ๐Ÿ’ฐ Cost **Free Tier (CPU Basic):** - โœ… Free! - โš ๏ธ Slower (~5-10 seconds per image) - โš ๏ธ Sleeps after 48h inactivity **Paid Tier (T4 Small GPU):** - ๐Ÿ’ฐ $0.60/hour - โœ… Fast (~1-2 seconds) - โœ… Always on **Upgrade:** Space Settings โ†’ Hardware โ†’ T4 small --- ## ๐Ÿ› Troubleshooting **"Application startup failed"** โ†’ Check Logs tab, make sure medsam_vit_b.pth is uploaded **"Space is sleeping"** โ†’ First request wakes it (takes 10-20s) **API timeout** โ†’ Space might be sleeping or overloaded, retry **CORS error** โ†’ Update your backend CORS settings --- ## ๐Ÿ“š More Info - **Detailed guide:** `DEPLOYMENT_GUIDE.md` - **Integration examples:** `integration_example.py` - **Test script:** `test_space.py` --- ## โœจ Summary 1. โœ… Create Space on HuggingFace (2 min) 2. โœ… Upload 4 files + model (5 min) 3. โœ… Wait for build (3-5 min) 4. โœ… Test via UI (1 min) 5. โœ… Integrate with backend (5 min) 6. ๐ŸŽ‰ **Total: ~15 minutes!** **Your MedSAM model is now a cloud API!** ๐Ÿš€ --- **Questions? Check:** `DEPLOYMENT_GUIDE.md`