Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -2,117 +2,127 @@ import gradio as gr
|
|
2 |
from ultralytics import YOLO
|
3 |
from PIL import Image, ImageDraw, ImageFont
|
4 |
import random
|
|
|
|
|
5 |
|
6 |
-
#
|
7 |
YOLO_MODEL_PATH = "best-Dense.pt"
|
|
|
|
|
|
|
|
|
8 |
model = YOLO(YOLO_MODEL_PATH, task='detect').to("cpu")
|
9 |
|
10 |
-
# Define
|
11 |
CLASS_COLORS = {}
|
|
|
12 |
|
13 |
def get_class_color(class_id):
|
14 |
-
"""Assign
|
15 |
if class_id not in CLASS_COLORS:
|
16 |
CLASS_COLORS[class_id] = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
|
17 |
return CLASS_COLORS[class_id]
|
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 |
-
draw = ImageDraw.Draw(annotated_image)
|
48 |
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
# Draw filled rectangle behind text for better visibility
|
68 |
-
draw.rectangle([x1, y1 - text_height - 4, x1 + text_width + 6, y1], fill=color)
|
69 |
-
draw.text((x1 + 3, y1 - text_height - 2), class_name, fill="white", font=font)
|
70 |
-
|
71 |
-
total_objects = len(detected_boxes)
|
72 |
-
total_classes = len(set(class_ids))
|
73 |
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
78 |
})
|
79 |
|
80 |
-
return (
|
81 |
-
|
82 |
-
|
|
|
|
|
83 |
)
|
84 |
|
85 |
-
# Gradio
|
86 |
with gr.Blocks() as iface:
|
87 |
gr.Markdown("# 📜 Text Line Detection with YOLO")
|
88 |
-
|
89 |
-
|
90 |
with gr.Row():
|
91 |
-
with gr.Column(
|
92 |
-
gr.
|
93 |
-
|
94 |
-
|
95 |
-
with gr.Column(
|
96 |
-
gr.
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
image_input.upload(
|
108 |
detect_text_lines,
|
109 |
-
inputs=
|
110 |
-
outputs=[
|
111 |
-
output_annotated_1, output_objects_1, output_classes_1,
|
112 |
-
output_annotated_2, output_objects_2, output_classes_2
|
113 |
-
]
|
114 |
)
|
115 |
|
116 |
-
# 🚀 Run the app locally
|
117 |
if __name__ == "__main__":
|
118 |
-
iface.launch(
|
|
|
|
|
|
|
|
|
|
|
|
2 |
from ultralytics import YOLO
|
3 |
from PIL import Image, ImageDraw, ImageFont
|
4 |
import random
|
5 |
+
import numpy as np
|
6 |
+
import os
|
7 |
|
8 |
+
# Check if YOLO model exists
|
9 |
YOLO_MODEL_PATH = "best-Dense.pt"
|
10 |
+
if not os.path.exists(YOLO_MODEL_PATH):
|
11 |
+
raise FileNotFoundError(f"YOLO model file not found at {YOLO_MODEL_PATH}")
|
12 |
+
|
13 |
+
# Load YOLO model
|
14 |
model = YOLO(YOLO_MODEL_PATH, task='detect').to("cpu")
|
15 |
|
16 |
+
# Define class colors and names
|
17 |
CLASS_COLORS = {}
|
18 |
+
CLASS_NAMES = {0: "Text"}
|
19 |
|
20 |
def get_class_color(class_id):
|
21 |
+
"""Assign consistent random colors to classes."""
|
22 |
if class_id not in CLASS_COLORS:
|
23 |
CLASS_COLORS[class_id] = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
|
24 |
return CLASS_COLORS[class_id]
|
25 |
|
26 |
+
def safe_font_load():
|
27 |
+
"""Safely load font with fallback."""
|
28 |
+
try:
|
29 |
+
return ImageFont.truetype("arial.ttf", 18)
|
30 |
+
except:
|
31 |
+
return ImageFont.load_default()
|
32 |
+
|
33 |
+
def process_detection(image, conf, iou):
|
34 |
+
"""Process detection with error handling."""
|
35 |
+
pil_image = Image.fromarray(image)
|
36 |
+
draw = ImageDraw.Draw(pil_image)
|
37 |
+
font = safe_font_load()
|
38 |
+
|
39 |
+
# Run model prediction
|
40 |
+
results = model.predict(pil_image, conf=conf, iou=iou, device="cpu")
|
41 |
+
|
42 |
+
# Handle empty results safely
|
43 |
+
detected_boxes = []
|
44 |
+
class_ids = []
|
45 |
+
if results[0].boxes is not None:
|
46 |
+
detected_boxes = results[0].boxes.xyxy.cpu().numpy().tolist()
|
47 |
+
class_ids = results[0].boxes.cls.cpu().numpy().astype(int).tolist()
|
48 |
+
|
49 |
+
# Draw bounding boxes and labels
|
50 |
+
for idx, (x1, y1, x2, y2) in enumerate(detected_boxes):
|
51 |
+
class_id = class_ids[idx] if idx < len(class_ids) else 0
|
52 |
+
color = get_class_color(class_id)
|
53 |
+
class_name = CLASS_NAMES.get(class_id, f"Class {class_id}")
|
|
|
54 |
|
55 |
+
# Draw rectangle
|
56 |
+
draw.rectangle([x1, y1, x2, y2], outline=color, width=2)
|
57 |
+
|
58 |
+
# Draw text label
|
59 |
+
text = f"{class_name}"
|
60 |
+
text_bbox = draw.textbbox((0, 0), text, font=font)
|
61 |
+
draw.rectangle(
|
62 |
+
[x1, y1 - (text_bbox[3] - text_bbox[1]) - 4, x1 + (text_bbox[2] - text_bbox[0]) + 6, y1],
|
63 |
+
fill=color
|
64 |
+
)
|
65 |
+
draw.text(
|
66 |
+
(x1 + 3, y1 - (text_bbox[3] - text_bbox[1]) - 2),
|
67 |
+
text,
|
68 |
+
fill="white",
|
69 |
+
font=font
|
70 |
+
)
|
71 |
+
|
72 |
+
return pil_image, len(detected_boxes), len(set(class_ids))
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
|
74 |
+
def detect_text_lines(image):
|
75 |
+
"""Main detection function with dual threshold handling."""
|
76 |
+
# Process with two different threshold sets
|
77 |
+
results = []
|
78 |
+
for thresholds in [(0.6, 0.5), (0.4, 0.3)]:
|
79 |
+
conf, iou = thresholds
|
80 |
+
annotated_img, obj_count, class_count = process_detection(
|
81 |
+
np.array(image), conf, iou
|
82 |
+
)
|
83 |
+
results.append({
|
84 |
+
"image": annotated_img,
|
85 |
+
"objects": f"Objects: {obj_count} (Conf={conf}, IoU={iou})",
|
86 |
+
"classes": f"Classes: {class_count} (Conf={conf}, IoU={iou})"
|
87 |
})
|
88 |
|
89 |
+
return tuple(
|
90 |
+
item for sublist in [
|
91 |
+
(results[0]["image"], results[0]["objects"], results[0]["classes"],
|
92 |
+
results[1]["image"], results[1]["objects"], results[1]["classes"])
|
93 |
+
] for item in sublist
|
94 |
)
|
95 |
|
96 |
+
# Gradio interface
|
97 |
with gr.Blocks() as iface:
|
98 |
gr.Markdown("# 📜 Text Line Detection with YOLO")
|
99 |
+
|
|
|
100 |
with gr.Row():
|
101 |
+
with gr.Column():
|
102 |
+
input_image = gr.Image(type="numpy", label="Input Image")
|
103 |
+
submit_btn = gr.Button("Detect Text")
|
104 |
+
|
105 |
+
with gr.Column():
|
106 |
+
with gr.Tab("High Confidence"):
|
107 |
+
high_conf_img = gr.Image(type="pil", label="Detections (0.6 conf)")
|
108 |
+
high_conf_obj = gr.Textbox(label="Object Count")
|
109 |
+
high_conf_cls = gr.Textbox(label="Class Count")
|
110 |
+
|
111 |
+
with gr.Tab("Low Confidence"):
|
112 |
+
low_conf_img = gr.Image(type="pil", label="Detections (0.4 conf)")
|
113 |
+
low_conf_obj = gr.Textbox(label="Object Count")
|
114 |
+
low_conf_cls = gr.Textbox(label="Class Count")
|
115 |
+
|
116 |
+
submit_btn.click(
|
|
|
117 |
detect_text_lines,
|
118 |
+
inputs=input_image,
|
119 |
+
outputs=[high_conf_img, high_conf_obj, high_conf_cls, low_conf_img, low_conf_obj, low_conf_cls]
|
|
|
|
|
|
|
120 |
)
|
121 |
|
|
|
122 |
if __name__ == "__main__":
|
123 |
+
iface.launch(
|
124 |
+
server_name="0.0.0.0",
|
125 |
+
server_port=7860,
|
126 |
+
show_error=True,
|
127 |
+
share=False
|
128 |
+
)
|