fix problem from claude
This commit is contained in:
@@ -2,21 +2,25 @@ 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 = [
|
||||
"a normal photo",
|
||||
NORMAL_LABEL,
|
||||
"a photo containing marijuana",
|
||||
"a photo containing drugs",
|
||||
"a photo containing violence"
|
||||
]
|
||||
|
||||
def __init__(self):
|
||||
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
||||
print(f"Loading CLIP on {self.device}")
|
||||
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)
|
||||
@@ -24,19 +28,26 @@ class ClipClassifier:
|
||||
self.model.to(self.device)
|
||||
self.model.eval()
|
||||
|
||||
def predict(self, image: Image.Image) -> ClipPredictionResult:
|
||||
inputs = self.processor(
|
||||
text=self.LABELS,
|
||||
images=image,
|
||||
return_tensors="pt",
|
||||
padding=True
|
||||
)
|
||||
inputs = {k: v.to(self.device) for k, v in inputs.items()}
|
||||
# Метки постоянные — токенизируем один раз. Заодно запросы не трогают
|
||||
# общий токенизатор, который не потокобезопасен.
|
||||
self.text_inputs = {
|
||||
key: value.to(self.device)
|
||||
for key, value in self.processor(
|
||||
text=self.LABELS,
|
||||
padding=True,
|
||||
return_tensors="pt"
|
||||
).items()
|
||||
}
|
||||
|
||||
with torch.no_grad():
|
||||
outputs = self.model(**inputs)
|
||||
logits = outputs.logits_per_image
|
||||
probs = logits.softmax(dim=1)[0]
|
||||
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 = []
|
||||
@@ -46,14 +57,16 @@ class ClipClassifier:
|
||||
score = float(probability)
|
||||
scores[label] = score
|
||||
|
||||
if label != "a normal photo" and score >= settings.CLIP_THRESHOLD:
|
||||
if label != self.NORMAL_LABEL and score >= settings.CLIP_THRESHOLD:
|
||||
detected_labels.append(label)
|
||||
|
||||
max_index = torch.argmax(probs).item()
|
||||
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
|
||||
)
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user