Spaces:
Runtime error
Runtime error
Upload 8 files
Browse files- anomaly_detection.py +88 -0
- face_analysis.py +40 -0
- main.py +152 -0
- pose_analysis.py +135 -0
- transcribe.py +84 -0
- utils.py +94 -0
- video_processing.py +347 -0
- visualization.py +177 -0
anomaly_detection.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.optim as optim
|
| 4 |
+
import numpy as np
|
| 5 |
+
from sklearn.preprocessing import MinMaxScaler
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Autoencoder(nn.Module):
|
| 9 |
+
def __init__(self, input_size):
|
| 10 |
+
super(Autoencoder, self).__init__()
|
| 11 |
+
self.encoder = nn.Sequential(
|
| 12 |
+
nn.Linear(input_size, 256),
|
| 13 |
+
nn.ReLU(),
|
| 14 |
+
nn.Linear(256, 128),
|
| 15 |
+
nn.ReLU(),
|
| 16 |
+
nn.Linear(128, 64),
|
| 17 |
+
nn.ReLU(),
|
| 18 |
+
nn.Linear(64, 32)
|
| 19 |
+
)
|
| 20 |
+
self.decoder = nn.Sequential(
|
| 21 |
+
nn.Linear(32, 64),
|
| 22 |
+
nn.ReLU(),
|
| 23 |
+
nn.Linear(64, 128),
|
| 24 |
+
nn.ReLU(),
|
| 25 |
+
nn.Linear(128, 256),
|
| 26 |
+
nn.ReLU(),
|
| 27 |
+
nn.Linear(256, input_size)
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
def forward(self, x):
|
| 31 |
+
batch_size, seq_len, _ = x.size()
|
| 32 |
+
x = x.view(batch_size * seq_len, -1)
|
| 33 |
+
encoded = self.encoder(x)
|
| 34 |
+
decoded = self.decoder(encoded)
|
| 35 |
+
return decoded.view(batch_size, seq_len, -1)
|
| 36 |
+
|
| 37 |
+
def anomaly_detection(X_embeddings, X_posture, epochs=200, patience=5):
|
| 38 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 39 |
+
|
| 40 |
+
# Normalize posture
|
| 41 |
+
scaler_posture = MinMaxScaler()
|
| 42 |
+
X_posture_scaled = scaler_posture.fit_transform(X_posture.reshape(-1, 1))
|
| 43 |
+
|
| 44 |
+
# Process facial embeddings
|
| 45 |
+
X_embeddings = torch.FloatTensor(X_embeddings).to(device)
|
| 46 |
+
if X_embeddings.dim() == 2:
|
| 47 |
+
X_embeddings = X_embeddings.unsqueeze(0)
|
| 48 |
+
|
| 49 |
+
# Process posture
|
| 50 |
+
X_posture_scaled = torch.FloatTensor(X_posture_scaled).to(device)
|
| 51 |
+
if X_posture_scaled.dim() == 2:
|
| 52 |
+
X_posture_scaled = X_posture_scaled.unsqueeze(0)
|
| 53 |
+
|
| 54 |
+
model_embeddings = Autoencoder(input_size=X_embeddings.shape[2]).to(device)
|
| 55 |
+
model_posture = Autoencoder(input_size=X_posture_scaled.shape[2]).to(device)
|
| 56 |
+
|
| 57 |
+
criterion = nn.MSELoss()
|
| 58 |
+
optimizer_embeddings = optim.Adam(model_embeddings.parameters())
|
| 59 |
+
optimizer_posture = optim.Adam(model_posture.parameters())
|
| 60 |
+
|
| 61 |
+
# Train models
|
| 62 |
+
for epoch in range(epochs):
|
| 63 |
+
for model, optimizer, X in [(model_embeddings, optimizer_embeddings, X_embeddings),
|
| 64 |
+
(model_posture, optimizer_posture, X_posture_scaled)]:
|
| 65 |
+
model.train()
|
| 66 |
+
optimizer.zero_grad()
|
| 67 |
+
output = model(X)
|
| 68 |
+
loss = criterion(output, X)
|
| 69 |
+
loss.backward()
|
| 70 |
+
optimizer.step()
|
| 71 |
+
|
| 72 |
+
# Compute MSE for embeddings and posture
|
| 73 |
+
model_embeddings.eval()
|
| 74 |
+
model_posture.eval()
|
| 75 |
+
with torch.no_grad():
|
| 76 |
+
reconstructed_embeddings = model_embeddings(X_embeddings).cpu().numpy()
|
| 77 |
+
reconstructed_posture = model_posture(X_posture_scaled).cpu().numpy()
|
| 78 |
+
|
| 79 |
+
mse_embeddings = np.mean(np.power(X_embeddings.cpu().numpy() - reconstructed_embeddings, 2), axis=2).squeeze()
|
| 80 |
+
mse_posture = np.mean(np.power(X_posture_scaled.cpu().numpy() - reconstructed_posture, 2), axis=2).squeeze()
|
| 81 |
+
|
| 82 |
+
return mse_embeddings, mse_posture
|
| 83 |
+
|
| 84 |
+
def determine_anomalies(mse_values, threshold):
|
| 85 |
+
mean = np.mean(mse_values)
|
| 86 |
+
std = np.std(mse_values)
|
| 87 |
+
anomalies = mse_values > (mean + threshold * std)
|
| 88 |
+
return anomalies
|
face_analysis.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import numpy as np
|
| 3 |
+
from facenet_pytorch import InceptionResnetV1
|
| 4 |
+
from sklearn.cluster import DBSCAN
|
| 5 |
+
import os
|
| 6 |
+
import shutil
|
| 7 |
+
|
| 8 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 9 |
+
model = InceptionResnetV1(pretrained='vggface2').eval().to(device)
|
| 10 |
+
|
| 11 |
+
def get_face_embedding(face_img):
|
| 12 |
+
face_tensor = torch.tensor(face_img).permute(2, 0, 1).unsqueeze(0).float() / 255
|
| 13 |
+
face_tensor = (face_tensor - 0.5) / 0.5
|
| 14 |
+
face_tensor = face_tensor.to(device)
|
| 15 |
+
with torch.no_grad():
|
| 16 |
+
embedding = model(face_tensor)
|
| 17 |
+
return embedding.cpu().numpy().flatten()
|
| 18 |
+
|
| 19 |
+
def cluster_faces(embeddings):
|
| 20 |
+
if len(embeddings) < 2:
|
| 21 |
+
print("Not enough faces for clustering. Assigning all to one cluster.")
|
| 22 |
+
return np.zeros(len(embeddings), dtype=int)
|
| 23 |
+
|
| 24 |
+
X = np.stack(embeddings)
|
| 25 |
+
dbscan = DBSCAN(eps=0.5, min_samples=5, metric='cosine')
|
| 26 |
+
clusters = dbscan.fit_predict(X)
|
| 27 |
+
|
| 28 |
+
if np.all(clusters == -1):
|
| 29 |
+
print("DBSCAN assigned all to noise. Considering as one cluster.")
|
| 30 |
+
return np.zeros(len(embeddings), dtype=int)
|
| 31 |
+
|
| 32 |
+
return clusters
|
| 33 |
+
|
| 34 |
+
def organize_faces_by_person(embeddings_by_frame, clusters, aligned_faces_folder, organized_faces_folder):
|
| 35 |
+
for (frame_num, embedding), cluster in zip(embeddings_by_frame.items(), clusters):
|
| 36 |
+
person_folder = os.path.join(organized_faces_folder, f"person_{cluster}")
|
| 37 |
+
os.makedirs(person_folder, exist_ok=True)
|
| 38 |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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import time
|
| 3 |
+
from video_processing import process_video
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import matplotlib
|
| 6 |
+
matplotlib.rcParams['figure.dpi'] = 500
|
| 7 |
+
matplotlib.rcParams['savefig.dpi'] = 500
|
| 8 |
+
|
| 9 |
+
def process_and_show_completion(video_input_path, anomaly_threshold_input, fps, progress=gr.Progress()):
|
| 10 |
+
try:
|
| 11 |
+
print("Starting video processing...")
|
| 12 |
+
results = process_video(video_input_path, anomaly_threshold_input, fps, progress=progress)
|
| 13 |
+
print("Video processing completed.")
|
| 14 |
+
|
| 15 |
+
if isinstance(results[0], str) and results[0].startswith("Error"):
|
| 16 |
+
print(f"Error occurred: {results[0]}")
|
| 17 |
+
return [results[0]] + [None] * 18
|
| 18 |
+
|
| 19 |
+
exec_time, results_summary, df, mse_embeddings, mse_posture, \
|
| 20 |
+
mse_plot_embeddings, mse_histogram_embeddings, \
|
| 21 |
+
mse_plot_posture, mse_histogram_posture, \
|
| 22 |
+
mse_heatmap_embeddings, mse_heatmap_posture, \
|
| 23 |
+
face_samples_frequent, face_samples_other, \
|
| 24 |
+
anomaly_faces_embeddings, anomaly_frames_posture_images, \
|
| 25 |
+
aligned_faces_folder, frames_folder, \
|
| 26 |
+
anomaly_sentences_features, anomaly_sentences_posture = results
|
| 27 |
+
|
| 28 |
+
anomaly_faces_embeddings_pil = [Image.fromarray(face) for face in anomaly_faces_embeddings]
|
| 29 |
+
anomaly_frames_posture_pil = [Image.fromarray(frame) for frame in anomaly_frames_posture_images]
|
| 30 |
+
|
| 31 |
+
face_samples_frequent = [Image.open(path) for path in face_samples_frequent]
|
| 32 |
+
face_samples_other = [Image.open(path) for path in face_samples_other]
|
| 33 |
+
|
| 34 |
+
anomaly_sentences_features, anomaly_sentences_posture = results[-2:]
|
| 35 |
+
|
| 36 |
+
# Format anomaly sentences output
|
| 37 |
+
sentences_features_output = format_anomaly_sentences(anomaly_sentences_features, "Facial Features")
|
| 38 |
+
sentences_posture_output = format_anomaly_sentences(anomaly_sentences_posture, "Body Posture")
|
| 39 |
+
|
| 40 |
+
output = [
|
| 41 |
+
exec_time, results_summary,
|
| 42 |
+
df, mse_embeddings, mse_posture,
|
| 43 |
+
mse_plot_embeddings, mse_plot_posture,
|
| 44 |
+
mse_histogram_embeddings, mse_histogram_posture,
|
| 45 |
+
mse_heatmap_embeddings, mse_heatmap_posture,
|
| 46 |
+
anomaly_faces_embeddings_pil, anomaly_frames_posture_pil,
|
| 47 |
+
face_samples_frequent, face_samples_other,
|
| 48 |
+
aligned_faces_folder, frames_folder,
|
| 49 |
+
mse_embeddings, mse_posture,
|
| 50 |
+
sentences_features_output, sentences_posture_output
|
| 51 |
+
]
|
| 52 |
+
|
| 53 |
+
return output
|
| 54 |
+
|
| 55 |
+
except Exception as e:
|
| 56 |
+
error_message = f"An error occurred: {str(e)}"
|
| 57 |
+
print(error_message)
|
| 58 |
+
import traceback
|
| 59 |
+
traceback.print_exc()
|
| 60 |
+
return [error_message] + [None] * 20
|
| 61 |
+
|
| 62 |
+
with gr.Blocks() as iface:
|
| 63 |
+
gr.Markdown("""
|
| 64 |
+
# Facial Expression and Body Language Anomaly Detection
|
| 65 |
+
|
| 66 |
+
This application analyzes videos to detect anomalies in facial features and body language.
|
| 67 |
+
It processes the video frames to extract facial embeddings and body posture,
|
| 68 |
+
then uses machine learning techniques to identify unusual patterns or deviations from the norm.
|
| 69 |
+
|
| 70 |
+
For more information, visit: [https://github.com/reab5555/Facial-Expression-Anomaly-Detection](https://github.com/reab5555/Facial-Expression-Anomaly-Detection)
|
| 71 |
+
""")
|
| 72 |
+
|
| 73 |
+
with gr.Row():
|
| 74 |
+
video_input = gr.Video()
|
| 75 |
+
|
| 76 |
+
anomaly_threshold = gr.Slider(minimum=1, maximum=5, step=0.1, value=3, label="Anomaly Detection Threshold")
|
| 77 |
+
fps_slider = gr.Slider(minimum=5, maximum=20, step=1, value=10, label="Frames Per Second")
|
| 78 |
+
process_btn = gr.Button("Detect Anomalies")
|
| 79 |
+
progress_bar = gr.Progress()
|
| 80 |
+
execution_time = gr.Number(label="Execution Time (seconds)")
|
| 81 |
+
|
| 82 |
+
with gr.Group(visible=False) as results_group:
|
| 83 |
+
results_text = gr.TextArea(label="Anomaly Detection Results", lines=4)
|
| 84 |
+
|
| 85 |
+
with gr.Tab("Facial Features"):
|
| 86 |
+
mse_features_plot = gr.Plot(label="MSE: Facial Features")
|
| 87 |
+
mse_features_hist = gr.Plot(label="MSE Distribution: Facial Features")
|
| 88 |
+
mse_features_heatmap = gr.Plot(label="MSE Heatmap: Facial Features")
|
| 89 |
+
anomaly_frames_features = gr.Gallery(label="Anomaly Frames (Facial Features)", columns=6, rows=2, height="auto")
|
| 90 |
+
|
| 91 |
+
with gr.Tab("Body Posture"):
|
| 92 |
+
mse_posture_plot = gr.Plot(label="MSE: Body Posture")
|
| 93 |
+
mse_posture_hist = gr.Plot(label="MSE Distribution: Body Posture")
|
| 94 |
+
mse_posture_heatmap = gr.Plot(label="MSE Heatmap: Body Posture")
|
| 95 |
+
anomaly_frames_posture = gr.Gallery(label="Anomaly Frames (Body Posture)", columns=6, rows=2, height="auto")
|
| 96 |
+
|
| 97 |
+
with gr.Tab("Sentences"):
|
| 98 |
+
with gr.Row():
|
| 99 |
+
anomaly_sentences_features_output = gr.Textbox(label="Sentences before Facial Feature Anomalies",
|
| 100 |
+
lines=10)
|
| 101 |
+
anomaly_frames_features = gr.Gallery(label="Anomaly Frames (Facial Features)", columns=6, rows=2,
|
| 102 |
+
height="auto")
|
| 103 |
+
|
| 104 |
+
with gr.Row():
|
| 105 |
+
anomaly_sentences_posture_output = gr.Textbox(label="Sentences before Body Posture Anomalies", lines=10)
|
| 106 |
+
anomaly_frames_posture = gr.Gallery(label="Anomaly Frames (Body Posture)", columns=6, rows=2,
|
| 107 |
+
height="auto")
|
| 108 |
+
|
| 109 |
+
with gr.Tab("Face Samples"):
|
| 110 |
+
face_samples_most_frequent = gr.Gallery(label="Most Frequent Person Samples (Target)", columns=6, rows=2, height="auto")
|
| 111 |
+
face_samples_others = gr.Gallery(label="Other Persons Samples", columns=6, rows=1, height="auto")
|
| 112 |
+
|
| 113 |
+
df_store = gr.State()
|
| 114 |
+
mse_features_store = gr.State()
|
| 115 |
+
mse_posture_store = gr.State()
|
| 116 |
+
aligned_faces_folder_store = gr.State()
|
| 117 |
+
frames_folder_store = gr.State()
|
| 118 |
+
mse_heatmap_embeddings_store = gr.State()
|
| 119 |
+
mse_heatmap_posture_store = gr.State()
|
| 120 |
+
|
| 121 |
+
def format_anomaly_sentences(anomaly_sentences, anomaly_type):
|
| 122 |
+
output = f"Sentences before {anomaly_type} Anomalies:\n\n"
|
| 123 |
+
for anomaly_timecode, sentences in anomaly_sentences:
|
| 124 |
+
output += f"Anomaly at {anomaly_timecode}:\n"
|
| 125 |
+
for sentence_timecode, sentence in sentences:
|
| 126 |
+
output += f" [{sentence_timecode}] {sentence}\n"
|
| 127 |
+
output += "\n"
|
| 128 |
+
return output
|
| 129 |
+
|
| 130 |
+
process_btn.click(
|
| 131 |
+
process_and_show_completion,
|
| 132 |
+
inputs=[video_input, anomaly_threshold, fps_slider],
|
| 133 |
+
outputs=[
|
| 134 |
+
execution_time, results_text, df_store,
|
| 135 |
+
mse_features_store, mse_posture_store,
|
| 136 |
+
mse_features_plot, mse_posture_plot,
|
| 137 |
+
mse_features_hist, mse_posture_hist,
|
| 138 |
+
mse_features_heatmap, mse_posture_heatmap,
|
| 139 |
+
anomaly_frames_features, anomaly_frames_posture,
|
| 140 |
+
face_samples_most_frequent, face_samples_others,
|
| 141 |
+
aligned_faces_folder_store, frames_folder_store,
|
| 142 |
+
mse_heatmap_embeddings_store, mse_heatmap_posture_store,
|
| 143 |
+
anomaly_sentences_features_output, anomaly_sentences_posture_output
|
| 144 |
+
]
|
| 145 |
+
).then(
|
| 146 |
+
lambda: gr.Group(visible=True),
|
| 147 |
+
input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6 |
+
mp_drawing = mp.solutions.drawing_utils
|
| 7 |
+
pose = mp_pose.Pose(static_image_mode=False, min_detection_confidence=0.7, min_tracking_confidence=0.7)
|
| 8 |
+
|
| 9 |
+
def calculate_posture_score(frame):
|
| 10 |
+
image_height, image_width, _ = frame.shape
|
| 11 |
+
results = pose.process(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
|
| 12 |
+
|
| 13 |
+
if not results.pose_landmarks:
|
| 14 |
+
return None, None
|
| 15 |
+
|
| 16 |
+
landmarks = results.pose_landmarks.landmark
|
| 17 |
+
|
| 18 |
+
# Use only body landmarks
|
| 19 |
+
left_shoulder = landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER.value]
|
| 20 |
+
right_shoulder = landmarks[mp_pose.PoseLandmark.RIGHT_SHOULDER.value]
|
| 21 |
+
left_hip = landmarks[mp_pose.PoseLandmark.LEFT_HIP.value]
|
| 22 |
+
right_hip = landmarks[mp_pose.PoseLandmark.RIGHT_HIP.value]
|
| 23 |
+
left_knee = landmarks[mp_pose.PoseLandmark.LEFT_KNEE.value]
|
| 24 |
+
right_knee = landmarks[mp_pose.PoseLandmark.RIGHT_KNEE.value]
|
| 25 |
+
|
| 26 |
+
# Calculate angles
|
| 27 |
+
shoulder_angle = abs(math.degrees(math.atan2(right_shoulder.y - left_shoulder.y, right_shoulder.x - left_shoulder.x)))
|
| 28 |
+
hip_angle = abs(math.degrees(math.atan2(right_hip.y - left_hip.y, right_hip.x - left_hip.x)))
|
| 29 |
+
knee_angle = abs(math.degrees(math.atan2(right_knee.y - left_knee.y, right_knee.x - left_knee.x)))
|
| 30 |
+
|
| 31 |
+
# Calculate vertical alignment
|
| 32 |
+
shoulder_hip_alignment = abs((left_shoulder.y + right_shoulder.y) / 2 - (left_hip.y + right_hip.y) / 2)
|
| 33 |
+
hip_knee_alignment = abs((left_hip.y + right_hip.y) / 2 - (left_knee.y + right_knee.y) / 2)
|
| 34 |
+
# Add head landmarks
|
| 35 |
+
nose = landmarks[mp_pose.PoseLandmark.NOSE.value]
|
| 36 |
+
left_ear = landmarks[mp_pose.PoseLandmark.LEFT_EAR.value]
|
| 37 |
+
right_ear = landmarks[mp_pose.PoseLandmark.RIGHT_EAR.value]
|
| 38 |
+
# Calculate head tilt
|
| 39 |
+
head_tilt = abs(math.degrees(math.atan2(right_ear.y - left_ear.y, right_ear.x - left_ear.x)))
|
| 40 |
+
# Calculate head position relative to shoulders
|
| 41 |
+
head_position = abs((nose.y - (left_shoulder.y + right_shoulder.y) / 2) /
|
| 42 |
+
((left_shoulder.y + right_shoulder.y) / 2 - (left_hip.y + right_hip.y) / 2))
|
| 43 |
+
|
| 44 |
+
# Combine metrics into a single posture score (you may need to adjust these weights)
|
| 45 |
+
posture_score = (
|
| 46 |
+
(1 - abs(shoulder_angle - hip_angle) / 90) * 0.3 +
|
| 47 |
+
(1 - abs(hip_angle - knee_angle) / 90) * 0.2 +
|
| 48 |
+
(1 - shoulder_hip_alignment) * 0.1 +
|
| 49 |
+
(1 - hip_knee_alignment) * 0.1 +
|
| 50 |
+
(1 - abs(head_tilt - 90) / 90) * 0.15 +
|
| 51 |
+
(1 - head_position) * 0.15
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
return posture_score, results.pose_landmarks
|
| 55 |
+
|
| 56 |
+
def draw_pose_landmarks(frame, landmarks):
|
| 57 |
+
annotated_frame = frame.copy()
|
| 58 |
+
# Include relevant landmarks for head position and body
|
| 59 |
+
body_landmarks = [
|
| 60 |
+
mp_pose.PoseLandmark.NOSE,
|
| 61 |
+
mp_pose.PoseLandmark.LEFT_SHOULDER,
|
| 62 |
+
mp_pose.PoseLandmark.RIGHT_SHOULDER,
|
| 63 |
+
mp_pose.PoseLandmark.LEFT_EAR,
|
| 64 |
+
mp_pose.PoseLandmark.RIGHT_EAR,
|
| 65 |
+
mp_pose.PoseLandmark.LEFT_ELBOW,
|
| 66 |
+
mp_pose.PoseLandmark.RIGHT_ELBOW,
|
| 67 |
+
mp_pose.PoseLandmark.LEFT_WRIST,
|
| 68 |
+
mp_pose.PoseLandmark.RIGHT_WRIST,
|
| 69 |
+
mp_pose.PoseLandmark.LEFT_HIP,
|
| 70 |
+
mp_pose.PoseLandmark.RIGHT_HIP,
|
| 71 |
+
mp_pose.PoseLandmark.LEFT_KNEE,
|
| 72 |
+
mp_pose.PoseLandmark.RIGHT_KNEE,
|
| 73 |
+
mp_pose.PoseLandmark.LEFT_ANKLE,
|
| 74 |
+
mp_pose.PoseLandmark.RIGHT_ANKLE
|
| 75 |
+
]
|
| 76 |
+
|
| 77 |
+
# Connections for head position and body
|
| 78 |
+
body_connections = [
|
| 79 |
+
(mp_pose.PoseLandmark.LEFT_EAR, mp_pose.PoseLandmark.LEFT_SHOULDER),
|
| 80 |
+
(mp_pose.PoseLandmark.RIGHT_EAR, mp_pose.PoseLandmark.RIGHT_SHOULDER),
|
| 81 |
+
(mp_pose.PoseLandmark.NOSE, mp_pose.PoseLandmark.LEFT_SHOULDER),
|
| 82 |
+
(mp_pose.PoseLandmark.NOSE, mp_pose.PoseLandmark.RIGHT_SHOULDER),
|
| 83 |
+
(mp_pose.PoseLandmark.LEFT_SHOULDER, mp_pose.PoseLandmark.RIGHT_SHOULDER),
|
| 84 |
+
(mp_pose.PoseLandmark.LEFT_SHOULDER, mp_pose.PoseLandmark.LEFT_ELBOW),
|
| 85 |
+
(mp_pose.PoseLandmark.RIGHT_SHOULDER, mp_pose.PoseLandmark.RIGHT_ELBOW),
|
| 86 |
+
(mp_pose.PoseLandmark.LEFT_ELBOW, mp_pose.PoseLandmark.LEFT_WRIST),
|
| 87 |
+
(mp_pose.PoseLandmark.RIGHT_ELBOW, mp_pose.PoseLandmark.RIGHT_WRIST),
|
| 88 |
+
(mp_pose.PoseLandmark.LEFT_SHOULDER, mp_pose.PoseLandmark.LEFT_HIP),
|
| 89 |
+
(mp_pose.PoseLandmark.RIGHT_SHOULDER, mp_pose.PoseLandmark.RIGHT_HIP),
|
| 90 |
+
(mp_pose.PoseLandmark.LEFT_HIP, mp_pose.PoseLandmark.RIGHT_HIP),
|
| 91 |
+
(mp_pose.PoseLandmark.LEFT_HIP, mp_pose.PoseLandmark.LEFT_KNEE),
|
| 92 |
+
(mp_pose.PoseLandmark.RIGHT_HIP, mp_pose.PoseLandmark.RIGHT_KNEE),
|
| 93 |
+
(mp_pose.PoseLandmark.LEFT_KNEE, mp_pose.PoseLandmark.LEFT_ANKLE),
|
| 94 |
+
(mp_pose.PoseLandmark.RIGHT_KNEE, mp_pose.PoseLandmark.RIGHT_ANKLE)
|
| 95 |
+
]
|
| 96 |
+
|
| 97 |
+
# Draw landmarks
|
| 98 |
+
for landmark in body_landmarks:
|
| 99 |
+
if landmark in landmarks.landmark:
|
| 100 |
+
lm = landmarks.landmark[landmark]
|
| 101 |
+
h, w, _ = annotated_frame.shape
|
| 102 |
+
cx, cy = int(lm.x * w), int(lm.y * h)
|
| 103 |
+
cv2.circle(annotated_frame, (cx, cy), 5, (245, 117, 66), -1)
|
| 104 |
+
|
| 105 |
+
# Draw connections
|
| 106 |
+
for connection in body_connections:
|
| 107 |
+
start_lm = landmarks.landmark[connection[0]]
|
| 108 |
+
end_lm = landmarks.landmark[connection[1]]
|
| 109 |
+
h, w, _ = annotated_frame.shape
|
| 110 |
+
start_point = (int(start_lm.x * w), int(start_lm.y * h))
|
| 111 |
+
end_point = (int(end_lm.x * w), int(end_lm.y * h))
|
| 112 |
+
cv2.line(annotated_frame, start_point, end_point, (245, 66, 230), 2)
|
| 113 |
+
|
| 114 |
+
# Highlight head tilt
|
| 115 |
+
left_ear = landmarks.landmark[mp_pose.PoseLandmark.LEFT_EAR]
|
| 116 |
+
right_ear = landmarks.landmark[mp_pose.PoseLandmark.RIGHT_EAR]
|
| 117 |
+
nose = landmarks.landmark[mp_pose.PoseLandmark.NOSE]
|
| 118 |
+
|
| 119 |
+
h, w, _ = annotated_frame.shape
|
| 120 |
+
left_ear_point = (int(left_ear.x * w), int(left_ear.y * h))
|
| 121 |
+
right_ear_point = (int(right_ear.x * w), int(right_ear.y * h))
|
| 122 |
+
nose_point = (int(nose.x * w), int(nose.y * h))
|
| 123 |
+
|
| 124 |
+
# Draw a line between ears to show head tilt
|
| 125 |
+
cv2.line(annotated_frame, left_ear_point, right_ear_point, (0, 255, 0), 2)
|
| 126 |
+
|
| 127 |
+
# Draw a line from nose to the midpoint between shoulders to show head forward/backward tilt
|
| 128 |
+
left_shoulder = landmarks.landmark[mp_pose.PoseLandmark.LEFT_SHOULDER]
|
| 129 |
+
right_shoulder = landmarks.landmark[mp_pose.PoseLandmark.RIGHT_SHOULDER]
|
| 130 |
+
shoulder_mid_x = (left_shoulder.x + right_shoulder.x) / 2
|
| 131 |
+
shoulder_mid_y = (left_shoulder.y + right_shoulder.y) / 2
|
| 132 |
+
shoulder_mid_point = (int(shoulder_mid_x * w), int(shoulder_mid_y * h))
|
| 133 |
+
cv2.line(annotated_frame, nose_point, shoulder_mid_point, (0, 255, 0), 2)
|
| 134 |
+
|
| 135 |
+
return annotated_frame
|
transcribe.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, WhisperFeatureExtractor
|
| 6 |
+
from moviepy.editor import VideoFileClip, AudioFileClip
|
| 7 |
+
import nltk
|
| 8 |
+
nltk.download('punkt', quiet=True)
|
| 9 |
+
from nltk.tokenize import sent_tokenize
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def transcribe(video_file, transcribe_to_text=True, transcribe_to_srt=True, target_language='en'):
|
| 13 |
+
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
| 14 |
+
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
|
| 15 |
+
|
| 16 |
+
model_id = "openai/whisper-large-v3"
|
| 17 |
+
model = AutoModelForSpeechSeq2Seq.from_pretrained(
|
| 18 |
+
model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, use_safetensors=True
|
| 19 |
+
)
|
| 20 |
+
model.to(device)
|
| 21 |
+
|
| 22 |
+
processor = AutoProcessor.from_pretrained(model_id)
|
| 23 |
+
feature_extractor = WhisperFeatureExtractor.from_pretrained(model_id)
|
| 24 |
+
|
| 25 |
+
video = VideoFileClip(video_file)
|
| 26 |
+
audio = video.audio
|
| 27 |
+
duration = audio.duration
|
| 28 |
+
chunk_duration = 60
|
| 29 |
+
n_chunks = int(np.ceil(duration / chunk_duration))
|
| 30 |
+
|
| 31 |
+
full_transcription = ""
|
| 32 |
+
for i in range(n_chunks):
|
| 33 |
+
start_time = i * chunk_duration
|
| 34 |
+
end_time = min((i + 1) * chunk_duration, duration)
|
| 35 |
+
|
| 36 |
+
audio_chunk = audio.subclip(start_time, end_time)
|
| 37 |
+
temp_file_path = f"temp_audio_chunk_{i}.wav"
|
| 38 |
+
audio_chunk.write_audiofile(temp_file_path, codec='pcm_s16le')
|
| 39 |
+
|
| 40 |
+
sound_array = AudioFileClip(temp_file_path).to_soundarray(fps=16000)
|
| 41 |
+
if sound_array.ndim > 1:
|
| 42 |
+
sound_array = np.mean(sound_array, axis=1)
|
| 43 |
+
|
| 44 |
+
input_features = feature_extractor(sound_array, sampling_rate=16000, return_tensors="pt").input_features
|
| 45 |
+
input_features = input_features.to(device=device, dtype=torch_dtype)
|
| 46 |
+
|
| 47 |
+
with torch.no_grad():
|
| 48 |
+
if target_language:
|
| 49 |
+
model.config.forced_decoder_ids = processor.get_decoder_prompt_ids(language=target_language,
|
| 50 |
+
task="transcribe")
|
| 51 |
+
generated_ids = model.generate(input_features, max_length=448)
|
| 52 |
+
transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 53 |
+
|
| 54 |
+
full_transcription += transcription + " "
|
| 55 |
+
os.remove(temp_file_path)
|
| 56 |
+
print(f"Processed chunk {i + 1}/{n_chunks}")
|
| 57 |
+
|
| 58 |
+
# Split the transcription into sentences
|
| 59 |
+
sentences = sent_tokenize(full_transcription.strip())
|
| 60 |
+
|
| 61 |
+
# Estimate time for each sentence based on its length relative to the total transcription
|
| 62 |
+
total_chars = sum(len(s) for s in sentences)
|
| 63 |
+
sentence_times = []
|
| 64 |
+
current_time = 0
|
| 65 |
+
for sentence in sentences:
|
| 66 |
+
sentence_duration = (len(sentence) / total_chars) * duration
|
| 67 |
+
sentence_times.append((current_time, current_time + sentence_duration))
|
| 68 |
+
current_time += sentence_duration
|
| 69 |
+
|
| 70 |
+
output = ""
|
| 71 |
+
if transcribe_to_text:
|
| 72 |
+
output += "Text Transcription:\n" + full_transcription + "\n\n"
|
| 73 |
+
|
| 74 |
+
if transcribe_to_srt:
|
| 75 |
+
output += "SRT Transcription:\n"
|
| 76 |
+
for i, (sentence, (start, end)) in enumerate(zip(sentences, sentence_times), 1):
|
| 77 |
+
output += f"{i}\n{format_time(start)} --> {format_time(end)}\n{sentence}\n\n"
|
| 78 |
+
|
| 79 |
+
return output
|
| 80 |
+
|
| 81 |
+
def format_time(seconds):
|
| 82 |
+
m, s = divmod(seconds, 60)
|
| 83 |
+
h, m = divmod(m, 60)
|
| 84 |
+
return f"{int(h):02d}:{int(m):02d}:{s:06.3f}".replace('.', ',')
|
utils.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from nltk import sent_tokenize
|
| 2 |
+
from transcribe import format_time
|
| 3 |
+
|
| 4 |
+
def frame_to_timecode(frame_num, total_frames, duration):
|
| 5 |
+
total_seconds = (frame_num / total_frames) * duration
|
| 6 |
+
hours = int(total_seconds // 3600)
|
| 7 |
+
minutes = int((total_seconds % 3600) // 60)
|
| 8 |
+
seconds = int(total_seconds % 60)
|
| 9 |
+
milliseconds = int((total_seconds - int(total_seconds)) * 1000)
|
| 10 |
+
return f"{hours:02d}:{minutes:02d}:{seconds:02d}.{milliseconds:03d}"
|
| 11 |
+
|
| 12 |
+
def seconds_to_timecode(seconds):
|
| 13 |
+
hours = int(seconds // 3600)
|
| 14 |
+
minutes = int((seconds % 3600) // 60)
|
| 15 |
+
seconds = int(seconds % 60)
|
| 16 |
+
return f"{hours:02d}:{minutes:02d}:{seconds:02d}"
|
| 17 |
+
|
| 18 |
+
def timecode_to_seconds(timecode):
|
| 19 |
+
h, m, s = map(int, timecode.split(':'))
|
| 20 |
+
return h * 3600 + m * 60 + s
|
| 21 |
+
|
| 22 |
+
def add_timecode_to_image(image, timecode):
|
| 23 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 24 |
+
import numpy as np
|
| 25 |
+
|
| 26 |
+
img_pil = Image.fromarray(image)
|
| 27 |
+
draw = ImageDraw.Draw(img_pil)
|
| 28 |
+
font = ImageFont.truetype("arial.ttf", 15)
|
| 29 |
+
draw.text((10, 10), timecode, (255, 0, 0), font=font)
|
| 30 |
+
return np.array(img_pil)
|
| 31 |
+
|
| 32 |
+
def flexible_timecode_to_seconds(timecode):
|
| 33 |
+
try:
|
| 34 |
+
if ',' in timecode:
|
| 35 |
+
h, m, s = timecode.replace(',', '.').split(':')
|
| 36 |
+
else:
|
| 37 |
+
h, m, s = timecode.split(':')
|
| 38 |
+
return int(float(h)) * 3600 + int(float(m)) * 60 + float(s)
|
| 39 |
+
except ValueError:
|
| 40 |
+
print(f"Invalid timecode format: {timecode}")
|
| 41 |
+
return 0
|
| 42 |
+
|
| 43 |
+
def add_timecode_to_image_body(image, timecode):
|
| 44 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 45 |
+
import numpy as np
|
| 46 |
+
|
| 47 |
+
img_pil = Image.fromarray(image)
|
| 48 |
+
draw = ImageDraw.Draw(img_pil)
|
| 49 |
+
font = ImageFont.truetype("arial.ttf", 100)
|
| 50 |
+
draw.text((10, 10), timecode, (255, 0, 0), font=font)
|
| 51 |
+
return np.array(img_pil)
|
| 52 |
+
|
| 53 |
+
def parse_transcription(transcription_output, video_duration):
|
| 54 |
+
# Remove the "Text Transcription:" prefix if it exists
|
| 55 |
+
if transcription_output.startswith("Text Transcription:"):
|
| 56 |
+
transcription_output = transcription_output.split("Text Transcription:", 1)[1].strip()
|
| 57 |
+
|
| 58 |
+
sentences = sent_tokenize(transcription_output)
|
| 59 |
+
total_chars = sum(len(s) for s in sentences)
|
| 60 |
+
sentences_with_timecodes = []
|
| 61 |
+
current_time = 0
|
| 62 |
+
|
| 63 |
+
for sentence in sentences:
|
| 64 |
+
sentence_duration = (len(sentence) / total_chars) * video_duration
|
| 65 |
+
end_time = current_time + sentence_duration
|
| 66 |
+
timecode = format_time(current_time)
|
| 67 |
+
sentences_with_timecodes.append((timecode, sentence))
|
| 68 |
+
current_time = end_time
|
| 69 |
+
|
| 70 |
+
return sentences_with_timecodes
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def get_sentences_before_anomalies(sentences_with_timecodes, anomaly_timecodes, time_threshold=5):
|
| 74 |
+
anomaly_sentences = {}
|
| 75 |
+
for anomaly_timecode in anomaly_timecodes:
|
| 76 |
+
try:
|
| 77 |
+
anomaly_time = flexible_timecode_to_seconds(anomaly_timecode)
|
| 78 |
+
relevant_sentences = [
|
| 79 |
+
(timecode, sentence) for timecode, sentence in sentences_with_timecodes
|
| 80 |
+
if 0 <= anomaly_time - flexible_timecode_to_seconds(timecode) <= time_threshold
|
| 81 |
+
]
|
| 82 |
+
if relevant_sentences:
|
| 83 |
+
# Use the sentences as the key to avoid duplicates
|
| 84 |
+
key = tuple((timecode, sentence) for timecode, sentence in relevant_sentences)
|
| 85 |
+
if key not in anomaly_sentences:
|
| 86 |
+
anomaly_sentences[key] = anomaly_timecode
|
| 87 |
+
except Exception as e:
|
| 88 |
+
print(f"Error processing anomaly timecode {anomaly_timecode}: {str(e)}")
|
| 89 |
+
continue
|
| 90 |
+
return [(timecode, list(sentences)) for sentences, timecode in anomaly_sentences.items()]
|
| 91 |
+
|
| 92 |
+
def timecode_to_seconds(timecode):
|
| 93 |
+
h, m, s = map(float, timecode.split(':'))
|
| 94 |
+
return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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import cv2
|
| 3 |
+
import numpy as np
|
| 4 |
+
from moviepy.editor import VideoFileClip
|
| 5 |
+
import tempfile
|
| 6 |
+
import time
|
| 7 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 8 |
+
import math
|
| 9 |
+
from face_analysis import get_face_embedding, cluster_faces, organize_faces_by_person
|
| 10 |
+
from pose_analysis import calculate_posture_score, draw_pose_landmarks
|
| 11 |
+
from anomaly_detection import anomaly_detection
|
| 12 |
+
from visualization import plot_mse, plot_mse_histogram, plot_mse_heatmap
|
| 13 |
+
from utils import frame_to_timecode, parse_transcription, get_sentences_before_anomalies
|
| 14 |
+
from transcribe import transcribe
|
| 15 |
+
import pandas as pd
|
| 16 |
+
from facenet_pytorch import MTCNN
|
| 17 |
+
import torch
|
| 18 |
+
import mediapipe as mp
|
| 19 |
+
|
| 20 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 21 |
+
mtcnn = MTCNN(keep_all=False, device=device, thresholds=[0.95, 0.95, 0.95], min_face_size=80)
|
| 22 |
+
|
| 23 |
+
mp_face_mesh = mp.solutions.face_mesh
|
| 24 |
+
face_mesh = mp_face_mesh.FaceMesh(static_image_mode=False, max_num_faces=1, min_detection_confidence=0.7)
|
| 25 |
+
|
| 26 |
+
mp_pose = mp.solutions.pose
|
| 27 |
+
pose = mp_pose.Pose(static_image_mode=False, min_detection_confidence=0.7, min_tracking_confidence=0.7)
|
| 28 |
+
|
| 29 |
+
def extract_frames(video_path, output_folder, desired_fps, progress_callback=None):
|
| 30 |
+
os.makedirs(output_folder, exist_ok=True)
|
| 31 |
+
clip = VideoFileClip(video_path)
|
| 32 |
+
original_fps = clip.fps
|
| 33 |
+
duration = clip.duration
|
| 34 |
+
total_frames = int(duration * original_fps)
|
| 35 |
+
step = max(1, original_fps / desired_fps)
|
| 36 |
+
total_frames_to_extract = int(total_frames / step)
|
| 37 |
+
|
| 38 |
+
frame_count = 0
|
| 39 |
+
for t in np.arange(0, duration, step / original_fps):
|
| 40 |
+
frame = clip.get_frame(t)
|
| 41 |
+
cv2.imwrite(os.path.join(output_folder, f"frame_{frame_count:04d}.jpg"), cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
|
| 42 |
+
frame_count += 1
|
| 43 |
+
if progress_callback:
|
| 44 |
+
progress = min(100, (frame_count / total_frames_to_extract) * 100)
|
| 45 |
+
progress_callback(progress, f"Extracting frame")
|
| 46 |
+
if frame_count >= total_frames_to_extract:
|
| 47 |
+
break
|
| 48 |
+
clip.close()
|
| 49 |
+
return frame_count, original_fps
|
| 50 |
+
|
| 51 |
+
def process_frames(frames_folder, aligned_faces_folder, frame_count, progress):
|
| 52 |
+
embeddings_by_frame = {}
|
| 53 |
+
posture_scores_by_frame = {}
|
| 54 |
+
posture_landmarks_by_frame = {}
|
| 55 |
+
aligned_face_paths = []
|
| 56 |
+
frame_files = sorted([f for f in os.listdir(frames_folder) if f.endswith('.jpg')])
|
| 57 |
+
|
| 58 |
+
for i, frame_file in enumerate(frame_files):
|
| 59 |
+
frame_num = int(frame_file.split('_')[1].split('.')[0])
|
| 60 |
+
frame_path = os.path.join(frames_folder, frame_file)
|
| 61 |
+
frame = cv2.imread(frame_path)
|
| 62 |
+
|
| 63 |
+
if frame is not None:
|
| 64 |
+
posture_score, posture_landmarks = calculate_posture_score(frame)
|
| 65 |
+
posture_scores_by_frame[frame_num] = posture_score
|
| 66 |
+
posture_landmarks_by_frame[frame_num] = posture_landmarks
|
| 67 |
+
|
| 68 |
+
boxes, probs = mtcnn.detect(frame)
|
| 69 |
+
|
| 70 |
+
if boxes is not None and len(boxes) > 0 and probs[0] >= 0.99:
|
| 71 |
+
x1, y1, x2, y2 = [int(b) for b in boxes[0]]
|
| 72 |
+
face = frame[y1:y2, x1:x2]
|
| 73 |
+
if face.size > 0:
|
| 74 |
+
results = face_mesh.process(cv2.cvtColor(face, cv2.COLOR_BGR2RGB))
|
| 75 |
+
if results.multi_face_landmarks and is_frontal_face(results.multi_face_landmarks[0].landmark):
|
| 76 |
+
aligned_face = face
|
| 77 |
+
|
| 78 |
+
if aligned_face is not None:
|
| 79 |
+
aligned_face_resized = cv2.resize(aligned_face, (160, 160))
|
| 80 |
+
output_path = os.path.join(aligned_faces_folder, f"frame_{frame_num}_face.jpg")
|
| 81 |
+
cv2.imwrite(output_path, aligned_face_resized)
|
| 82 |
+
aligned_face_paths.append(output_path)
|
| 83 |
+
embedding = get_face_embedding(aligned_face_resized)
|
| 84 |
+
embeddings_by_frame[frame_num] = embedding
|
| 85 |
+
|
| 86 |
+
progress((i + 1) / len(frame_files), f"Processing frame {i + 1} of {len(frame_files)}")
|
| 87 |
+
|
| 88 |
+
return embeddings_by_frame, posture_scores_by_frame, posture_landmarks_by_frame, aligned_face_paths
|
| 89 |
+
|
| 90 |
+
def process_video(video_path, anomaly_threshold, desired_fps, progress=None):
|
| 91 |
+
start_time = time.time()
|
| 92 |
+
output_folder = "output"
|
| 93 |
+
os.makedirs(output_folder, exist_ok=True)
|
| 94 |
+
|
| 95 |
+
GRAPH_COLORS = {
|
| 96 |
+
'facial_embeddings': 'navy',
|
| 97 |
+
'body_posture': 'purple'
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
with tempfile.TemporaryDirectory() as temp_dir:
|
| 101 |
+
aligned_faces_folder = os.path.join(temp_dir, 'aligned_faces')
|
| 102 |
+
organized_faces_folder = os.path.join(temp_dir, 'organized_faces')
|
| 103 |
+
os.makedirs(aligned_faces_folder, exist_ok=True)
|
| 104 |
+
os.makedirs(organized_faces_folder, exist_ok=True)
|
| 105 |
+
|
| 106 |
+
clip = VideoFileClip(video_path)
|
| 107 |
+
video_duration = clip.duration
|
| 108 |
+
clip.close()
|
| 109 |
+
|
| 110 |
+
progress(0, "Starting frame extraction")
|
| 111 |
+
frames_folder = os.path.join(temp_dir, 'extracted_frames')
|
| 112 |
+
|
| 113 |
+
def extraction_progress(percent, message):
|
| 114 |
+
progress(percent / 100, f"Extracting frames")
|
| 115 |
+
|
| 116 |
+
frame_count, original_fps = extract_frames(video_path, frames_folder, desired_fps, extraction_progress)
|
| 117 |
+
|
| 118 |
+
progress(1, "Frame extraction complete")
|
| 119 |
+
progress(0.3, "Processing frames")
|
| 120 |
+
embeddings_by_frame, posture_scores_by_frame, posture_landmarks_by_frame, aligned_face_paths = process_frames(
|
| 121 |
+
frames_folder, aligned_faces_folder,
|
| 122 |
+
frame_count,
|
| 123 |
+
progress)
|
| 124 |
+
|
| 125 |
+
if not aligned_face_paths:
|
| 126 |
+
raise ValueError("No faces were extracted from the video.")
|
| 127 |
+
|
| 128 |
+
progress(0.6, "Clustering faces")
|
| 129 |
+
embeddings = [embedding for _, embedding in embeddings_by_frame.items()]
|
| 130 |
+
clusters = cluster_faces(embeddings)
|
| 131 |
+
num_clusters = len(set(clusters))
|
| 132 |
+
|
| 133 |
+
progress(0.7, "Organizing faces")
|
| 134 |
+
organize_faces_by_person(embeddings_by_frame, clusters, aligned_faces_folder, organized_faces_folder)
|
| 135 |
+
|
| 136 |
+
progress(0.8, "Saving person data")
|
| 137 |
+
df, largest_cluster = save_person_data_to_csv(embeddings_by_frame, clusters, desired_fps,
|
| 138 |
+
original_fps, temp_dir, video_duration)
|
| 139 |
+
|
| 140 |
+
df['Seconds'] = df['Timecode'].apply(
|
| 141 |
+
lambda x: sum(float(t) * 60 ** i for i, t in enumerate(reversed(x.split(':')))))
|
| 142 |
+
|
| 143 |
+
progress(0.85, "Getting face samples")
|
| 144 |
+
face_samples = get_all_face_samples(organized_faces_folder, output_folder, largest_cluster)
|
| 145 |
+
|
| 146 |
+
progress(0.9, "Performing anomaly detection")
|
| 147 |
+
embedding_columns = [col for col in df.columns if col.startswith('Raw_Embedding_')]
|
| 148 |
+
|
| 149 |
+
X_embeddings = df[embedding_columns].values
|
| 150 |
+
|
| 151 |
+
try:
|
| 152 |
+
X_posture = np.array([posture_scores_by_frame.get(frame, None) for frame in df['Frame']])
|
| 153 |
+
X_posture = X_posture[X_posture != None].reshape(-1, 1)
|
| 154 |
+
|
| 155 |
+
if len(X_posture) == 0:
|
| 156 |
+
raise ValueError("No valid posture data found")
|
| 157 |
+
|
| 158 |
+
mse_embeddings, mse_posture = anomaly_detection(X_embeddings, X_posture)
|
| 159 |
+
|
| 160 |
+
progress(0.95, "Generating plots")
|
| 161 |
+
mse_plot_embeddings, anomaly_frames_embeddings = plot_mse(df, mse_embeddings, "Facial Features",
|
| 162 |
+
color=GRAPH_COLORS['facial_embeddings'],
|
| 163 |
+
anomaly_threshold=anomaly_threshold)
|
| 164 |
+
|
| 165 |
+
mse_histogram_embeddings = plot_mse_histogram(mse_embeddings, "MSE Distribution: Facial Features",
|
| 166 |
+
anomaly_threshold, color=GRAPH_COLORS['facial_embeddings'])
|
| 167 |
+
|
| 168 |
+
mse_plot_posture, anomaly_frames_posture = plot_mse(df, mse_posture, "Body Posture",
|
| 169 |
+
color=GRAPH_COLORS['body_posture'],
|
| 170 |
+
anomaly_threshold=anomaly_threshold)
|
| 171 |
+
|
| 172 |
+
mse_histogram_posture = plot_mse_histogram(mse_posture, "MSE Distribution: Body Posture",
|
| 173 |
+
anomaly_threshold, color=GRAPH_COLORS['body_posture'])
|
| 174 |
+
|
| 175 |
+
mse_heatmap_posture = plot_mse_heatmap(mse_posture, "Body Posture MSE Heatmap", df)
|
| 176 |
+
|
| 177 |
+
mse_heatmap_embeddings = plot_mse_heatmap(mse_embeddings, "Facial Features MSE Heatmap", df)
|
| 178 |
+
|
| 179 |
+
except Exception as e:
|
| 180 |
+
print(f"Error details: {str(e)}")
|
| 181 |
+
import traceback
|
| 182 |
+
traceback.print_exc()
|
| 183 |
+
return (f"Error in video processing: {str(e)}",) + (None,) * 14
|
| 184 |
+
|
| 185 |
+
# Add transcription
|
| 186 |
+
progress(0.96, "Transcribing video")
|
| 187 |
+
transcription_output = transcribe(video_path, transcribe_to_text=True, transcribe_to_srt=False,
|
| 188 |
+
target_language='en')
|
| 189 |
+
|
| 190 |
+
# Parse the transcription output to get sentences and their timecodes
|
| 191 |
+
sentences_with_timecodes = parse_transcription(transcription_output, video_duration)
|
| 192 |
+
|
| 193 |
+
# Get anomaly timecodes
|
| 194 |
+
anomaly_timecodes_features = [df[df['Frame'] == frame]['Timecode'].iloc[0] for frame in
|
| 195 |
+
anomaly_frames_embeddings]
|
| 196 |
+
anomaly_timecodes_posture = [df[df['Frame'] == frame]['Timecode'].iloc[0] for frame in anomaly_frames_posture]
|
| 197 |
+
|
| 198 |
+
anomaly_sentences_features = get_sentences_before_anomalies(sentences_with_timecodes,
|
| 199 |
+
anomaly_timecodes_features)
|
| 200 |
+
anomaly_sentences_posture = get_sentences_before_anomalies(sentences_with_timecodes,
|
| 201 |
+
anomaly_timecodes_posture)
|
| 202 |
+
progress(1.0, "Preparing results")
|
| 203 |
+
results = f"Number of persons detected: {num_clusters}\n\n"
|
| 204 |
+
results += "Breakdown:\n"
|
| 205 |
+
for cluster_id in range(num_clusters):
|
| 206 |
+
face_count = len([c for c in clusters if c == cluster_id])
|
| 207 |
+
results += f"Person {cluster_id + 1}: {face_count} face frames\n"
|
| 208 |
+
|
| 209 |
+
end_time = time.time()
|
| 210 |
+
execution_time = end_time - start_time
|
| 211 |
+
|
| 212 |
+
def add_timecode_to_image(image, timecode):
|
| 213 |
+
img_pil = Image.fromarray(image)
|
| 214 |
+
draw = ImageDraw.Draw(img_pil)
|
| 215 |
+
font = ImageFont.truetype("arial.ttf", 15)
|
| 216 |
+
draw.text((10, 10), timecode, (255, 0, 0), font=font)
|
| 217 |
+
return np.array(img_pil)
|
| 218 |
+
|
| 219 |
+
anomaly_faces_embeddings = []
|
| 220 |
+
for frame in anomaly_frames_embeddings:
|
| 221 |
+
face_path = os.path.join(aligned_faces_folder, f"frame_{frame}_face.jpg")
|
| 222 |
+
if os.path.exists(face_path):
|
| 223 |
+
face_img = cv2.imread(face_path)
|
| 224 |
+
if face_img is not None:
|
| 225 |
+
face_img = cv2.cvtColor(face_img, cv2.COLOR_BGR2RGB)
|
| 226 |
+
timecode = df[df['Frame'] == frame]['Timecode'].iloc[0]
|
| 227 |
+
face_img_with_timecode = add_timecode_to_image(face_img, timecode)
|
| 228 |
+
anomaly_faces_embeddings.append(face_img_with_timecode)
|
| 229 |
+
|
| 230 |
+
anomaly_frames_posture_images = []
|
| 231 |
+
for frame in anomaly_frames_posture:
|
| 232 |
+
frame_path = os.path.join(frames_folder, f"frame_{frame:04d}.jpg")
|
| 233 |
+
if os.path.exists(frame_path):
|
| 234 |
+
frame_img = cv2.imread(frame_path)
|
| 235 |
+
if frame_img is not None:
|
| 236 |
+
frame_img = cv2.cvtColor(frame_img, cv2.COLOR_BGR2RGB)
|
| 237 |
+
pose_results = pose.process(frame_img)
|
| 238 |
+
if pose_results.pose_landmarks:
|
| 239 |
+
frame_img = draw_pose_landmarks(frame_img, pose_results.pose_landmarks)
|
| 240 |
+
timecode = df[df['Frame'] == frame]['Timecode'].iloc[0]
|
| 241 |
+
frame_img_with_timecode = add_timecode_to_image(frame_img, timecode)
|
| 242 |
+
anomaly_frames_posture_images.append(frame_img_with_timecode)
|
| 243 |
+
|
| 244 |
+
return (
|
| 245 |
+
execution_time,
|
| 246 |
+
results,
|
| 247 |
+
df,
|
| 248 |
+
mse_embeddings,
|
| 249 |
+
mse_posture,
|
| 250 |
+
mse_plot_embeddings,
|
| 251 |
+
mse_histogram_embeddings,
|
| 252 |
+
mse_plot_posture,
|
| 253 |
+
mse_histogram_posture,
|
| 254 |
+
mse_heatmap_embeddings,
|
| 255 |
+
mse_heatmap_posture,
|
| 256 |
+
face_samples["most_frequent"],
|
| 257 |
+
face_samples["others"],
|
| 258 |
+
anomaly_faces_embeddings,
|
| 259 |
+
anomaly_frames_posture_images,
|
| 260 |
+
aligned_faces_folder,
|
| 261 |
+
frames_folder,
|
| 262 |
+
anomaly_sentences_features,
|
| 263 |
+
anomaly_sentences_posture
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
def is_frontal_face(landmarks, threshold=40):
|
| 267 |
+
nose_tip = landmarks[4]
|
| 268 |
+
left_chin = landmarks[234]
|
| 269 |
+
right_chin = landmarks[454]
|
| 270 |
+
nose_to_left = [left_chin.x - nose_tip.x, left_chin.y - nose_tip.y]
|
| 271 |
+
nose_to_right = [right_chin.x - nose_tip.x, right_chin.y - nose_tip.y]
|
| 272 |
+
dot_product = nose_to_left[0] * nose_to_right[0] + nose_to_left[1] * nose_to_right[1]
|
| 273 |
+
magnitude_left = math.sqrt(nose_to_left[0] ** 2 + nose_to_left[1] ** 2)
|
| 274 |
+
magnitude_right = math.sqrt(nose_to_right[0] ** 2 + nose_to_right[1] ** 2)
|
| 275 |
+
cos_angle = dot_product / (magnitude_left * magnitude_right)
|
| 276 |
+
angle = math.acos(cos_angle)
|
| 277 |
+
angle_degrees = math.degrees(angle)
|
| 278 |
+
return abs(180 - angle_degrees) < threshold
|
| 279 |
+
|
| 280 |
+
def save_person_data_to_csv(embeddings_by_frame, clusters, desired_fps, original_fps, output_folder, video_duration):
|
| 281 |
+
person_data = {}
|
| 282 |
+
|
| 283 |
+
for (frame_num, embedding), cluster in zip(embeddings_by_frame.items(), clusters):
|
| 284 |
+
if cluster not in person_data:
|
| 285 |
+
person_data[cluster] = []
|
| 286 |
+
person_data[cluster].append((frame_num, embedding))
|
| 287 |
+
|
| 288 |
+
largest_cluster = max(person_data, key=lambda k: len(person_data[k]))
|
| 289 |
+
|
| 290 |
+
data = person_data[largest_cluster]
|
| 291 |
+
data.sort(key=lambda x: x[0])
|
| 292 |
+
frames, embeddings = zip(*data)
|
| 293 |
+
|
| 294 |
+
embeddings_array = np.array(embeddings)
|
| 295 |
+
np.save(os.path.join(output_folder, 'face_embeddings.npy'), embeddings_array)
|
| 296 |
+
|
| 297 |
+
total_frames = max(frames)
|
| 298 |
+
timecodes = [frame_to_timecode(frame, total_frames, video_duration) for frame in frames]
|
| 299 |
+
|
| 300 |
+
df_data = {
|
| 301 |
+
'Frame': frames,
|
| 302 |
+
'Timecode': timecodes,
|
| 303 |
+
'Embedding_Index': range(len(embeddings))
|
| 304 |
+
}
|
| 305 |
+
|
| 306 |
+
for i in range(len(embeddings[0])):
|
| 307 |
+
df_data[f'Raw_Embedding_{i}'] = [embedding[i] for embedding in embeddings]
|
| 308 |
+
|
| 309 |
+
df = pd.DataFrame(df_data)
|
| 310 |
+
|
| 311 |
+
return df, largest_cluster
|
| 312 |
+
|
| 313 |
+
def get_all_face_samples(organized_faces_folder, output_folder, largest_cluster, max_samples=100):
|
| 314 |
+
face_samples = {"most_frequent": [], "others": []}
|
| 315 |
+
for cluster_folder in sorted(os.listdir(organized_faces_folder)):
|
| 316 |
+
if cluster_folder.startswith("person_"):
|
| 317 |
+
person_folder = os.path.join(organized_faces_folder, cluster_folder)
|
| 318 |
+
face_files = sorted([f for f in os.listdir(person_folder) if f.endswith('.jpg')])
|
| 319 |
+
if face_files:
|
| 320 |
+
cluster_id = int(cluster_folder.split('_')[1])
|
| 321 |
+
if cluster_id == largest_cluster:
|
| 322 |
+
for i, sample in enumerate(face_files[:max_samples]):
|
| 323 |
+
face_path = os.path.join(person_folder, sample)
|
| 324 |
+
output_path = os.path.join(output_folder, f"face_sample_most_frequent_{i:04d}.jpg")
|
| 325 |
+
face_img = cv2.imread(face_path)
|
| 326 |
+
if face_img is not None:
|
| 327 |
+
small_face = cv2.resize(face_img, (160, 160))
|
| 328 |
+
cv2.imwrite(output_path, small_face)
|
| 329 |
+
face_samples["most_frequent"].append(output_path)
|
| 330 |
+
if len(face_samples["most_frequent"]) >= max_samples:
|
| 331 |
+
break
|
| 332 |
+
else:
|
| 333 |
+
remaining_samples = max_samples - len(face_samples["others"])
|
| 334 |
+
if remaining_samples > 0:
|
| 335 |
+
for i, sample in enumerate(face_files[:remaining_samples]):
|
| 336 |
+
face_path = os.path.join(person_folder, sample)
|
| 337 |
+
output_path = os.path.join(output_folder, f"face_sample_other_{cluster_id:02d}_{i:04d}.jpg")
|
| 338 |
+
face_img = cv2.imread(face_path)
|
| 339 |
+
if face_img is not None:
|
| 340 |
+
small_face = cv2.resize(face_img, (160, 160))
|
| 341 |
+
cv2.imwrite(output_path, small_face)
|
| 342 |
+
face_samples["others"].append(output_path)
|
| 343 |
+
if len(face_samples["others"]) >= max_samples:
|
| 344 |
+
break
|
| 345 |
+
return face_samples
|
| 346 |
+
|
| 347 |
+
|
visualization.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import matplotlib.pyplot as plt
|
| 2 |
+
import seaborn as sns
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from matplotlib.patches import Rectangle
|
| 6 |
+
from utils import seconds_to_timecode
|
| 7 |
+
from anomaly_detection import determine_anomalies
|
| 8 |
+
|
| 9 |
+
def plot_mse(df, mse_values, title, color='navy', time_threshold=3, anomaly_threshold=4):
|
| 10 |
+
plt.figure(figsize=(16, 8), dpi=400)
|
| 11 |
+
fig, ax = plt.subplots(figsize=(16, 8))
|
| 12 |
+
|
| 13 |
+
if 'Seconds' not in df.columns:
|
| 14 |
+
df['Seconds'] = df['Timecode'].apply(
|
| 15 |
+
lambda x: sum(float(t) * 60 ** i for i, t in enumerate(reversed(x.split(':')))))
|
| 16 |
+
|
| 17 |
+
# Ensure df and mse_values have the same length and remove NaN values
|
| 18 |
+
min_length = min(len(df), len(mse_values))
|
| 19 |
+
df = df.iloc[:min_length]
|
| 20 |
+
mse_values = mse_values[:min_length]
|
| 21 |
+
|
| 22 |
+
# Remove NaN values
|
| 23 |
+
mask = ~np.isnan(mse_values)
|
| 24 |
+
df = df[mask]
|
| 25 |
+
mse_values = mse_values[mask]
|
| 26 |
+
|
| 27 |
+
mean = pd.Series(mse_values).rolling(window=10).mean()
|
| 28 |
+
std = pd.Series(mse_values).rolling(window=10).std()
|
| 29 |
+
median = np.median(mse_values)
|
| 30 |
+
|
| 31 |
+
ax.scatter(df['Seconds'], mse_values, color=color, alpha=0.3, s=5)
|
| 32 |
+
ax.plot(df['Seconds'], mean, color=color, linewidth=0.5)
|
| 33 |
+
ax.fill_between(df['Seconds'], mean - std, mean + std, color=color, alpha=0.1)
|
| 34 |
+
|
| 35 |
+
# Add median line
|
| 36 |
+
ax.axhline(y=median, color='black', linestyle='--', label='Median Baseline')
|
| 37 |
+
|
| 38 |
+
# Add threshold line
|
| 39 |
+
threshold = np.mean(mse_values) + anomaly_threshold * np.std(mse_values)
|
| 40 |
+
ax.axhline(y=threshold, color='red', linestyle='--', label=f'Threshold: {anomaly_threshold:.1f}')
|
| 41 |
+
ax.text(ax.get_xlim()[1], threshold, f'Threshold: {anomaly_threshold:.1f}', verticalalignment='center', horizontalalignment='left', color='red')
|
| 42 |
+
|
| 43 |
+
anomalies = determine_anomalies(mse_values, anomaly_threshold)
|
| 44 |
+
anomaly_frames = df['Frame'].iloc[anomalies].tolist()
|
| 45 |
+
|
| 46 |
+
ax.scatter(df['Seconds'].iloc[anomalies], mse_values[anomalies], color='red', s=20, zorder=5)
|
| 47 |
+
|
| 48 |
+
anomaly_data = list(zip(df['Timecode'].iloc[anomalies],
|
| 49 |
+
df['Seconds'].iloc[anomalies],
|
| 50 |
+
mse_values[anomalies]))
|
| 51 |
+
anomaly_data.sort(key=lambda x: x[1])
|
| 52 |
+
|
| 53 |
+
grouped_anomalies = []
|
| 54 |
+
current_group = []
|
| 55 |
+
for timecode, sec, mse in anomaly_data:
|
| 56 |
+
if not current_group or sec - current_group[-1][1] <= time_threshold:
|
| 57 |
+
current_group.append((timecode, sec, mse))
|
| 58 |
+
else:
|
| 59 |
+
grouped_anomalies.append(current_group)
|
| 60 |
+
current_group = [(timecode, sec, mse)]
|
| 61 |
+
if current_group:
|
| 62 |
+
grouped_anomalies.append(current_group)
|
| 63 |
+
|
| 64 |
+
for group in grouped_anomalies:
|
| 65 |
+
start_sec = group[0][1]
|
| 66 |
+
end_sec = group[-1][1]
|
| 67 |
+
rect = Rectangle((start_sec, ax.get_ylim()[0]), end_sec - start_sec, ax.get_ylim()[1] - ax.get_ylim()[0],
|
| 68 |
+
facecolor='red', alpha=0.2, zorder=1)
|
| 69 |
+
ax.add_patch(rect)
|
| 70 |
+
|
| 71 |
+
for group in grouped_anomalies:
|
| 72 |
+
highest_mse_anomaly = max(group, key=lambda x: x[2])
|
| 73 |
+
timecode, sec, mse = highest_mse_anomaly
|
| 74 |
+
ax.annotate(timecode, (sec, mse), textcoords="offset points", xytext=(0, 10),
|
| 75 |
+
ha='center', fontsize=6, color='red')
|
| 76 |
+
|
| 77 |
+
max_seconds = df['Seconds'].max()
|
| 78 |
+
num_ticks = 100
|
| 79 |
+
tick_locations = np.linspace(0, max_seconds, num_ticks)
|
| 80 |
+
tick_labels = [seconds_to_timecode(int(s)) for s in tick_locations]
|
| 81 |
+
|
| 82 |
+
ax.set_xticks(tick_locations)
|
| 83 |
+
ax.set_xticklabels(tick_labels, rotation=90, ha='center', fontsize=6)
|
| 84 |
+
|
| 85 |
+
ax.set_xlabel('Timecode')
|
| 86 |
+
ax.set_ylabel('Mean Squared Error')
|
| 87 |
+
ax.set_title(title)
|
| 88 |
+
|
| 89 |
+
ax.grid(True, linestyle='--', alpha=0.7)
|
| 90 |
+
ax.legend()
|
| 91 |
+
plt.tight_layout()
|
| 92 |
+
plt.close()
|
| 93 |
+
return fig, anomaly_frames
|
| 94 |
+
|
| 95 |
+
def plot_mse_histogram(mse_values, title, anomaly_threshold, color='blue'):
|
| 96 |
+
plt.figure(figsize=(16, 3), dpi=400)
|
| 97 |
+
fig, ax = plt.subplots(figsize=(16, 3))
|
| 98 |
+
|
| 99 |
+
ax.hist(mse_values, bins=100, edgecolor='black', color=color, alpha=0.7)
|
| 100 |
+
ax.set_xlabel('Mean Squared Error')
|
| 101 |
+
ax.set_ylabel('Number of Samples')
|
| 102 |
+
ax.set_title(title)
|
| 103 |
+
|
| 104 |
+
mean = np.mean(mse_values)
|
| 105 |
+
std = np.std(mse_values)
|
| 106 |
+
threshold = mean + anomaly_threshold * std
|
| 107 |
+
|
| 108 |
+
ax.axvline(x=threshold, color='red', linestyle='--', linewidth=2)
|
| 109 |
+
|
| 110 |
+
plt.tight_layout()
|
| 111 |
+
plt.close()
|
| 112 |
+
return fig
|
| 113 |
+
|
| 114 |
+
def plot_mse_heatmap(mse_values, title, df):
|
| 115 |
+
plt.figure(figsize=(20, 3), dpi=400)
|
| 116 |
+
fig, ax = plt.subplots(figsize=(20, 3))
|
| 117 |
+
|
| 118 |
+
# Reshape MSE values to 2D array for heatmap
|
| 119 |
+
mse_2d = mse_values.reshape(1, -1)
|
| 120 |
+
|
| 121 |
+
# Create heatmap
|
| 122 |
+
sns.heatmap(mse_2d, cmap='YlOrRd', cbar=False, ax=ax)
|
| 123 |
+
|
| 124 |
+
# Set x-axis ticks to timecodes
|
| 125 |
+
num_ticks = 60
|
| 126 |
+
tick_locations = np.linspace(0, len(mse_values) - 1, num_ticks).astype(int)
|
| 127 |
+
tick_labels = [df['Timecode'].iloc[i] for i in tick_locations]
|
| 128 |
+
|
| 129 |
+
ax.set_xticks(tick_locations)
|
| 130 |
+
ax.set_xticklabels(tick_labels, rotation=90, ha='center', va='top')
|
| 131 |
+
|
| 132 |
+
ax.set_title(title)
|
| 133 |
+
|
| 134 |
+
# Remove y-axis labels
|
| 135 |
+
ax.set_yticks([])
|
| 136 |
+
|
| 137 |
+
plt.tight_layout()
|
| 138 |
+
plt.close()
|
| 139 |
+
return fig
|
| 140 |
+
|
| 141 |
+
def plot_posture(df, posture_scores, color='blue', anomaly_threshold=3):
|
| 142 |
+
plt.figure(figsize=(16, 8), dpi=400)
|
| 143 |
+
fig, ax = plt.subplots(figsize=(16, 8))
|
| 144 |
+
|
| 145 |
+
df['Seconds'] = df['Timecode'].apply(
|
| 146 |
+
lambda x: sum(float(t) * 60 ** i for i, t in enumerate(reversed(x.split(':')))))
|
| 147 |
+
|
| 148 |
+
posture_data = [(frame, score) for frame, score in posture_scores.items() if score is not None]
|
| 149 |
+
posture_frames, posture_scores = zip(*posture_data)
|
| 150 |
+
|
| 151 |
+
# Create a new dataframe for posture data
|
| 152 |
+
posture_df = pd.DataFrame({'Frame': posture_frames, 'Score': posture_scores})
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
posture_df = posture_df.merge(df[['Frame', 'Seconds']], on='Frame', how='inner')
|
| 156 |
+
|
| 157 |
+
ax.scatter(posture_df['Seconds'], posture_df['Score'], color=color, alpha=0.3, s=5)
|
| 158 |
+
mean = posture_df['Score'].rolling(window=10).mean()
|
| 159 |
+
ax.plot(posture_df['Seconds'], mean, color=color, linewidth=0.5)
|
| 160 |
+
|
| 161 |
+
ax.set_xlabel('Timecode')
|
| 162 |
+
ax.set_ylabel('Posture Score')
|
| 163 |
+
ax.set_title("Body Posture Over Time")
|
| 164 |
+
|
| 165 |
+
ax.grid(True, linestyle='--', alpha=0.7)
|
| 166 |
+
|
| 167 |
+
max_seconds = df['Seconds'].max()
|
| 168 |
+
num_ticks = 80
|
| 169 |
+
tick_locations = np.linspace(0, max_seconds, num_ticks)
|
| 170 |
+
tick_labels = [seconds_to_timecode(int(s)) for s in tick_locations]
|
| 171 |
+
|
| 172 |
+
ax.set_xticks(tick_locations)
|
| 173 |
+
ax.set_xticklabels(tick_labels, rotation=90, ha='center', fontsize=6)
|
| 174 |
+
|
| 175 |
+
plt.tight_layout()
|
| 176 |
+
plt.close()
|
| 177 |
+
return fig
|