Instructions to use paragon-AI/blip2-image-to-text with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use paragon-AI/blip2-image-to-text 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="paragon-AI/blip2-image-to-text")# pip install -U transformers accelerate # Load model directly from transformers import AutoProcessor, AutoModelForMultimodalLM processor = AutoProcessor.from_pretrained("paragon-AI/blip2-image-to-text") model = AutoModelForMultimodalLM.from_pretrained("paragon-AI/blip2-image-to-text", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Download handler.py from paragon-AI/blip2-image-to-text: direct link, hf CLI and curl.
- Browser
- Download file 1.54 kB
-
https://huggingface.co/paragon-AI/blip2-image-to-text/resolve/main/handler.py
- Command line
-
hf download hf://paragon-AI/blip2-image-to-text/handler.py
-
curl -L -o handler.py https://huggingface.co/paragon-AI/blip2-image-to-text/resolve/main/handler.py
1.54 kB
| from typing import Dict, List, Any | |
| from transformers import Blip2Processor, Blip2ForConditionalGeneration | |
| from PIL import Image | |
| from io import BytesIO | |
| import torch, re, base64 | |
| class EndpointHandler: | |
| def __init__(self, path=""): | |
| # load the optimized model | |
| self.processor = Blip2Processor.from_pretrained("Salesforce/blip2-opt-2.7b") | |
| self.model = Blip2ForConditionalGeneration.from_pretrained("Salesforce/blip2-opt-2.7b", device_map="auto") | |
| def __call__(self, data: Any) -> Dict[str, Any]: | |
| """ | |
| Args: | |
| data (:obj:): | |
| includes the input data and the parameters for the inference. | |
| Return: | |
| A :obj:`dict`:. The object returned should be a dict of one list like {"captions": ["A hugging face at the office"]} containing : | |
| - "caption": A string corresponding to the generated caption. | |
| """ | |
| # parameters = data.pop("parameters", {}) | |
| device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') | |
| inputs = base64.b64decode(re.sub('^data:image/.+;base64,', '', data['inputs'])) | |
| raw_images = Image.open(BytesIO(inputs)) | |
| processed_image = self.processor(images=raw_images, return_tensors="pt").to(device) | |
| out = self.model.generate(**processed_image) | |
| captions = self.processor.decode(out[0], skip_special_tokens=True) | |
| # postprocess the prediction | |
| return {"captions": captions} | |
| EndpointHandler() |