File size: 1,676 Bytes
346a1b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# Step 1: Import libraries
from transformers import DetrImageProcessor, DetrForObjectDetection
from PIL import Image, ImageDraw
import torch
import gradio as gr

# Step 2: Load model and processor
model = DetrForObjectDetection.from_pretrained("hilmantm/detr-traffic-accident-detection")
processor = DetrImageProcessor.from_pretrained("hilmantm/detr-traffic-accident-detection")

# Step 3: Define the inference logic
def detect_traffic_accidents(image):
    # Preprocess image
    inputs = processor(images=image, return_tensors="pt")
    
    # Run model inference
    outputs = model(**inputs)

    # Extract detections
    target_sizes = torch.tensor([image.size[::-1]])  # Width, height
    results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.9)[0]
    
    # Annotate image with bounding boxes
    draw = ImageDraw.Draw(image)
    for box, score, label in zip(results["boxes"], results["scores"], results["labels"]):
        if score > 0.9:  # Confidence threshold
            x_min, y_min, x_max, y_max = box
            draw.rectangle([x_min, y_min, x_max, y_max], outline="red", width=3)
            draw.text((x_min, y_min), f"{model.config.id2label[label]}: {score:.2f}", fill="red")

    return image

# Step 4: Define the Gradio Interface
def api_endpoint(input_image):
    output_image = detect_traffic_accidents(input_image)
    return output_image

# Step 5: Launch Gradio app
iface = gr.Interface(
    fn=api_endpoint,
    inputs=gr.Image(type="pil"),  # Accepts images
    outputs=gr.Image(type="pil"),  # Returns annotated image
)

iface.launch(server_name="0.0.0.0", server_port=7860)  # Accessible via LAN/WAN