from PIL import Image
from inference.models.paligemma.paligemma import PaliGemma
model = PaliGemma("paligemma-3b-mix-224", api_key="YOUR_API_KEY")
image = Image.open("image.jpeg")
result = model.predict(image, "この画像には何匹の犬がいますか?")
print(result)
import re
from typing import List, Optional, Tuple
import numpy as np
import supervision as sv
_DETECT_RE = re.compile(r"(.*?)" + r"<loc(\d{4})>" * 4 + r"\s*([^;<>]+)? ?(?:; )?")
def from_pali_gemma(
response: str,
resolution_wh: Tuple[int, int],
class_list: Optional[List[str]] = None,
) -> sv.Detections:
width, height = resolution_wh
xyxy_list, class_name_list = [], []
while response:
match = _DETECT_RE.match(response)
if not match:
break
groups = list(match.groups())
before = groups.pop(0)
name = groups.pop()
y1, x1, y2, x2 = [int(value) / 1024 for value in groups[:4]]
y1, x1, y2, x2 = map(round, (y1 * height, x1 * width, y2 * height, x2 * width))
content = match.group()
if before:
response = response[len(before):]
content = content[len(before):]
xyxy_list.append([x1, y1, x2, y2])
class_name_list.append(name.strip())
response = response[len(content):]
class_name = np.array(class_name_list)
class_id = (
np.array([class_list.index(name) for name in class_name])
if class_list is not None
else None
)
return sv.Detections(
xyxy=np.array(xyxy_list),
class_id=class_id,
data={"class_name": class_name},
)
classes = ["person", "car", "backpack"]
response = model.predict(image, "detect person; car; backpack")[0]
detections = from_pali_gemma(response, resolution_wh=image.size, class_list=classes)