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