Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,16 +1,16 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
|
8 |
import gradio as gr
|
9 |
-
|
10 |
from PIL import Image
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
import numpy as np
|
15 |
|
16 |
# BASE_DIR = "/home/user/app"
|
@@ -18,200 +18,207 @@ import numpy as np
|
|
18 |
# os.makedirs(f"{BASE_DIR}/input",exist_ok=True)
|
19 |
# os.system(f"git clone https://github.com/WongKinYiu/yolov7.git {BASE_DIR}/yolov7")
|
20 |
# sys.path.append(f'{BASE_DIR}/yolov7')
|
|
|
21 |
|
22 |
-
|
23 |
# from models.experimental import attempt_load
|
24 |
# from utils.datasets import LoadStreams, LoadImages
|
25 |
# from utils.general import check_img_size, check_requirements, check_imshow, non_max_suppression, apply_classifier, \
|
26 |
# scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path
|
27 |
# from utils.plots import plot_one_box
|
28 |
# from utils.torch_utils import select_device, load_classifier, time_synchronized, TracedModel
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
def get_output(input_image):
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
return input_image
|
216 |
|
217 |
|
|
|
1 |
+
import os
|
2 |
+
import sys
|
3 |
+
import argparse
|
4 |
+
import time
|
5 |
+
from pathlib import Path
|
6 |
+
import pandas as pd
|
7 |
|
8 |
import gradio as gr
|
9 |
+
import cv2
|
10 |
from PIL import Image
|
11 |
+
import torch
|
12 |
+
import torch.backends.cudnn as cudnn
|
13 |
+
from numpy import random
|
14 |
import numpy as np
|
15 |
|
16 |
# BASE_DIR = "/home/user/app"
|
|
|
18 |
# os.makedirs(f"{BASE_DIR}/input",exist_ok=True)
|
19 |
# os.system(f"git clone https://github.com/WongKinYiu/yolov7.git {BASE_DIR}/yolov7")
|
20 |
# sys.path.append(f'{BASE_DIR}/yolov7')
|
21 |
+
os.system("pip install yolov7-package==0.0.12")
|
22 |
|
23 |
+
def detect(opt, save_img=False):
|
24 |
# from models.experimental import attempt_load
|
25 |
# from utils.datasets import LoadStreams, LoadImages
|
26 |
# from utils.general import check_img_size, check_requirements, check_imshow, non_max_suppression, apply_classifier, \
|
27 |
# scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path
|
28 |
# from utils.plots import plot_one_box
|
29 |
# from utils.torch_utils import select_device, load_classifier, time_synchronized, TracedModel
|
30 |
+
|
31 |
+
from yolov7_package.models.experimental import attempt_load
|
32 |
+
from yolov7_package.utils.general import check_img_size, check_requirements, check_imshow, non_max_suppression, apply_classifier, \
|
33 |
+
scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path
|
34 |
+
from yolov7_package.utils.torch_utils import select_device, load_classifier, time_synchronized, TracedModel
|
35 |
+
from yolov7_package.utils.datasets import LoadStreams, LoadImages
|
36 |
|
37 |
+
bbox = {}
|
38 |
+
source, weights, view_img, save_txt, imgsz, trace = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size, not opt.no_trace
|
39 |
+
save_img = not opt.nosave and not source.endswith('.txt') # save inference images
|
40 |
+
webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
|
41 |
+
('rtsp://', 'rtmp://', 'http://', 'https://'))
|
42 |
+
|
43 |
+
# Directories
|
44 |
+
save_dir = Path(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok)) # increment run
|
45 |
+
(save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
|
46 |
+
|
47 |
+
# Initialize
|
48 |
+
set_logging()
|
49 |
+
device = select_device(opt.device)
|
50 |
+
half = device.type != 'cpu' # half precision only supported on CUDA
|
51 |
+
|
52 |
+
# Load model
|
53 |
+
model = attempt_load(weights, map_location=device) # load FP32 model
|
54 |
+
stride = int(model.stride.max()) # model stride
|
55 |
+
imgsz = check_img_size(imgsz, s=stride) # check img_size
|
56 |
+
|
57 |
+
if trace:
|
58 |
+
model = TracedModel(model, device, opt.img_size)
|
59 |
+
|
60 |
+
if half:
|
61 |
+
model.half() # to FP16
|
62 |
+
|
63 |
+
# Second-stage classifier
|
64 |
+
classify = False
|
65 |
+
if classify:
|
66 |
+
modelc = load_classifier(name='resnet101', n=2) # initialize
|
67 |
+
modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']).to(device).eval()
|
68 |
+
|
69 |
+
# Set Dataloader
|
70 |
+
vid_path, vid_writer = None, None
|
71 |
+
if webcam:
|
72 |
+
view_img = check_imshow()
|
73 |
+
cudnn.benchmark = True # set True to speed up constant image size inference
|
74 |
+
dataset = LoadStreams(source, img_size=imgsz, stride=stride)
|
75 |
+
else:
|
76 |
+
dataset = LoadImages(source, img_size=imgsz, stride=stride)
|
77 |
+
|
78 |
+
# Get names and colors
|
79 |
+
names = model.module.names if hasattr(model, 'module') else model.names
|
80 |
+
colors = [[random.randint(0, 255) for _ in range(3)] for _ in names]
|
81 |
+
|
82 |
+
# Run inference
|
83 |
+
if device.type != 'cpu':
|
84 |
+
model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
|
85 |
+
old_img_w = old_img_h = imgsz
|
86 |
+
old_img_b = 1
|
87 |
+
|
88 |
+
t0 = time.time()
|
89 |
+
for path, img, im0s, vid_cap in dataset:
|
90 |
+
img = torch.from_numpy(img).to(device)
|
91 |
+
img = img.half() if half else img.float() # uint8 to fp16/32
|
92 |
+
img /= 255.0 # 0 - 255 to 0.0 - 1.0
|
93 |
+
if img.ndimension() == 3:
|
94 |
+
img = img.unsqueeze(0)
|
95 |
+
|
96 |
+
# Warmup
|
97 |
+
if device.type != 'cpu' and (old_img_b != img.shape[0] or old_img_h != img.shape[2] or old_img_w != img.shape[3]):
|
98 |
+
old_img_b = img.shape[0]
|
99 |
+
old_img_h = img.shape[2]
|
100 |
+
old_img_w = img.shape[3]
|
101 |
+
for i in range(3):
|
102 |
+
model(img, augment=opt.augment)[0]
|
103 |
+
|
104 |
+
# Inference
|
105 |
+
t1 = time_synchronized()
|
106 |
+
with torch.no_grad(): # Calculating gradients would cause a GPU memory leak
|
107 |
+
pred = model(img, augment=opt.augment)[0]
|
108 |
+
t2 = time_synchronized()
|
109 |
+
|
110 |
+
# Apply NMS
|
111 |
+
pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)
|
112 |
+
t3 = time_synchronized()
|
113 |
+
|
114 |
+
# Apply Classifier
|
115 |
+
if classify:
|
116 |
+
pred = apply_classifier(pred, modelc, img, im0s)
|
117 |
+
|
118 |
+
# Process detections
|
119 |
+
for i, det in enumerate(pred): # detections per image
|
120 |
+
if webcam: # batch_size >= 1
|
121 |
+
p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count
|
122 |
+
else:
|
123 |
+
p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0)
|
124 |
+
|
125 |
+
p = Path(p) # to Path
|
126 |
+
save_path = str(save_dir / p.name) # img.jpg
|
127 |
+
txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
|
128 |
+
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
|
129 |
+
if len(det):
|
130 |
+
# Rescale boxes from img_size to im0 size
|
131 |
+
det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
|
132 |
+
# print(f"BOXES ---->>>> {det[:, :4]}")
|
133 |
+
bbox[f"{txt_path.split('/')[4]}"]=(det[:, :4]).numpy()
|
134 |
+
|
135 |
+
# Print results
|
136 |
+
for c in det[:, -1].unique():
|
137 |
+
n = (det[:, -1] == c).sum() # detections per class
|
138 |
+
s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
|
139 |
+
|
140 |
+
# Write results
|
141 |
+
for *xyxy, conf, cls in reversed(det):
|
142 |
+
if save_txt: # Write to file
|
143 |
+
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
|
144 |
+
line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh) # label format
|
145 |
+
with open(txt_path + '.txt', 'a') as f:
|
146 |
+
f.write(('%g ' * len(line)).rstrip() % line + '\n')
|
147 |
+
|
148 |
+
if save_img or view_img: # Add bbox to image
|
149 |
+
label = f'{names[int(cls)]} {conf:.2f}'
|
150 |
+
plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=1)
|
151 |
+
|
152 |
+
# Print time (inference + NMS)
|
153 |
+
print(f'{s}Done. ({(1E3 * (t2 - t1)):.1f}ms) Inference, ({(1E3 * (t3 - t2)):.1f}ms) NMS')
|
154 |
+
|
155 |
+
# Stream results
|
156 |
+
# if view_img:
|
157 |
+
# cv2.imshow(str(p), im0)
|
158 |
+
# cv2.waitKey(1) # 1 millisecond
|
159 |
+
|
160 |
+
# Save results (image with detections)
|
161 |
+
if save_img:
|
162 |
+
if dataset.mode == 'image':
|
163 |
+
# Image.fromarray(im0).show()
|
164 |
+
cv2.imwrite(save_path, im0)
|
165 |
+
print(f" The image with the result is saved in: {save_path}")
|
166 |
+
# else: # 'video' or 'stream'
|
167 |
+
# if vid_path != save_path: # new video
|
168 |
+
# vid_path = save_path
|
169 |
+
# if isinstance(vid_writer, cv2.VideoWriter):
|
170 |
+
# vid_writer.release() # release previous video writer
|
171 |
+
# if vid_cap: # video
|
172 |
+
# fps = vid_cap.get(cv2.CAP_PROP_FPS)
|
173 |
+
# w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
174 |
+
# h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
175 |
+
# else: # stream
|
176 |
+
# fps, w, h = 30, im0.shape[1], im0.shape[0]
|
177 |
+
# save_path += '.mp4'
|
178 |
+
# vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
|
179 |
+
# vid_writer.write(im0)
|
180 |
+
|
181 |
+
if save_txt or save_img:
|
182 |
+
s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
|
183 |
+
#print(f"Results saved to {save_dir}{s}")
|
184 |
+
|
185 |
+
print(f'Done. ({time.time() - t0:.3f}s)')
|
186 |
+
return bbox,save_path
|
187 |
+
|
188 |
+
class options:
|
189 |
+
def __init__(self, weights, source, img_size=640, conf_thres=0.1, iou_thres=0.45, device='',
|
190 |
+
view_img=False, save_txt=False, save_conf=False, nosave=False, classes=None,
|
191 |
+
agnostic_nms=False, augment=False, update=False, project='runs/detect', name='exp',
|
192 |
+
exist_ok=False, no_trace=False):
|
193 |
+
self.weights=weights
|
194 |
+
self.source=source
|
195 |
+
self.img_size=img_size
|
196 |
+
self.conf_thres=conf_thres
|
197 |
+
self.iou_thres=iou_thres
|
198 |
+
self.device=device
|
199 |
+
self.view_img=view_img
|
200 |
+
self.save_txt=save_txt
|
201 |
+
self.save_conf=save_conf
|
202 |
+
self.nosave=nosave
|
203 |
+
self.classes=classes
|
204 |
+
self.agnostic_nms=agnostic_nms
|
205 |
+
self.augment=augment
|
206 |
+
self.update=update
|
207 |
+
self.project=project
|
208 |
+
self.name=name
|
209 |
+
self.exist_ok=exist_ok
|
210 |
+
self.no_trace=no_trace
|
211 |
|
212 |
def get_output(input_image):
|
213 |
+
image.save(f"{BASE_DIR}/input/image.jpg")
|
214 |
+
source = f"{BASE_DIR}/input"
|
215 |
+
opt = options(weights='logo_detection.pt',source=source)
|
216 |
+
bbox = None
|
217 |
+
with torch.no_grad():
|
218 |
+
bbox,output_path = detect(opt)
|
219 |
+
if os.path.exists(output_path):
|
220 |
+
return np.array(Image.open(output_path))
|
221 |
+
else:
|
222 |
return input_image
|
223 |
|
224 |
|