AID / app.py
Netrava's picture
Update app.py
5502f1e verified
Raw History Blame Contribute Delete
7.71 kB
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()