SRUTHI123 commited on
Commit
ee47dc3
·
verified ·
1 Parent(s): d6c4dbe

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -30
app.py CHANGED
@@ -3,50 +3,48 @@ from PIL import Image
3
  import numpy as np
4
  from ultralytics import YOLO
5
 
6
- # Streamlit page config
7
  st.set_page_config(page_title="Suspicious Activity Detection", layout="centered")
8
 
9
  # Load the YOLOv11 model
10
  @st.cache_resource
11
  def load_model():
12
- return YOLO("yolo11l.pt") # Ensure the file is in your app directory
13
 
14
  model = load_model()
15
 
16
- # ------------------ Action Classification Logic ------------------
17
  def classify_action(detections):
18
  action_scores = {'Stealing': 0, 'Sneaking': 0, 'Peaking': 0, 'Normal': 0}
19
  objects = [d[0] for d in detections]
20
  confidences = [d[1] for d in detections]
21
 
22
- num_persons = objects.count('person')
23
- total_objects = len(objects)
24
- avg_conf = np.mean(confidences) if confidences else 0.0
25
-
26
- has_valuable = any(obj in objects for obj in ['backpack', 'handbag', 'laptop', 'cash', 'microwave', 'refrigerator'])
27
-
28
- if num_persons >= 1:
29
- # Stealing
30
- if has_valuable:
 
 
31
  action_scores['Stealing'] += 0.7
32
- if 'handbag' in objects or 'laptop' in objects:
33
- action_scores['Stealing'] += 0.2
34
 
35
- # Sneaking - enhanced logic
36
- if (total_objects <= 2 and avg_conf < 0.5 and not has_valuable):
37
  action_scores['Sneaking'] += 0.9
38
 
39
- # Peaking
40
- elif (total_objects <= 3 and num_persons == 1 and avg_conf >= 0.5):
41
- action_scores['Peaking'] += 0.7
42
 
43
- # Normal fallback
44
- else:
45
- action_scores['Normal'] += 0.6
46
  else:
47
  action_scores['Normal'] += 1.0
48
 
49
- # Normalize scores
50
  total = sum(action_scores.values())
51
  if total > 0:
52
  for k in action_scores:
@@ -54,24 +52,21 @@ def classify_action(detections):
54
 
55
  return action_scores
56
 
57
-
58
  # ------------------ Detection Function ------------------
59
  def detect_action(image_path):
60
  results = model.predict(source=image_path, conf=0.4, iou=0.5, save=False, verbose=False)
61
  result = results[0]
62
-
63
  detections = [
64
  (model.names[int(cls)], float(conf))
65
  for cls, conf in zip(result.boxes.cls, result.boxes.conf)
66
  ]
67
-
68
  annotated_image = result.plot()
69
  action_scores = classify_action(detections)
70
  return annotated_image, action_scores
71
 
72
  # ------------------ Streamlit UI ------------------
73
- st.title("🛡️ Suspicious Activity Detection")
74
- st.markdown("Detect if someone is **Stealing**, **Sneaking**, **Peaking**, or just acting **Normal**.")
75
 
76
  uploaded_file = st.file_uploader("📸 Upload an image", type=["jpg", "jpeg", "png"])
77
 
@@ -82,7 +77,7 @@ if uploaded_file:
82
  temp_path = "/tmp/uploaded.jpg"
83
  image.save(temp_path)
84
 
85
- with st.spinner("Detecting activity..."):
86
  detected_image, action_scores = detect_action(temp_path)
87
 
88
  st.image(detected_image, caption="Detection Results", use_column_width=True)
@@ -92,4 +87,4 @@ if uploaded_file:
92
  st.write(f"**{action}**: {score:.2%}")
93
 
94
  top_action = max(action_scores.items(), key=lambda x: x[1])
95
- st.success(f"**Predicted Action:** {top_action[0]} ({top_action[1]:.2%} confidence)")
 
3
  import numpy as np
4
  from ultralytics import YOLO
5
 
 
6
  st.set_page_config(page_title="Suspicious Activity Detection", layout="centered")
7
 
8
  # Load the YOLOv11 model
9
  @st.cache_resource
10
  def load_model():
11
+ return YOLO("yolo11l.pt") # Ensure your model is uploaded in the root of the Hugging Face Space
12
 
13
  model = load_model()
14
 
15
+ # ------------------ Improved Classification Logic ------------------
16
  def classify_action(detections):
17
  action_scores = {'Stealing': 0, 'Sneaking': 0, 'Peaking': 0, 'Normal': 0}
18
  objects = [d[0] for d in detections]
19
  confidences = [d[1] for d in detections]
20
 
21
+ has_person = 'person' in objects
22
+ person_count = objects.count('person')
23
+ unique_objs = set(objects)
24
+ has_bag = any(obj in objects for obj in ['backpack', 'handbag'])
25
+ stealthy_conf = all(conf < 0.55 for conf in confidences) if confidences else True
26
+ low_activity = len(objects) <= 2
27
+
28
+ # --- Classify based on heuristic rules ---
29
+ if has_person:
30
+ # Stealing: person with object like bag/fridge and high confidence
31
+ if has_bag or any(obj in objects for obj in ['refrigerator', 'microwave', 'laptop']):
32
  action_scores['Stealing'] += 0.7
 
 
33
 
34
+ # Sneaking: low confidence + very few objects + only person
35
+ if stealthy_conf and person_count == 1 and len(unique_objs) == 1:
36
  action_scores['Sneaking'] += 0.9
37
 
38
+ # Peaking: low object count, mostly person, no interaction
39
+ elif person_count >= 1 and low_activity:
40
+ action_scores['Peaking'] += 0.6
41
 
42
+ # Otherwise: Normal
43
+ if action_scores['Sneaking'] == 0 and action_scores['Peaking'] == 0 and action_scores['Stealing'] == 0:
44
+ action_scores['Normal'] += 1.0
45
  else:
46
  action_scores['Normal'] += 1.0
47
 
 
48
  total = sum(action_scores.values())
49
  if total > 0:
50
  for k in action_scores:
 
52
 
53
  return action_scores
54
 
 
55
  # ------------------ Detection Function ------------------
56
  def detect_action(image_path):
57
  results = model.predict(source=image_path, conf=0.4, iou=0.5, save=False, verbose=False)
58
  result = results[0]
 
59
  detections = [
60
  (model.names[int(cls)], float(conf))
61
  for cls, conf in zip(result.boxes.cls, result.boxes.conf)
62
  ]
 
63
  annotated_image = result.plot()
64
  action_scores = classify_action(detections)
65
  return annotated_image, action_scores
66
 
67
  # ------------------ Streamlit UI ------------------
68
+ st.title("🕵️ Suspicious Activity Detection")
69
+ st.markdown("Detect if someone is **Stealing**, **Sneaking**, **Peaking**, or just acting **Normal** based on image input.")
70
 
71
  uploaded_file = st.file_uploader("📸 Upload an image", type=["jpg", "jpeg", "png"])
72
 
 
77
  temp_path = "/tmp/uploaded.jpg"
78
  image.save(temp_path)
79
 
80
+ with st.spinner("🔎 Detecting activity..."):
81
  detected_image, action_scores = detect_action(temp_path)
82
 
83
  st.image(detected_image, caption="Detection Results", use_column_width=True)
 
87
  st.write(f"**{action}**: {score:.2%}")
88
 
89
  top_action = max(action_scores.items(), key=lambda x: x[1])
90
+ st.success(f"🎯 **Predicted Action:** {top_action[0]} ({top_action[1]:.2%} confidence)")