Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,54 +1,19 @@
|
|
| 1 |
import torch
|
| 2 |
from ultralytics import YOLO
|
| 3 |
import gradio as gr
|
| 4 |
-
import easyocr
|
| 5 |
-
import numpy as np
|
| 6 |
-
from PIL import Image
|
| 7 |
-
import ultralytics.nn.tasks as tasks
|
| 8 |
|
| 9 |
-
#
|
| 10 |
-
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
|
| 14 |
-
model = YOLO(WEIGHTS_PATH, task="detect")
|
| 15 |
|
| 16 |
-
|
| 17 |
-
reader = easyocr.Reader(['en'], gpu=False)
|
| 18 |
|
| 19 |
-
def
|
| 20 |
-
# Run YOLO detection
|
| 21 |
results = model(image)
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
output_data = []
|
| 26 |
-
img_pil = Image.fromarray(image)
|
| 27 |
-
|
| 28 |
-
for i, box in enumerate(detections):
|
| 29 |
-
x1, y1, x2, y2 = [int(v) for v in box[:4]]
|
| 30 |
-
cropped_img = img_pil.crop((x1, y1, x2, y2))
|
| 31 |
-
|
| 32 |
-
# OCR
|
| 33 |
-
ocr_result = reader.readtext(np.array(cropped_img))
|
| 34 |
-
text = " ".join([res[1] for res in ocr_result])
|
| 35 |
-
|
| 36 |
-
output_data.append({
|
| 37 |
-
"bbox": (x1, y1, x2, y2),
|
| 38 |
-
"label": labels[int(results[0].boxes.cls[i])],
|
| 39 |
-
"text": text
|
| 40 |
-
})
|
| 41 |
-
|
| 42 |
-
return output_data
|
| 43 |
-
|
| 44 |
-
# Gradio UI
|
| 45 |
-
demo = gr.Interface(
|
| 46 |
-
fn=detect_and_read,
|
| 47 |
-
inputs=gr.Image(type="numpy"),
|
| 48 |
-
outputs="json",
|
| 49 |
-
title="YOLOv8 + EasyOCR",
|
| 50 |
-
description="Object detection with YOLOv8 and OCR with EasyOCR"
|
| 51 |
-
)
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
|
|
|
| 1 |
import torch
|
| 2 |
from ultralytics import YOLO
|
| 3 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
+
# Trusted YOLO weights path
|
| 6 |
+
WEIGHTS_PATH = "/app/yolov8n.pt"
|
| 7 |
|
| 8 |
+
# Allow loading full model (Option 1 from error)
|
| 9 |
+
torch.serialization.add_safe_globals([YOLO])
|
|
|
|
| 10 |
|
| 11 |
+
model = YOLO(WEIGHTS_PATH, task="detect")
|
|
|
|
| 12 |
|
| 13 |
+
def detect_objects(image):
|
|
|
|
| 14 |
results = model(image)
|
| 15 |
+
annotated = results[0].plot()
|
| 16 |
+
return annotated
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
+
demo = gr.Interface(fn=detect_objects, inputs="image", outputs="image")
|
| 19 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|