File size: 1,648 Bytes
4ae7d54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import torch

import numpy as np
import supervision as sv
from PIL import Image


CAPTIONING_TASK = "<DETAILED_CAPTION>"
CAPTION_TO_PHRASE_GROUNDING_TASK = "<CAPTION_TO_PHRASE_GROUNDING>"


def run_captioning(model, processor, image: np.ndarray, device: torch.device) -> str:
    image = Image.fromarray(image).convert("RGB")
    text = "<DETAILED_CAPTION>"

    inputs = processor(text=text, images=image, return_tensors="pt").to(device)
    generated_ids = model.generate(
        input_ids=inputs["input_ids"],
        pixel_values=inputs["pixel_values"],
        max_new_tokens=1024,
        num_beams=3
    )
    generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
    return processor.post_process_generation(
        generated_text, task=CAPTIONING_TASK, image_size=image.size)


def run_caption_to_phrase_grounding(
    model,
    processor,
    caption: str,
    image: np.ndarray,
    device: torch.device
) -> sv.Detections:
    image = Image.fromarray(image).convert("RGB")
    text = f"{CAPTION_TO_PHRASE_GROUNDING_TASK} {caption}"

    inputs = processor(text=text, images=image, return_tensors="pt").to(device)
    generated_ids = model.generate(
        input_ids=inputs["input_ids"],
        pixel_values=inputs["pixel_values"],
        max_new_tokens=1024,
        num_beams=3
    )
    generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
    response = processor.post_process_generation(
        generated_text, task=CAPTION_TO_PHRASE_GROUNDING_TASK, image_size=image.size)
    return sv.Detections.from_lmm(sv.LMM.FLORENCE_2, response, resolution_wh=image.size)