Create video_model.py
Browse files- video_model.py +37 -0
video_model.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from transformers import AutoModelForImageClassification, AutoFeatureExtractor
|
| 3 |
+
|
| 4 |
+
class DrowsinessModel:
|
| 5 |
+
def __init__(self, model_path, threshold=0.15):
|
| 6 |
+
# Инициализация модели и экстрактора признаков
|
| 7 |
+
self.model = AutoModelForImageClassification.from_pretrained('MonikaG7/fine-tuned_fatique_model')
|
| 8 |
+
self.feature_extractor = AutoFeatureExtractor.from_pretrained('MonikaG7/fine-tuned_fatique_model')
|
| 9 |
+
self.threshold = threshold
|
| 10 |
+
|
| 11 |
+
def predict(self, video_path):
|
| 12 |
+
"""
|
| 13 |
+
Анализирует видео, выводя 1 (усталость) или 0 (нет усталости)
|
| 14 |
+
"""
|
| 15 |
+
import cv2
|
| 16 |
+
cap = cv2.VideoCapture(video_path)
|
| 17 |
+
predictions = []
|
| 18 |
+
|
| 19 |
+
while cap.isOpened():
|
| 20 |
+
ret, frame = cap.read()
|
| 21 |
+
if not ret:
|
| 22 |
+
break
|
| 23 |
+
|
| 24 |
+
inputs = self.feature_extractor(images=[frame], return_tensors="pt")
|
| 25 |
+
with torch.no_grad():
|
| 26 |
+
outputs = self.model(**inputs)
|
| 27 |
+
pred = torch.argmax(outputs.logits, dim=1).item()
|
| 28 |
+
predictions.append(pred)
|
| 29 |
+
|
| 30 |
+
cap.release()
|
| 31 |
+
|
| 32 |
+
if not predictions:
|
| 33 |
+
return 0 # если видео пустое, возвращаем 0
|
| 34 |
+
|
| 35 |
+
# Рассчитываем drowsiness_ratio
|
| 36 |
+
drowsiness_ratio = sum(predictions) / len(predictions)
|
| 37 |
+
return 1 if drowsiness_ratio > self.threshold else 0
|