73 lines
2.1 KiB
Python
73 lines
2.1 KiB
Python
import torch
|
|
from PIL import Image
|
|
from transformers import CLIPProcessor, CLIPModel
|
|
|
|
from app.config.logging import logger
|
|
from app.config.settings import settings
|
|
from app.ml.image.clip_prediction_result import ClipPredictionResult
|
|
from app.ml.model_manager import model_manager
|
|
|
|
|
|
class ClipClassifier:
|
|
NORMAL_LABEL = "a normal photo"
|
|
|
|
LABELS = [
|
|
NORMAL_LABEL,
|
|
"a photo containing marijuana",
|
|
"a photo containing drugs",
|
|
"a photo containing violence"
|
|
]
|
|
|
|
def __init__(self):
|
|
self.device = model_manager.get_device()
|
|
logger.info("Loading CLIP on %s", self.device)
|
|
|
|
self.model = CLIPModel.from_pretrained(settings.IMAGE_CLIP_MODEL)
|
|
self.processor = CLIPProcessor.from_pretrained(settings.IMAGE_CLIP_MODEL)
|
|
|
|
self.model.to(self.device)
|
|
self.model.eval()
|
|
|
|
# Метки постоянные — токенизируем один раз. Заодно запросы не трогают
|
|
# общий токенизатор, который не потокобезопасен.
|
|
self.text_inputs = {
|
|
key: value.to(self.device)
|
|
for key, value in self.processor(
|
|
text=self.LABELS,
|
|
padding=True,
|
|
return_tensors="pt"
|
|
).items()
|
|
}
|
|
|
|
def predict(self, image: Image.Image) -> ClipPredictionResult:
|
|
pixel_values = self.processor(
|
|
images=image,
|
|
return_tensors="pt"
|
|
)["pixel_values"].to(self.device)
|
|
|
|
with torch.inference_mode():
|
|
outputs = self.model(pixel_values=pixel_values, **self.text_inputs)
|
|
probs = outputs.logits_per_image.softmax(dim=1)[0]
|
|
|
|
scores = {}
|
|
detected_labels = []
|
|
|
|
for index, probability in enumerate(probs):
|
|
label = self.LABELS[index]
|
|
score = float(probability)
|
|
scores[label] = score
|
|
|
|
if label != self.NORMAL_LABEL and score >= settings.CLIP_THRESHOLD:
|
|
detected_labels.append(label)
|
|
|
|
max_index = int(torch.argmax(probs).item())
|
|
|
|
logger.debug("CLIP scores: %s", scores)
|
|
|
|
return ClipPredictionResult(
|
|
label=self.LABELS[max_index],
|
|
score=float(probs[max_index]),
|
|
detected_labels=detected_labels,
|
|
scores=scores
|
|
)
|