Instructions to use Salesforce/blip-image-captioning-large with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Salesforce/blip-image-captioning-large with Transformers:
# Use a pipeline as a high-level helper # Warning: Pipeline type "image-to-text" is no longer supported in transformers v5. # You must load the model directly (see below) or downgrade to v4.x with: # pip install "transformers<5.0.0" from transformers import pipeline pipe = pipeline("image-to-text", model="Salesforce/blip-image-captioning-large")# pip install -U transformers accelerate # Load model directly from transformers import AutoProcessor, AutoModelForMultimodalLM processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-large") model = AutoModelForMultimodalLM.from_pretrained("Salesforce/blip-image-captioning-large", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Download Handler.py from Salesforce/blip-image-captioning-large: direct link, hf CLI and curl.
- Browser
- Download file 1.48 kB
-
https://huggingface.co/Salesforce/blip-image-captioning-large/resolve/refs%2Fpr%2F46/Handler.py
- Command line
-
hf download hf://Salesforce/blip-image-captioning-large@refs/pr/46/Handler.py
-
curl -L -o Handler.py https://huggingface.co/Salesforce/blip-image-captioning-large/resolve/refs%2Fpr%2F46/Handler.py
1.48 kB
| from transformers import BlipProcessor, BlipForConditionalGeneration | |
| from PIL import Image | |
| import requests | |
| import torch | |
| import base64 | |
| import io | |
| class EndpointHandler: | |
| def __init__(self, path): | |
| self.processor = BlipProcessor.from_pretrained(path) | |
| self.model = BlipForConditionalGeneration.from_pretrained( | |
| path, | |
| torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32 | |
| ) | |
| self.device = "cuda" if torch.cuda.is_available() else "cpu" | |
| self.model.to(self.device) | |
| def _load_image(self, image_input): | |
| # URL | |
| if isinstance(image_input, str) and image_input.startswith("http"): | |
| return Image.open(requests.get(image_input, stream=True).raw).convert("RGB") | |
| # Base64 | |
| if isinstance(image_input, str): | |
| image_bytes = base64.b64decode(image_input) | |
| return Image.open(io.BytesIO(image_bytes)).convert("RGB") | |
| raise ValueError("Unsupported image input format") | |
| def __call__(self, data): | |
| image_input = data.get("inputs") | |
| if image_input is None: | |
| raise ValueError("No image provided") | |
| image = self._load_image(image_input) | |
| inputs = self.processor(images=image, return_tensors="pt").to(self.device) | |
| output = self.model.generate(**inputs, max_new_tokens=50) | |
| caption = self.processor.decode(output[0], skip_special_tokens=True) | |
| return {"caption": caption} | |