Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
@@ -2,45 +2,122 @@ import gradio as gr
|
|
2 |
from ultralytics import YOLO
|
3 |
import spaces
|
4 |
import torch
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
|
6 |
# Load pre-trained YOLOv8 model
|
7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
-
#
|
10 |
-
|
|
|
|
|
|
|
|
|
|
|
11 |
|
12 |
@spaces.GPU(duration=60)
|
13 |
-
def process_image(image):
|
14 |
try:
|
15 |
-
|
16 |
-
|
17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
|
19 |
-
|
20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
|
27 |
-
return annotated_image, detected_areas_labels
|
28 |
except Exception as e:
|
29 |
return None, f"Error processing image: {e}"
|
30 |
|
31 |
# Create the Gradio Interface
|
32 |
with gr.Blocks() as demo:
|
33 |
gr.Markdown("# Document Segmentation Demo (ZeroGPU)")
|
34 |
-
|
35 |
with gr.Row():
|
|
|
36 |
input_image = gr.Image(type="pil", label="Upload Image")
|
37 |
-
|
38 |
-
|
39 |
output_text = gr.Textbox(label="Detected Areas and Labels")
|
40 |
-
|
41 |
-
# Button to trigger inference
|
42 |
btn = gr.Button("Run Document Segmentation")
|
43 |
-
btn.click(fn=process_image, inputs=input_image, outputs=[output_image, output_text])
|
44 |
|
45 |
# Launch the demo with queuing
|
46 |
demo.queue(max_size=1).launch()
|
|
|
2 |
from ultralytics import YOLO
|
3 |
import spaces
|
4 |
import torch
|
5 |
+
import cv2
|
6 |
+
import numpy as np
|
7 |
+
import os
|
8 |
+
import requests
|
9 |
+
|
10 |
+
# Define constants for the new model
|
11 |
+
ENTITIES_COLORS = {
|
12 |
+
"Caption": (191, 100, 21),
|
13 |
+
"Footnote": (2, 62, 115),
|
14 |
+
"Formula": (140, 80, 58),
|
15 |
+
"List-item": (168, 181, 69),
|
16 |
+
"Page-footer": (2, 69, 84),
|
17 |
+
"Page-header": (83, 115, 106),
|
18 |
+
"Picture": (255, 72, 88),
|
19 |
+
"Section-header": (0, 204, 192),
|
20 |
+
"Table": (116, 127, 127),
|
21 |
+
"Text": (0, 153, 221),
|
22 |
+
"Title": (196, 51, 2)
|
23 |
+
}
|
24 |
+
BOX_PADDING = 2
|
25 |
|
26 |
# Load pre-trained YOLOv8 model
|
27 |
+
model_path_1 = "yolov8x-doclaynet-epoch64-imgsz640-initiallr1e-4-finallr1e-5.pt"
|
28 |
+
model_path_2 = "models/dla-model.pt"
|
29 |
+
|
30 |
+
if not os.path.exists(model_path_1):
|
31 |
+
# Download the model file if it doesn't exist
|
32 |
+
model_url_1 = "https://huggingface.co/DILHTWD/documentlayoutsegmentation_YOLOv8_ondoclaynet/resolve/main/yolov8x-doclaynet-epoch64-imgsz640-initiallr1e-4-finallr1e-5.pt"
|
33 |
+
response = requests.get(model_url_1)
|
34 |
+
with open(model_path_1, "wb") as f:
|
35 |
+
f.write(response.content)
|
36 |
+
|
37 |
+
if not os.path.exists(model_path_2):
|
38 |
+
# Assume the second model file is manually uploaded in the specified path
|
39 |
|
40 |
+
# Load models
|
41 |
+
model_1 = YOLO(model_path_1)
|
42 |
+
model_2 = YOLO(model_path_2)
|
43 |
+
|
44 |
+
# Get class names from the first model
|
45 |
+
class_names_1 = model_1.names
|
46 |
+
class_names_2 = list(ENTITIES_COLORS.keys())
|
47 |
|
48 |
@spaces.GPU(duration=60)
|
49 |
+
def process_image(image, model_choice):
|
50 |
try:
|
51 |
+
if model_choice == "YOLOv8 Model":
|
52 |
+
# Use the first model
|
53 |
+
results = model_1(source=image, save=False, show_labels=True, show_conf=True, show_boxes=True)
|
54 |
+
result = results[0]
|
55 |
+
|
56 |
+
# Extract annotated image and labels with class names
|
57 |
+
annotated_image = result.plot()
|
58 |
+
|
59 |
+
detected_areas_labels = "\n".join([
|
60 |
+
f"{class_names_1[int(box.cls.item())].upper()}: {float(box.conf):.2f}" for box in result.boxes
|
61 |
+
])
|
62 |
|
63 |
+
return annotated_image, detected_areas_labels
|
64 |
+
|
65 |
+
elif model_choice == "DLA Model":
|
66 |
+
# Use the second model
|
67 |
+
image_path = "input_image.jpg" # Temporary save the uploaded image
|
68 |
+
cv2.imwrite(image_path, cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR))
|
69 |
+
image = cv2.imread(image_path)
|
70 |
+
results = model_2.predict(source=image, conf=0.2, iou=0.8)
|
71 |
+
boxes = results[0].boxes
|
72 |
|
73 |
+
if len(boxes) == 0:
|
74 |
+
return image
|
75 |
+
|
76 |
+
for box in boxes:
|
77 |
+
detection_class_conf = round(box.conf.item(), 2)
|
78 |
+
cls = class_names_2[int(box.cls)]
|
79 |
+
start_box = (int(box.xyxy[0][0]), int(box.xyxy[0][1]))
|
80 |
+
end_box = (int(box.xyxy[0][2]), int(box.xyxy[0][3]))
|
81 |
+
|
82 |
+
line_thickness = round(0.002 * (image.shape[0] + image.shape[1]) / 2) + 1
|
83 |
+
image = cv2.rectangle(img=image,
|
84 |
+
pt1=start_box,
|
85 |
+
pt2=end_box,
|
86 |
+
color=ENTITIES_COLORS[cls],
|
87 |
+
thickness=line_thickness)
|
88 |
+
|
89 |
+
text = cls + " " + str(detection_class_conf)
|
90 |
+
font_thickness = max(line_thickness - 1, 1)
|
91 |
+
(text_w, text_h), _ = cv2.getTextSize(text=text, fontFace=2, fontScale=line_thickness/3, thickness=font_thickness)
|
92 |
+
image = cv2.rectangle(img=image,
|
93 |
+
pt1=(start_box[0], start_box[1] - text_h - BOX_PADDING*2),
|
94 |
+
pt2=(start_box[0] + text_w + BOX_PADDING * 2, start_box[1]),
|
95 |
+
color=ENTITIES_COLORS[cls],
|
96 |
+
thickness=-1)
|
97 |
+
start_text = (start_box[0] + BOX_PADDING, start_box[1] - BOX_PADDING)
|
98 |
+
image = cv2.putText(img=image, text=text, org=start_text, fontFace=0, color=(255,255,255), fontScale=line_thickness/3, thickness=font_thickness)
|
99 |
+
|
100 |
+
return cv2.cvtColor(image, cv2.COLOR_BGR2RGB), "Labels: " + ", ".join(class_names_2)
|
101 |
+
|
102 |
+
else:
|
103 |
+
return None, "Invalid model choice"
|
104 |
|
|
|
105 |
except Exception as e:
|
106 |
return None, f"Error processing image: {e}"
|
107 |
|
108 |
# Create the Gradio Interface
|
109 |
with gr.Blocks() as demo:
|
110 |
gr.Markdown("# Document Segmentation Demo (ZeroGPU)")
|
111 |
+
|
112 |
with gr.Row():
|
113 |
+
model_choice = gr.Dropdown(["YOLOv8 Model", "DLA Model"], label="Select Model", value="YOLOv8 Model")
|
114 |
input_image = gr.Image(type="pil", label="Upload Image")
|
115 |
+
|
116 |
+
output_image = gr.Image(type="pil", label="Annotated Image")
|
117 |
output_text = gr.Textbox(label="Detected Areas and Labels")
|
118 |
+
|
|
|
119 |
btn = gr.Button("Run Document Segmentation")
|
120 |
+
btn.click(fn=process_image, inputs=[input_image, model_choice], outputs=[output_image, output_text])
|
121 |
|
122 |
# Launch the demo with queuing
|
123 |
demo.queue(max_size=1).launch()
|