2024-10-09 23:31:54 +02:00
|
|
|
import logging
|
|
|
|
import os
|
|
|
|
import warnings
|
2024-10-22 00:19:34 +02:00
|
|
|
from enum import Enum
|
2024-10-09 23:31:54 +02:00
|
|
|
from io import BytesIO
|
2024-10-13 19:33:27 +02:00
|
|
|
from typing import Dict, List, Optional, Union
|
2024-10-09 23:31:54 +02:00
|
|
|
|
|
|
|
import numpy as np
|
|
|
|
import requests
|
|
|
|
from PIL import Image
|
|
|
|
|
|
|
|
# importing this without pytorch or others causes a warning
|
|
|
|
# https://github.com/huggingface/transformers/issues/27214
|
|
|
|
# suppressed by setting env TRANSFORMERS_NO_ADVISORY_WARNINGS=1
|
|
|
|
from transformers import AutoFeatureExtractor, AutoTokenizer
|
|
|
|
from transformers.utils.logging import disable_progress_bar
|
|
|
|
|
2024-10-10 23:37:43 +02:00
|
|
|
from frigate.comms.inter_process import InterProcessRequestor
|
2024-10-09 23:31:54 +02:00
|
|
|
from frigate.const import MODEL_CACHE_DIR, UPDATE_MODEL_STATE
|
|
|
|
from frigate.types import ModelStatusTypesEnum
|
|
|
|
from frigate.util.downloader import ModelDownloader
|
2024-10-11 18:47:23 +02:00
|
|
|
from frigate.util.model import ONNXModelRunner
|
2024-10-09 23:31:54 +02:00
|
|
|
|
|
|
|
warnings.filterwarnings(
|
|
|
|
"ignore",
|
|
|
|
category=FutureWarning,
|
|
|
|
message="The class CLIPFeatureExtractor is deprecated",
|
|
|
|
)
|
|
|
|
|
|
|
|
# disables the progress bar for downloading tokenizers and feature extractors
|
|
|
|
disable_progress_bar()
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2024-10-23 00:05:48 +02:00
|
|
|
FACE_EMBEDDING_SIZE = 160
|
|
|
|
|
2024-10-09 23:31:54 +02:00
|
|
|
|
2024-10-22 00:19:34 +02:00
|
|
|
class ModelTypeEnum(str, Enum):
|
|
|
|
face = "face"
|
|
|
|
vision = "vision"
|
|
|
|
text = "text"
|
2024-11-02 00:43:21 +01:00
|
|
|
lpr_detect = "lpr_detect"
|
|
|
|
lpr_classify = "lpr_classify"
|
|
|
|
lpr_recognize = "lpr_recognize"
|
2024-10-22 00:19:34 +02:00
|
|
|
|
|
|
|
|
2024-10-09 23:31:54 +02:00
|
|
|
class GenericONNXEmbedding:
|
|
|
|
"""Generic embedding function for ONNX models (text and vision)."""
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
model_name: str,
|
|
|
|
model_file: str,
|
|
|
|
download_urls: Dict[str, str],
|
2024-10-11 00:46:21 +02:00
|
|
|
model_size: str,
|
2024-10-23 00:05:48 +02:00
|
|
|
model_type: ModelTypeEnum,
|
2024-10-10 23:37:43 +02:00
|
|
|
requestor: InterProcessRequestor,
|
2024-10-09 23:31:54 +02:00
|
|
|
tokenizer_file: Optional[str] = None,
|
2024-10-10 15:09:12 +02:00
|
|
|
device: str = "AUTO",
|
2024-10-09 23:31:54 +02:00
|
|
|
):
|
|
|
|
self.model_name = model_name
|
|
|
|
self.model_file = model_file
|
|
|
|
self.tokenizer_file = tokenizer_file
|
2024-10-10 23:37:43 +02:00
|
|
|
self.requestor = requestor
|
2024-10-09 23:31:54 +02:00
|
|
|
self.download_urls = download_urls
|
2024-10-23 00:05:48 +02:00
|
|
|
self.model_type = model_type
|
2024-10-11 18:47:23 +02:00
|
|
|
self.model_size = model_size
|
|
|
|
self.device = device
|
2024-10-09 23:31:54 +02:00
|
|
|
self.download_path = os.path.join(MODEL_CACHE_DIR, self.model_name)
|
|
|
|
self.tokenizer = None
|
|
|
|
self.feature_extractor = None
|
2024-10-11 18:47:23 +02:00
|
|
|
self.runner = None
|
2024-10-10 23:37:43 +02:00
|
|
|
files_names = list(self.download_urls.keys()) + (
|
|
|
|
[self.tokenizer_file] if self.tokenizer_file else []
|
2024-10-09 23:31:54 +02:00
|
|
|
)
|
2024-10-10 23:37:43 +02:00
|
|
|
|
|
|
|
if not all(
|
|
|
|
os.path.exists(os.path.join(self.download_path, n)) for n in files_names
|
|
|
|
):
|
|
|
|
logger.debug(f"starting model download for {self.model_name}")
|
|
|
|
self.downloader = ModelDownloader(
|
|
|
|
model_name=self.model_name,
|
|
|
|
download_path=self.download_path,
|
|
|
|
file_names=files_names,
|
|
|
|
download_func=self._download_model,
|
|
|
|
)
|
|
|
|
self.downloader.ensure_model_files()
|
|
|
|
else:
|
|
|
|
self.downloader = None
|
|
|
|
ModelDownloader.mark_files_state(
|
|
|
|
self.requestor,
|
|
|
|
self.model_name,
|
|
|
|
files_names,
|
|
|
|
ModelStatusTypesEnum.downloaded,
|
|
|
|
)
|
2024-10-26 19:07:45 +02:00
|
|
|
self._load_model_and_utils()
|
2024-10-10 23:37:43 +02:00
|
|
|
logger.debug(f"models are already downloaded for {self.model_name}")
|
2024-10-09 23:31:54 +02:00
|
|
|
|
|
|
|
def _download_model(self, path: str):
|
|
|
|
try:
|
|
|
|
file_name = os.path.basename(path)
|
2024-10-23 00:05:48 +02:00
|
|
|
|
2024-10-09 23:31:54 +02:00
|
|
|
if file_name in self.download_urls:
|
|
|
|
ModelDownloader.download_from_url(self.download_urls[file_name], path)
|
2024-10-22 00:19:34 +02:00
|
|
|
elif (
|
|
|
|
file_name == self.tokenizer_file
|
|
|
|
and self.model_type == ModelTypeEnum.text
|
|
|
|
):
|
2024-10-09 23:31:54 +02:00
|
|
|
if not os.path.exists(path + "/" + self.model_name):
|
|
|
|
logger.info(f"Downloading {self.model_name} tokenizer")
|
2024-10-23 00:05:48 +02:00
|
|
|
|
2024-10-09 23:31:54 +02:00
|
|
|
tokenizer = AutoTokenizer.from_pretrained(
|
|
|
|
self.model_name,
|
|
|
|
trust_remote_code=True,
|
|
|
|
cache_dir=f"{MODEL_CACHE_DIR}/{self.model_name}/tokenizer",
|
|
|
|
clean_up_tokenization_spaces=True,
|
|
|
|
)
|
|
|
|
tokenizer.save_pretrained(path)
|
|
|
|
|
|
|
|
self.downloader.requestor.send_data(
|
|
|
|
UPDATE_MODEL_STATE,
|
|
|
|
{
|
|
|
|
"model": f"{self.model_name}-{file_name}",
|
|
|
|
"state": ModelStatusTypesEnum.downloaded,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
except Exception:
|
|
|
|
self.downloader.requestor.send_data(
|
|
|
|
UPDATE_MODEL_STATE,
|
|
|
|
{
|
|
|
|
"model": f"{self.model_name}-{file_name}",
|
|
|
|
"state": ModelStatusTypesEnum.error,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
|
2024-10-26 19:07:45 +02:00
|
|
|
def _load_model_and_utils(self):
|
2024-10-11 18:47:23 +02:00
|
|
|
if self.runner is None:
|
2024-10-10 23:37:43 +02:00
|
|
|
if self.downloader:
|
|
|
|
self.downloader.wait_for_download()
|
2024-10-22 00:19:34 +02:00
|
|
|
if self.model_type == ModelTypeEnum.text:
|
2024-10-09 23:31:54 +02:00
|
|
|
self.tokenizer = self._load_tokenizer()
|
2024-10-23 00:05:48 +02:00
|
|
|
elif self.model_type == ModelTypeEnum.vision:
|
2024-10-09 23:31:54 +02:00
|
|
|
self.feature_extractor = self._load_feature_extractor()
|
2024-10-23 00:05:48 +02:00
|
|
|
elif self.model_type == ModelTypeEnum.face:
|
|
|
|
self.feature_extractor = []
|
2024-11-02 00:43:21 +01:00
|
|
|
elif self.model_type == ModelTypeEnum.lpr_detect:
|
2024-10-26 19:07:45 +02:00
|
|
|
self.feature_extractor = []
|
2024-11-02 00:43:21 +01:00
|
|
|
elif self.model_type == ModelTypeEnum.lpr_classify:
|
2024-10-26 19:07:45 +02:00
|
|
|
self.feature_extractor = []
|
2024-11-02 00:43:21 +01:00
|
|
|
elif self.model_type == ModelTypeEnum.lpr_recognize:
|
2024-10-26 19:07:45 +02:00
|
|
|
self.feature_extractor = []
|
2024-10-23 00:05:48 +02:00
|
|
|
|
2024-10-11 18:47:23 +02:00
|
|
|
self.runner = ONNXModelRunner(
|
|
|
|
os.path.join(self.download_path, self.model_file),
|
|
|
|
self.device,
|
|
|
|
self.model_size,
|
2024-10-09 23:31:54 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
def _load_tokenizer(self):
|
|
|
|
tokenizer_path = os.path.join(f"{MODEL_CACHE_DIR}/{self.model_name}/tokenizer")
|
|
|
|
return AutoTokenizer.from_pretrained(
|
|
|
|
self.model_name,
|
|
|
|
cache_dir=tokenizer_path,
|
|
|
|
trust_remote_code=True,
|
|
|
|
clean_up_tokenization_spaces=True,
|
|
|
|
)
|
|
|
|
|
|
|
|
def _load_feature_extractor(self):
|
|
|
|
return AutoFeatureExtractor.from_pretrained(
|
|
|
|
f"{MODEL_CACHE_DIR}/{self.model_name}",
|
|
|
|
)
|
|
|
|
|
2024-10-22 00:19:34 +02:00
|
|
|
def _preprocess_inputs(self, raw_inputs: any) -> any:
|
|
|
|
if self.model_type == ModelTypeEnum.text:
|
|
|
|
max_length = max(len(self.tokenizer.encode(text)) for text in raw_inputs)
|
|
|
|
return [
|
|
|
|
self.tokenizer(
|
|
|
|
text,
|
|
|
|
padding="max_length",
|
|
|
|
truncation=True,
|
|
|
|
max_length=max_length,
|
|
|
|
return_tensors="np",
|
|
|
|
)
|
|
|
|
for text in raw_inputs
|
|
|
|
]
|
|
|
|
elif self.model_type == ModelTypeEnum.vision:
|
|
|
|
processed_images = [self._process_image(img) for img in raw_inputs]
|
|
|
|
return [
|
|
|
|
self.feature_extractor(images=image, return_tensors="np")
|
|
|
|
for image in processed_images
|
|
|
|
]
|
2024-10-23 00:05:48 +02:00
|
|
|
elif self.model_type == ModelTypeEnum.face:
|
|
|
|
if isinstance(raw_inputs, list):
|
|
|
|
raise ValueError("Face embedding does not support batch inputs.")
|
|
|
|
|
|
|
|
pil = self._process_image(raw_inputs)
|
|
|
|
|
|
|
|
# handle images larger than input size
|
|
|
|
width, height = pil.size
|
|
|
|
if width != FACE_EMBEDDING_SIZE or height != FACE_EMBEDDING_SIZE:
|
|
|
|
if width > height:
|
|
|
|
new_height = int(((height / width) * FACE_EMBEDDING_SIZE) // 4 * 4)
|
|
|
|
pil = pil.resize((FACE_EMBEDDING_SIZE, new_height))
|
|
|
|
else:
|
|
|
|
new_width = int(((width / height) * FACE_EMBEDDING_SIZE) // 4 * 4)
|
|
|
|
pil = pil.resize((new_width, FACE_EMBEDDING_SIZE))
|
|
|
|
|
|
|
|
og = np.array(pil).astype(np.float32)
|
|
|
|
|
|
|
|
# Image must be FACE_EMBEDDING_SIZExFACE_EMBEDDING_SIZE
|
|
|
|
og_h, og_w, channels = og.shape
|
|
|
|
frame = np.full(
|
|
|
|
(FACE_EMBEDDING_SIZE, FACE_EMBEDDING_SIZE, channels),
|
|
|
|
(0, 0, 0),
|
|
|
|
dtype=np.float32,
|
|
|
|
)
|
|
|
|
|
|
|
|
# compute center offset
|
|
|
|
x_center = (FACE_EMBEDDING_SIZE - og_w) // 2
|
|
|
|
y_center = (FACE_EMBEDDING_SIZE - og_h) // 2
|
|
|
|
|
|
|
|
# copy img image into center of result image
|
|
|
|
frame[y_center : y_center + og_h, x_center : x_center + og_w] = og
|
|
|
|
frame = np.expand_dims(frame, axis=0)
|
2024-10-29 00:35:20 +01:00
|
|
|
return [{"input_2": frame}]
|
2024-11-02 00:43:21 +01:00
|
|
|
elif self.model_type == ModelTypeEnum.lpr_detect:
|
2024-10-26 19:07:45 +02:00
|
|
|
preprocessed = []
|
|
|
|
for x in raw_inputs:
|
|
|
|
preprocessed.append(x)
|
|
|
|
return [{"x": preprocessed[0]}]
|
2024-11-02 00:43:21 +01:00
|
|
|
elif self.model_type == ModelTypeEnum.lpr_classify:
|
2024-10-26 19:07:45 +02:00
|
|
|
processed = []
|
|
|
|
for img in raw_inputs:
|
|
|
|
processed.append({"x": img})
|
|
|
|
return processed
|
2024-11-02 00:43:21 +01:00
|
|
|
elif self.model_type == ModelTypeEnum.lpr_recognize:
|
2024-10-26 19:07:45 +02:00
|
|
|
processed = []
|
|
|
|
for img in raw_inputs:
|
|
|
|
processed.append({"x": img})
|
|
|
|
return processed
|
2024-10-22 00:19:34 +02:00
|
|
|
else:
|
|
|
|
raise ValueError(f"Unable to preprocess inputs for {self.model_type}")
|
|
|
|
|
2024-10-23 00:05:48 +02:00
|
|
|
def _process_image(self, image, output: str = "RGB") -> Image.Image:
|
2024-10-09 23:31:54 +02:00
|
|
|
if isinstance(image, str):
|
|
|
|
if image.startswith("http"):
|
|
|
|
response = requests.get(image)
|
2024-10-23 00:05:48 +02:00
|
|
|
image = Image.open(BytesIO(response.content)).convert(output)
|
2024-10-22 00:19:34 +02:00
|
|
|
elif isinstance(image, bytes):
|
2024-10-23 00:05:48 +02:00
|
|
|
image = Image.open(BytesIO(image)).convert(output)
|
2024-10-09 23:31:54 +02:00
|
|
|
|
|
|
|
return image
|
|
|
|
|
|
|
|
def __call__(
|
|
|
|
self, inputs: Union[List[str], List[Image.Image], List[str]]
|
|
|
|
) -> List[np.ndarray]:
|
2024-10-26 19:07:45 +02:00
|
|
|
self._load_model_and_utils()
|
2024-10-11 18:47:23 +02:00
|
|
|
if self.runner is None or (
|
2024-10-09 23:31:54 +02:00
|
|
|
self.tokenizer is None and self.feature_extractor is None
|
|
|
|
):
|
|
|
|
logger.error(
|
|
|
|
f"{self.model_name} model or tokenizer/feature extractor is not loaded."
|
|
|
|
)
|
|
|
|
return []
|
|
|
|
|
2024-10-22 00:19:34 +02:00
|
|
|
processed_inputs = self._preprocess_inputs(inputs)
|
2024-10-11 18:47:23 +02:00
|
|
|
input_names = self.runner.get_input_names()
|
2024-10-13 19:33:27 +02:00
|
|
|
onnx_inputs = {name: [] for name in input_names}
|
|
|
|
input: dict[str, any]
|
|
|
|
for input in processed_inputs:
|
|
|
|
for key, value in input.items():
|
|
|
|
if key in input_names:
|
|
|
|
onnx_inputs[key].append(value[0])
|
2024-10-09 23:31:54 +02:00
|
|
|
|
2024-10-13 23:25:13 +02:00
|
|
|
for key in input_names:
|
|
|
|
if onnx_inputs.get(key):
|
|
|
|
onnx_inputs[key] = np.stack(onnx_inputs[key])
|
|
|
|
else:
|
|
|
|
logger.warning(f"Expected input '{key}' not found in onnx_inputs")
|
2024-10-09 23:31:54 +02:00
|
|
|
|
2024-10-13 19:33:27 +02:00
|
|
|
embeddings = self.runner.run(onnx_inputs)[0]
|
2024-10-09 23:31:54 +02:00
|
|
|
return [embedding for embedding in embeddings]
|