File size: 7,712 Bytes
9d70440 5502f1e 9d70440 | 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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 |
import gradio as gr
from ultralytics import YOLO
import cv2
import numpy as np
from PIL import Image
import os
# Load model with error handling
model = None
model_info = "No model loaded"
# First, check if the model files exist
model_path = 'netrava_ui_model.pt'
default_model_path = 'yolov8n.pt'
print(f"Looking for model at: {os.path.abspath(model_path)}")
if os.path.exists(model_path):
print(f"β
Found custom model at {model_path}")
try:
model = YOLO(model_path)
model_info = f"Custom model loaded: {model_path}"
print(f"β
Custom model loaded successfully")
except Exception as e:
print(f"β οΈ Error loading custom model: {e}")
model = None
else:
print(f"β Custom model not found at {model_path}")
# Try to load default model if custom model failed
if model is None:
print(f"Looking for default model at: {os.path.abspath(default_model_path)}")
if os.path.exists(default_model_path):
print(f"β
Found default model at {default_model_path}")
try:
model = YOLO(default_model_path)
model_info = f"Default model loaded: {default_model_path}"
print(f"β
Default YOLOv8n model loaded successfully")
except Exception as e:
print(f"β Error loading default model: {e}")
model = None
else:
print(f"β Default model not found at {default_model_path}")
# If both models failed, try to download the default model
if model is None:
try:
print("Attempting to download default YOLOv8n model...")
model = YOLO('yolov8n.pt') # This will download the model if not found
model_info = "Downloaded default YOLOv8n model"
print("β
Default YOLOv8n model downloaded and loaded successfully")
except Exception as e:
print(f"β Failed to download default model: {e}")
model_info = f"Failed to load any model: {str(e)}"
model = None
def detect_ui_elements(image):
"""Detect UI elements in uploaded image"""
try:
# Check if model is loaded
if model is None:
# Create an error image with text
error_img = Image.new('RGB', (640, 480), color=(255, 0, 0))
# Add text to the image
from PIL import ImageDraw, ImageFont
draw = ImageDraw.Draw(error_img)
draw.text((20, 20), "ERROR: Model not loaded", fill=(255, 255, 255))
draw.text((20, 60), model_info, fill=(255, 255, 255))
draw.text((20, 100), "Please upload netrava_ui_model.pt to your Space", fill=(255, 255, 255))
return error_img, []
# Check if image is provided
if image is None:
error_img = Image.new('RGB', (640, 480), color=(255, 255, 0))
from PIL import ImageDraw
draw = ImageDraw.Draw(error_img)
draw.text((20, 20), "Please upload an image", fill=(0, 0, 0))
return error_img, []
# Print image info for debugging
print(f"Processing image of type: {type(image)}, shape: {image.size if hasattr(image, 'size') else 'unknown'}")
# Convert PIL to OpenCV format
img_array = np.array(image)
img_bgr = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR)
# Run detection
print("Running detection...")
results = model(img_bgr)
print(f"Detection complete. Found {len(results[0].boxes) if results and results[0].boxes else 0} objects")
# Prepare detections list for API
detections = []
# Draw results
for result in results:
boxes = result.boxes
if boxes is not None and len(boxes) > 0:
print(f"Processing {len(boxes)} boxes")
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())
class_name = model.names[cls]
# Add to detections list
detections.append({
"class": class_name,
"confidence": float(conf),
"bbox": [int(x1), int(y1), int(x2), int(y2)],
"center": [int((x1+x2)/2), int((y1+y2)/2)],
"size": [int(x2-x1), int(y2-y1)]
})
# Draw bounding box
cv2.rectangle(img_bgr, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
# Add label
label = f'{class_name}: {conf:.2f}'
cv2.putText(img_bgr, label, (int(x1), int(y1)-10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)
print(f"Detected: {label} at [{int(x1)}, {int(y1)}, {int(x2)}, {int(y2)}]")
else:
print("No objects detected")
# Convert back to RGB
result_img = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
return Image.fromarray(result_img), detections
except Exception as e:
print(f"Error in detection: {str(e)}")
import traceback
traceback.print_exc()
# Create an error image with the exception message
error_img = Image.new('RGB', (640, 480), color=(255, 0, 0))
from PIL import ImageDraw
draw = ImageDraw.Draw(error_img)
draw.text((20, 20), f"Error: {str(e)}", fill=(255, 255, 255))
return error_img, []
# API endpoint for health check
def health_check():
"""Health check endpoint"""
if model is None:
return {"status": "unhealthy", "message": model_info}
else:
return {"status": "healthy", "message": model_info}
# API endpoint for detection
def api_detect(image):
"""API endpoint for detection"""
_, detections = detect_ui_elements(image)
return {"success": True, "detections": detections, "count": len(detections)}
# Create Gradio interface with API endpoints
with gr.Blocks(title="Netrava UI Detection") as demo:
gr.Markdown("# π€ Netrava UI Detection")
gr.Markdown(f"""
Upload a screenshot to detect UI elements like buttons, textboxes, etc.
**Model Status:** {model_info}
*Note: For best results, upload the netrava_ui_model.pt file to your Hugging Face Space.*
""")
with gr.Row():
with gr.Column():
input_image = gr.Image(type="pil", label="Upload Screenshot")
detect_button = gr.Button("Detect UI Elements")
with gr.Column():
output_image = gr.Image(type="pil", label="Detection Result")
output_json = gr.JSON(label="Detection Results")
detect_button.click(
fn=detect_ui_elements,
inputs=input_image,
outputs=[output_image, output_json]
)
gr.Markdown("## API Usage")
gr.Markdown("""
```python
import requests
from PIL import Image
import io
# Prepare image
image = Image.open("screenshot.png")
buffer = io.BytesIO()
image.save(buffer, format="PNG")
image_bytes = buffer.getvalue()
# Send to API
response = requests.post(
"https://YOUR_USERNAME-netrava-ui-detection.hf.space/api/predict",
files={"image": image_bytes}
)
# Process results
result = response.json()
print(f"Detected {len(result['data'][1])} UI elements")
```
""")
# Launch the interface
if __name__ == "__main__":
demo.launch()
|