boostedhug commited on
Commit
346a1b8
·
verified ·
1 Parent(s): 36a1348
Files changed (1) hide show
  1. app.py +45 -0
app.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Step 1: Import libraries
2
+ from transformers import DetrImageProcessor, DetrForObjectDetection
3
+ from PIL import Image, ImageDraw
4
+ import torch
5
+ import gradio as gr
6
+
7
+ # Step 2: Load model and processor
8
+ model = DetrForObjectDetection.from_pretrained("hilmantm/detr-traffic-accident-detection")
9
+ processor = DetrImageProcessor.from_pretrained("hilmantm/detr-traffic-accident-detection")
10
+
11
+ # Step 3: Define the inference logic
12
+ def detect_traffic_accidents(image):
13
+ # Preprocess image
14
+ inputs = processor(images=image, return_tensors="pt")
15
+
16
+ # Run model inference
17
+ outputs = model(**inputs)
18
+
19
+ # Extract detections
20
+ target_sizes = torch.tensor([image.size[::-1]]) # Width, height
21
+ results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.9)[0]
22
+
23
+ # Annotate image with bounding boxes
24
+ draw = ImageDraw.Draw(image)
25
+ for box, score, label in zip(results["boxes"], results["scores"], results["labels"]):
26
+ if score > 0.9: # Confidence threshold
27
+ x_min, y_min, x_max, y_max = box
28
+ draw.rectangle([x_min, y_min, x_max, y_max], outline="red", width=3)
29
+ draw.text((x_min, y_min), f"{model.config.id2label[label]}: {score:.2f}", fill="red")
30
+
31
+ return image
32
+
33
+ # Step 4: Define the Gradio Interface
34
+ def api_endpoint(input_image):
35
+ output_image = detect_traffic_accidents(input_image)
36
+ return output_image
37
+
38
+ # Step 5: Launch Gradio app
39
+ iface = gr.Interface(
40
+ fn=api_endpoint,
41
+ inputs=gr.Image(type="pil"), # Accepts images
42
+ outputs=gr.Image(type="pil"), # Returns annotated image
43
+ )
44
+
45
+ iface.launch(server_name="0.0.0.0", server_port=7860) # Accessible via LAN/WAN