StarAtNyte1 commited on
Commit
91c3ba2
1 Parent(s): fb9bd11

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +194 -0
app.py CHANGED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+
4
+ import argparse
5
+ import time
6
+ from pathlib import Path
7
+
8
+ import cv2
9
+ import torch
10
+ import torch.backends.cudnn as cudnn
11
+ from numpy import random
12
+
13
+ from models.experimental import attempt_load
14
+ from utils.datasets import LoadStreams, LoadImages
15
+ from utils.general import check_img_size, check_requirements, check_imshow, non_max_suppression, apply_classifier, \
16
+ scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path
17
+ from utils.plots import plot_one_box
18
+ from utils.torch_utils import select_device, load_classifier, time_synchronized, TracedModel
19
+ from PIL import Image
20
+
21
+ from huggingface_hub import hf_hub_download
22
+
23
+
24
+ def load_model():
25
+ model_path = hf_hub_download(repo_id=f"StarAtNyte1/yolov7_custom", filename=f"best.pt")
26
+
27
+ return model_path
28
+
29
+
30
+
31
+
32
+ models = {'best': load_model()}
33
+
34
+
35
+ def detect(img,model):
36
+ parser = argparse.ArgumentParser()
37
+ parser.add_argument('--weights', nargs='+', type=str, default=models[model], help='model.pt path(s)')
38
+ parser.add_argument('--source', type=str, default='Inference/', help='source') # file/folder, 0 for webcam
39
+ parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
40
+ parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold')
41
+ parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
42
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
43
+ parser.add_argument('--view-img', action='store_true', help='display results')
44
+ parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
45
+ parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
46
+ parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
47
+ parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
48
+ parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
49
+ parser.add_argument('--augment', action='store_true', help='augmented inference')
50
+ parser.add_argument('--update', action='store_true', help='update all models')
51
+ parser.add_argument('--project', default='runs/detect', help='save results to project/name')
52
+ parser.add_argument('--name', default='exp', help='save results to project/name')
53
+ parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
54
+ parser.add_argument('--trace', action='store_true', help='trace model')
55
+ opt = parser.parse_args()
56
+ img.save("Inference/test.jpg")
57
+ source, weights, view_img, save_txt, imgsz, trace = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size, opt.trace
58
+ save_img = True # save inference images
59
+ webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
60
+ ('rtsp://', 'rtmp://', 'http://', 'https://'))
61
+
62
+ # Directories
63
+ save_dir = Path(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok)) # increment run
64
+ (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
65
+
66
+ # Initialize
67
+ set_logging()
68
+ device = select_device(opt.device)
69
+ half = device.type != 'cpu' # half precision only supported on CUDA
70
+
71
+ # Load model
72
+ model = attempt_load(weights, map_location=device) # load FP32 model
73
+ stride = int(model.stride.max()) # model stride
74
+ imgsz = check_img_size(imgsz, s=stride) # check img_size
75
+
76
+ if trace:
77
+ model = TracedModel(model, device, opt.img_size)
78
+
79
+ if half:
80
+ model.half() # to FP16
81
+
82
+ # Second-stage classifier
83
+ classify = False
84
+ if classify:
85
+ modelc = load_classifier(name='resnet101', n=2) # initialize
86
+ modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']).to(device).eval()
87
+
88
+ # Set Dataloader
89
+ vid_path, vid_writer = None, None
90
+ if webcam:
91
+ view_img = check_imshow()
92
+ cudnn.benchmark = True # set True to speed up constant image size inference
93
+ dataset = LoadStreams(source, img_size=imgsz, stride=stride)
94
+ else:
95
+ dataset = LoadImages(source, img_size=imgsz, stride=stride)
96
+
97
+ # Get names and colors
98
+ names = model.module.names if hasattr(model, 'module') else model.names
99
+ colors = [[random.randint(0, 255) for _ in range(3)] for _ in names]
100
+
101
+ # Run inference
102
+ if device.type != 'cpu':
103
+ model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
104
+ t0 = time.time()
105
+ for path, img, im0s, vid_cap in dataset:
106
+ img = torch.from_numpy(img).to(device)
107
+ img = img.half() if half else img.float() # uint8 to fp16/32
108
+ img /= 255.0 # 0 - 255 to 0.0 - 1.0
109
+ if img.ndimension() == 3:
110
+ img = img.unsqueeze(0)
111
+
112
+ # Inference
113
+ t1 = time_synchronized()
114
+ pred = model(img, augment=opt.augment)[0]
115
+
116
+ # Apply NMS
117
+ pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)
118
+ t2 = time_synchronized()
119
+
120
+ # Apply Classifier
121
+ if classify:
122
+ pred = apply_classifier(pred, modelc, img, im0s)
123
+
124
+ # Process detections
125
+ for i, det in enumerate(pred): # detections per image
126
+ if webcam: # batch_size >= 1
127
+ p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count
128
+ else:
129
+ p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0)
130
+
131
+ p = Path(p) # to Path
132
+ save_path = str(save_dir / p.name) # img.jpg
133
+ txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
134
+ s += '%gx%g ' % img.shape[2:] # print string
135
+ gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
136
+ if len(det):
137
+ # Rescale boxes from img_size to im0 size
138
+ det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
139
+
140
+ # Print results
141
+ for c in det[:, -1].unique():
142
+ n = (det[:, -1] == c).sum() # detections per class
143
+ s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
144
+
145
+ # Write results
146
+ for *xyxy, conf, cls in reversed(det):
147
+ if save_txt: # Write to file
148
+ xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
149
+ line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh) # label format
150
+ with open(txt_path + '.txt', 'a') as f:
151
+ f.write(('%g ' * len(line)).rstrip() % line + '\n')
152
+
153
+ if save_img or view_img: # Add bbox to image
154
+ label = f'{names[int(cls)]} {conf:.2f}'
155
+ plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)
156
+
157
+ # Print time (inference + NMS)
158
+ #print(f'{s}Done. ({t2 - t1:.3f}s)')
159
+
160
+ # Stream results
161
+ if view_img:
162
+ cv2.imshow(str(p), im0)
163
+ cv2.waitKey(1) # 1 millisecond
164
+
165
+ # Save results (image with detections)
166
+ if save_img:
167
+ if dataset.mode == 'image':
168
+ cv2.imwrite(save_path, im0)
169
+ else: # 'video' or 'stream'
170
+ if vid_path != save_path: # new video
171
+ vid_path = save_path
172
+ if isinstance(vid_writer, cv2.VideoWriter):
173
+ vid_writer.release() # release previous video writer
174
+ if vid_cap: # video
175
+ fps = vid_cap.get(cv2.CAP_PROP_FPS)
176
+ w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
177
+ h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
178
+ else: # stream
179
+ fps, w, h = 30, im0.shape[1], im0.shape[0]
180
+ save_path += '.mp4'
181
+ vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
182
+ vid_writer.write(im0)
183
+
184
+ if save_txt or save_img:
185
+ s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
186
+ #print(f"Results saved to {save_dir}{s}")
187
+
188
+ print(f'Done. ({time.time() - t0:.3f}s)')
189
+
190
+ return Image.fromarray(im0[:,:,::-1])
191
+
192
+
193
+ gr.Interface(detect,[gr.Image(type="pil"),gr.Dropdown(choices='yolov7')], gr.Image(type="pil"),title="Yolov7").launch()
194
+