CoolFace
Apppublic

Dense-Captioning/medsam-inference

sourceHugging Faceapache-2.0updated 9mo agoView on Hugging Face
0likes
QUICKSTART.md260 linesDownload Raw Back to root
1# โšก Quick Start - Deploy MedSAM to HuggingFace Space2 3## ๐ŸŽฏ Goal4Deploy your MedSAM model as an API that you can call from your backend.5 6## ๐Ÿ“ฆ What's in This Folder7 8```9huggingface_space/10โ”œโ”€โ”€ app.py                    # Gradio app (upload to HF Space)11โ”œโ”€โ”€ requirements.txt          # Dependencies (upload to HF Space)12โ”œโ”€โ”€ README.md                # Space description (upload to HF Space)13โ”œโ”€โ”€ .gitattributes           # Git LFS config (upload to HF Space)14โ”œโ”€โ”€ DEPLOYMENT_GUIDE.md      # Detailed deployment steps15โ”œโ”€โ”€ integration_example.py   # How to use in your backend16โ”œโ”€โ”€ test_space.py           # Test script after deployment17โ””โ”€โ”€ QUICKSTART.md           # This file18```19 20## ๐Ÿš€ Deploy in 5 Steps21 22### Step 1: Create Space (2 min)23 241. Go to: https://huggingface.co/new-space252. Fill in:26   - Space name: `medsam-inference`27   - SDK: **Gradio**28   - Hardware: **CPU basic** (free) or **T4 small** (GPU, $0.60/hr)293. Click **Create Space**30 31### Step 2: Upload Files (3 min)32 33**Option A: Via Web (Easiest)**34 351. In your Space, click **Files** โ†’ **Add file** โ†’ **Upload files**362. Upload these 4 files:37   - `app.py`38   - `requirements.txt`39   - `README.md`40   - `.gitattributes`41 42**Option B: Via Git**43 44```bash45# Clone your Space46git clone https://huggingface.co/spaces/YOUR_USERNAME/medsam-inference47cd medsam-inference48 49# Copy files50cp app.py requirements.txt README.md .gitattributes .51 52# Commit53git add .54git commit -m "Initial commit"55git push56```57 58### Step 3: Upload Model (2 min)59 60**Download your model:**61 62Go to: https://huggingface.co/Aniketg6/Fine-Tuned-MedSAM63 64Download: `medsam_vit_b.pth` (375 MB)65 66**Upload to Space:**67 68- Via web: **Files** โ†’ **Add file** โ†’ **Upload file** โ†’ Upload `medsam_vit_b.pth`69- Via git: 70  ```bash71  # Make sure Git LFS is installed72  git lfs install73  git lfs track "*.pth"74  75  # Copy your model76  cp /path/to/medsam_vit_b.pth .77  78  # Commit (will use LFS for large file)79  git add .gitattributes medsam_vit_b.pth80  git commit -m "Add MedSAM model"81  git push82  ```83 84### Step 4: Wait for Build (3-5 min)85 86- HuggingFace will build your Space automatically87- Check **Logs** tab to see progress88- When done, you'll see "Running" status โœ…89 90### Step 5: Test It! (1 min)91 921. Visit your Space: `https://huggingface.co/spaces/YOUR_USERNAME/medsam-inference`932. Click **Simple Interface** tab943. Upload a test image954. Enter X, Y coordinates (e.g., 200, 150)965. Click **Segment**976. You should see a mask! ๐ŸŽ‰98 99## โœ… Your API is Ready!100 101**Endpoint:** `https://YOUR_USERNAME-medsam-inference.hf.space/api/predict`102 103---104 105## ๐Ÿ”— Use in Your Backend106 107### Quick Integration108 1091. **Create client file:**110 111```bash112cd backend113nano medsam_space_client.py114```115 1162. **Add this code:**117 118```python119import requests120import json121import base64122from io import BytesIO123from PIL import Image124import numpy as np125 126SPACE_URL = "https://YOUR_USERNAME-medsam-inference.hf.space/api/predict"127 128class MedSAMSpacePredictor:129    def __init__(self, space_url):130        self.space_url = space_url131        self.image_array = None132    133    def set_image(self, image):134        self.image_array = image135    136    def predict(self, point_coords, point_labels, multimask_output=True, **kwargs):137        # Convert to base64138        img = Image.fromarray(self.image_array)139        buf = BytesIO()140        img.save(buf, format="PNG")141        img_b64 = base64.b64encode(buf.getvalue()).decode()142        143        # Call API144        points_json = json.dumps({145            "coords": point_coords.tolist(),146            "labels": point_labels.tolist(),147            "multimask_output": multimask_output148        })149        150        resp = requests.post(151            self.space_url,152            json={"data": [f"data:image/png;base64,{img_b64}", points_json]},153            timeout=120154        )155        156        result = json.loads(resp.json()["data"][0])157        masks = np.array([np.array(m["mask_data"], dtype=bool) for m in result["masks"]])158        scores = np.array(result["scores"])159        160        return masks, scores, None161```162 1633. **Update app.py:**164 165```python166# Add import167from medsam_space_client import MedSAMSpacePredictor168 169# Replace this:170# sam_predictor = SamPredictor(sam)171 172# With this:173sam_predictor = MedSAMSpacePredictor(174    "https://YOUR_USERNAME-medsam-inference.hf.space/api/predict"175)176 177# Everything else stays the same!178# sam_predictor.set_image(image_array)179# masks, scores, _ = sam_predictor.predict(...)180```181 1824. **Done!** Your backend now uses the HF Space API โœ…183 184---185 186## ๐Ÿงช Test Your Integration187 188```bash189cd backend/huggingface_space190 191# Update SPACE_URL in test_space.py first192nano test_space.py193 194# Run test195python test_space.py path/to/test/image.jpg 200 150196```197 198Should see:199```200โœ… TEST PASSED! Your Space is working correctly!201```202 203---204 205## ๐Ÿ’ฐ Cost206 207**Free Tier (CPU Basic):**208- โœ… Free!209- โš ๏ธ Slower (~5-10 seconds per image)210- โš ๏ธ Sleeps after 48h inactivity211 212**Paid Tier (T4 Small GPU):**213- ๐Ÿ’ฐ $0.60/hour214- โœ… Fast (~1-2 seconds)215- โœ… Always on216 217**Upgrade:** Space Settings โ†’ Hardware โ†’ T4 small218 219---220 221## ๐Ÿ› Troubleshooting222 223**"Application startup failed"**224โ†’ Check Logs tab, make sure medsam_vit_b.pth is uploaded225 226**"Space is sleeping"**227โ†’ First request wakes it (takes 10-20s)228 229**API timeout**230โ†’ Space might be sleeping or overloaded, retry231 232**CORS error**233โ†’ Update your backend CORS settings234 235---236 237## ๐Ÿ“š More Info238 239- **Detailed guide:** `DEPLOYMENT_GUIDE.md`240- **Integration examples:** `integration_example.py`241- **Test script:** `test_space.py`242 243---244 245## โœจ Summary246 2471. โœ… Create Space on HuggingFace (2 min)2482. โœ… Upload 4 files + model (5 min)2493. โœ… Wait for build (3-5 min)2504. โœ… Test via UI (1 min)2515. โœ… Integrate with backend (5 min)2526. ๐ŸŽ‰ **Total: ~15 minutes!**253 254**Your MedSAM model is now a cloud API!** ๐Ÿš€255 256---257 258**Questions? Check:** `DEPLOYMENT_GUIDE.md`259 260