File size: 2,387 Bytes
55e38fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7dff749
55e38fd
 
 
 
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72

import gradio as gr
import torch
from ultralytics import YOLO
import cv2
import numpy as np
from PIL import Image

# Load model with error handling
try:
    model = YOLO('best.pt')
    print("✅ Custom model loaded successfully")
except Exception as e:
    print(f"⚠️ Custom model not found, using default: {e}")
    try:
        model = YOLO('yolov8n.pt')  # Fallback to default
        print("✅ Default YOLOv8n model loaded")
    except Exception as e2:
        print(f"❌ Failed to load any model: {e2}")
        model = None

def detect_ui_elements(image):
    """Detect UI elements in uploaded image"""
    try:
        if model is None:
            return Image.new('RGB', (400, 300), color='red'), "❌ Model not available. Please upload netrava_ui_model.pt"
        
        # Convert PIL to OpenCV format
        img_array = np.array(image)
        img_bgr = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR)
        
        # Run detection
        results = model(img_bgr)
        
        # Draw results
        for result in results:
            boxes = result.boxes
            if boxes is not None:
                for box in boxes:
                    # Get coordinates
                    x1, y1, x2, y2 = box.xyxy[0].cpu().numpy()
                    conf = box.conf[0].cpu().numpy()
                    cls = int(box.cls[0].cpu().numpy())
                    
                    # Draw bounding box
                    cv2.rectangle(img_bgr, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
                    
                    # Add label
                    label = f'{model.names[cls]}: {conf:.2f}'
                    cv2.putText(img_bgr, label, (int(x1), int(y1)-10), 
                               cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)
        
        # Convert back to RGB
        result_img = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
        return Image.fromarray(result_img)
        
    except Exception as e:
        return f"Error: {str(e)}"

# Create Gradio interface
interface = gr.Interface(
    fn=detect_ui_elements,
    inputs=gr.Image(type="pil"),
    outputs=gr.Image(type="pil"),
    title="🤖 Netrava UI Element Detection",
    description="Upload a screenshot to detect UI elements like buttons, textboxes, etc.",
    examples=[["example1.png"], ["example2.png"]]
)

if __name__ == "__main__":
    interface.launch()