💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows
Python agentsaiai-agentsembeddingsinformation-retrievallanguage-modellarge-language-modelsllmnlppythonragretrieval-augmented-generationsearchsearch-enginesemantic-searchsentence-embeddingstransformerstxtaivector-databasevector-search
Add image caption pipeline, closes #149
davidmezzetti836080b69a8c
diff --git a/src/python/txtai/pipeline/image/__init__.py b/src/python/txtai/pipeline/image/__init__.pynew file mode 100644index 00000000..f1ac9151--- /dev/null+++ b/src/python/txtai/pipeline/image/__init__.py@@ -0,0 +1,6 @@+"""+Image imports+"""++from .caption import Caption+from .objects import Objectsdiff --git a/src/python/txtai/pipeline/image/caption.py b/src/python/txtai/pipeline/image/caption.pynew file mode 100644index 00000000..8a494cf8--- /dev/null+++ b/src/python/txtai/pipeline/image/caption.py@@ -0,0 +1,70 @@+"""+Caption module+"""++import torch++from transformers import AutoTokenizer, VisionEncoderDecoderModel, ViTFeatureExtractor++from ..hfmodel import HFModel+++class Caption(HFModel):+ """+ Transcribes audio files to text.+ """++ def __init__(self, path="ydshieh/vit-gpt2-coco-en", quantize=False, gpu=True, batch=64):+ """+ Constructs a new caption pipeline.++ Args:+ path: optional path to model, accepts Hugging Face model hub id or local path,+ uses default model for task if not provided+ quantize: if model should be quantized, defaults to False+ gpu: True/False if GPU should be enabled, also supports a GPU device id+ batch: batch size used to incrementally process content+ """++ # Call parent constructor+ super().__init__(path, quantize, gpu, batch)++ # load model and processor+ self.model = VisionEncoderDecoderModel.from_pretrained(self.path)+ self.tokenizer = AutoTokenizer.from_pretrained(self.path)+ self.extractor = ViTFeatureExtractor.from_pretrained(self.path)++ # Move model to device+ self.model.to(self.device)++ def __call__(self, images):+ """+ Builds captions for images.++ This method supports a single image or a list of images. If the input is an image, the return+ type is a string. If text is a list, a list of strings is returned++ Args:+ images: image|list++ Returns:+ list of captions+ """++ # Convert single element to list+ values = [images] if not isinstance(images, list) else images++ # Feature extraction+ pixels = self.extractor(images=values, return_tensors="pt").pixel_values+ pixels = pixels.to(self.device)++ # Run model+ with torch.no_grad():+ outputs = self.model.generate(pixels, max_length=16, num_beams=4, return_dict_in_generate=True).sequences++ # Tokenize outputs into text results+ captions = self.tokenizer.batch_decode(outputs, skip_special_tokens=True)+ captions = [caption.strip() for caption in captions]++ # Return single element if single element passed in+ return captions[0] if not isinstance(images, list) else captionsdiff --git a/test/python/testcaption.py b/test/python/testcaption.pynew file mode 100644index 00000000..6cacb9e9--- /dev/null+++ b/test/python/testcaption.py@@ -0,0 +1,26 @@+"""+Caption module tests+"""++import unittest++from PIL import Image++from txtai.pipeline import Caption++# pylint: disable = C0411+from utils import Utils+++class TestCaption(unittest.TestCase):+ """+ Caption tests+ """++ def testCaption(self):+ """+ Test captions+ """++ caption = Caption()+ self.assertEqual(caption(Image.open(Utils.PATH + "/books.jpg")), "a book shelf filled with many books")