SamiKhokhar commited on
Commit
9423eeb
·
verified ·
1 Parent(s): 293da65

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -0
app.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import gradio as gr
4
+ from PIL import Image
5
+
6
+ # Step 1: Search for best.pt in the training directory
7
+ base_path = "yolov5/runs/train/"
8
+ best_path = None
9
+
10
+ # Search through the directory structure to find best.pt
11
+ for root, dirs, files in os.walk(base_path):
12
+ if "best.pt" in files:
13
+ best_path = os.path.join(root, "best.pt")
14
+ break
15
+
16
+ # Step 2: If best.pt is not found, use pre-trained weights
17
+ if best_path is None:
18
+ print("Trained weights (best.pt) not found.")
19
+ print("Using pre-trained YOLOv5 weights (yolov5s.pt) instead.")
20
+
21
+ # Fallback to a pre-trained model if best.pt is not available
22
+ model = torch.hub.load('ultralytics/yolov5', 'yolov5s') # Load pre-trained weights
23
+
24
+ else:
25
+ print(f"Model weights found at: {best_path}")
26
+ # Load YOLOv5 model with the correct path
27
+ model = torch.hub.load('ultralytics/yolov5', 'custom', path=best_path)
28
+
29
+ # Step 3: Detection Function
30
+ def detect_weapons(image):
31
+ results = model(image)
32
+ detected_classes = results.pandas().xyxy[0]['name'].unique()
33
+
34
+ # Check for threats
35
+ threat_message = "Threat detected: Be careful" if len(detected_classes) > 0 else "No threat detected"
36
+ return threat_message, Image.fromarray(results.render()[0])
37
+
38
+ # Step 4: Gradio Interface
39
+ def inference(image):
40
+ threat, detected_image = detect_weapons(image)
41
+ return threat, detected_image
42
+
43
+ iface = gr.Interface(
44
+ fn=inference,
45
+ inputs=gr.Image(type="numpy", label="Upload Image"),
46
+ outputs=[
47
+ gr.Textbox(label="Threat Detection"),
48
+ gr.Image(label="Detected Image"),
49
+ ],
50
+ title="Weapon Detection AI",
51
+ description="Upload an image to detect weapons like bombs, guns, and pistols."
52
+ )
53
+
54
+ # Step 5: Launch Gradio App
55
+ iface.launch()