ummanmm commited on
Commit
6015401
·
verified ·
1 Parent(s): 9dabedd

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +75 -0
app.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import torch.nn.functional as F
4
+ import numpy as np
5
+ from torchvision import models, transforms
6
+ from huggingface_hub import hf_hub_download
7
+ from PIL import Image
8
+ from pytorch_grad_cam import GradCAM
9
+ from pytorch_grad_cam.utils.image import show_cam_on_image
10
+
11
+ MODEL_REPO = "ummanmm/classroom-engagement-mobilenet"
12
+ CLASSES = [
13
+ "Oriented (Lecture-Focused)",
14
+ "Diverted (Looking Away/Down)",
15
+ "Obscured (Blocked/Empty)",
16
+ ]
17
+ IMAGENET_MEAN = [0.485, 0.456, 0.406]
18
+ IMAGENET_STD = [0.229, 0.224, 0.225]
19
+
20
+ model_path = hf_hub_download(
21
+ repo_id=MODEL_REPO, filename="best_baseline.pth"
22
+ )
23
+
24
+ model = models.mobilenet_v2(weights=None)
25
+ model.classifier[1] = torch.nn.Linear(model.last_channel, 3)
26
+ model.load_state_dict(
27
+ torch.load(model_path, map_location=torch.device("cpu"))
28
+ )
29
+ model.eval()
30
+
31
+ transform = transforms.Compose([
32
+ transforms.Resize((224, 224)),
33
+ transforms.ToTensor(),
34
+ transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD),
35
+ ])
36
+
37
+
38
+ def predict_engagement(image):
39
+ if image is None:
40
+ return {}, None
41
+
42
+ img = Image.fromarray(image).convert("RGB")
43
+ tensor = transform(img).unsqueeze(0)
44
+
45
+ with torch.no_grad():
46
+ outputs = model(tensor)
47
+ probs = F.softmax(outputs[0], dim=0)
48
+
49
+ confidences = {CLASSES[i]: float(probs[i]) for i in range(3)}
50
+
51
+ rgb = np.array(img.resize((224, 224))).astype(np.float32) / 255.0
52
+ cam = GradCAM(model=model, target_layers=[model.features[-1]])
53
+ grayscale = cam(input_tensor=tensor, targets=None)[0, :]
54
+ heatmap = show_cam_on_image(rgb, grayscale, use_rgb=True)
55
+
56
+ return confidences, heatmap
57
+
58
+
59
+ demo = gr.Interface(
60
+ fn=predict_engagement,
61
+ inputs=gr.Image(label="Upload Student Crop"),
62
+ outputs=[
63
+ gr.Label(num_top_classes=3, label="Engagement Prediction"),
64
+ gr.Image(label="Grad-CAM Attention Heatmap"),
65
+ ],
66
+ title="Real-Time Classroom Engagement Telemetry",
67
+ description=(
68
+ "Upload a cropped image of a student to classify their "
69
+ "physical engagement state using a custom MobileNetV2 model. "
70
+ "The Grad-CAM heatmap shows which regions the CNN focuses on."
71
+ ),
72
+ examples=[],
73
+ )
74
+
75
+ demo.launch()