hysts HF staff commited on
Commit
0795e9e
1 Parent(s): c783dfd
Files changed (4) hide show
  1. .gitmodules +3 -0
  2. app.py +190 -0
  3. insightface +1 -0
  4. requirements.txt +9 -0
.gitmodules ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [submodule "insightface"]
2
+ path = insightface
3
+ url = https://github.com/deepinsight/insightface
app.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import functools
7
+ import os
8
+ import pathlib
9
+ import subprocess
10
+ import sys
11
+ import urllib.request
12
+
13
+ if os.environ.get('SYSTEM') == 'spaces':
14
+ import mim
15
+ mim.install('mmcv-full==1.3.3', is_yes=True)
16
+
17
+ subprocess.call('pip uninstall -y opencv-python'.split())
18
+ subprocess.call('pip uninstall -y opencv-python-headless'.split())
19
+ subprocess.call('pip install opencv-python-headless==4.5.5.64'.split())
20
+ subprocess.call('pip install terminaltables==3.1.0'.split())
21
+ subprocess.call('pip install mmpycocotools==12.0.3'.split())
22
+
23
+ subprocess.call('pip install insightface==0.6.2'.split())
24
+
25
+
26
+ import cv2
27
+ import gradio as gr
28
+ import huggingface_hub
29
+ import numpy as np
30
+ import torch
31
+ import torch.nn as nn
32
+
33
+ sys.path.insert(0, 'insightface/detection/scrfd')
34
+
35
+ from mmdet.apis import inference_detector, init_detector, show_result_pyplot
36
+
37
+ REPO_URL = 'https://github.com/deepinsight/insightface/tree/master/detection/scrfd'
38
+ TITLE = 'insightface Face Detection (SCRFD)'
39
+ DESCRIPTION = f'This is a demo for {REPO_URL}.'
40
+ ARTICLE = None
41
+
42
+ TOKEN = os.environ['TOKEN']
43
+
44
+
45
+ def parse_args() -> argparse.Namespace:
46
+ parser = argparse.ArgumentParser()
47
+ parser.add_argument('--face-score-slider-step', type=float, default=0.05)
48
+ parser.add_argument('--face-score-threshold', type=float, default=0.3)
49
+ parser.add_argument('--device', type=str, default='cpu')
50
+ parser.add_argument('--theme', type=str)
51
+ parser.add_argument('--live', action='store_true')
52
+ parser.add_argument('--share', action='store_true')
53
+ parser.add_argument('--port', type=int)
54
+ parser.add_argument('--disable-queue',
55
+ dest='enable_queue',
56
+ action='store_false')
57
+ parser.add_argument('--allow-flagging', type=str, default='never')
58
+ parser.add_argument('--allow-screenshot', action='store_true')
59
+ return parser.parse_args()
60
+
61
+
62
+ def load_model(model_size: str, device) -> nn.Module:
63
+ ckpt_path = huggingface_hub.hf_hub_download(
64
+ 'hysts/insightface',
65
+ f'models/scrfd_{model_size}/model.pth',
66
+ use_auth_token=TOKEN)
67
+ scrfd_dir = 'insightface/detection/scrfd'
68
+ config_path = f'{scrfd_dir}/configs/scrfd/scrfd_{model_size}.py'
69
+ model = init_detector(config_path, ckpt_path, device.type)
70
+ return model
71
+
72
+
73
+ def update_test_pipeline(model: nn.Module, mode: int):
74
+ cfg = model.cfg
75
+ pipelines = cfg.data.test.pipeline
76
+ for pipeline in pipelines:
77
+ if pipeline.type == 'MultiScaleFlipAug':
78
+ if mode == 0: #640 scale
79
+ pipeline.img_scale = (640, 640)
80
+ if hasattr(pipeline, 'scale_factor'):
81
+ del pipeline.scale_factor
82
+ elif mode == 1: #for single scale in other pages
83
+ pipeline.img_scale = (1100, 1650)
84
+ if hasattr(pipeline, 'scale_factor'):
85
+ del pipeline.scale_factor
86
+ elif mode == 2: #original scale
87
+ pipeline.img_scale = None
88
+ pipeline.scale_factor = 1.0
89
+ transforms = pipeline.transforms
90
+ for transform in transforms:
91
+ if transform.type == 'Pad':
92
+ if mode != 2:
93
+ transform.size = pipeline.img_scale
94
+ if hasattr(transform, 'size_divisor'):
95
+ del transform.size_divisor
96
+ else:
97
+ transform.size = None
98
+ transform.size_divisor = 32
99
+
100
+
101
+ def detect(image: np.ndarray, model_size: str, mode: int,
102
+ face_score_threshold: float,
103
+ detectors: dict[str, nn.Module]) -> np.ndarray:
104
+ model = detectors[model_size]
105
+ update_test_pipeline(model, mode)
106
+
107
+ # RGB -> BGR
108
+ image = image[:, :, ::-1]
109
+ preds = inference_detector(model, image)
110
+ boxes = preds[0]
111
+
112
+ res = image.copy()
113
+ for box in boxes:
114
+ box, score = box[:4], box[4]
115
+ if score < face_score_threshold:
116
+ continue
117
+ box = np.round(box).astype(int)
118
+
119
+ line_width = max(2, int(3 * (box[2:] - box[:2]).max() / 256))
120
+ cv2.rectangle(res, tuple(box[:2]), tuple(box[2:]), (0, 255, 0),
121
+ line_width)
122
+
123
+ res = cv2.cvtColor(res, cv2.COLOR_BGR2RGB)
124
+ return res
125
+
126
+
127
+ def main():
128
+ gr.close_all()
129
+
130
+ args = parse_args()
131
+ device = torch.device(args.device)
132
+
133
+ model_sizes = [
134
+ '500m',
135
+ '1g',
136
+ '2.5g',
137
+ '10g',
138
+ '34g',
139
+ ]
140
+ detectors = {
141
+ model_size: load_model(model_size, device=device)
142
+ for model_size in model_sizes
143
+ }
144
+ modes = [
145
+ '(640, 640)',
146
+ '(1100, 1650)',
147
+ 'original',
148
+ ]
149
+
150
+ func = functools.partial(detect, detectors=detectors)
151
+ func = functools.update_wrapper(func, detect)
152
+
153
+ image_path = pathlib.Path('selfie.jpg')
154
+ if not image_path.exists():
155
+ url = 'https://raw.githubusercontent.com/peiyunh/tiny/master/data/demo/selfie.jpg'
156
+ urllib.request.urlretrieve(url, image_path)
157
+ examples = [[image_path.as_posix(), '10g', modes[0], 0.3]]
158
+
159
+ gr.Interface(
160
+ func,
161
+ [
162
+ gr.inputs.Image(type='numpy', label='Input'),
163
+ gr.inputs.Radio(
164
+ model_sizes, type='value', default='10g', label='Model'),
165
+ gr.inputs.Radio(
166
+ modes, type='index', default=modes[0], label='Mode'),
167
+ gr.inputs.Slider(0,
168
+ 1,
169
+ step=args.face_score_slider_step,
170
+ default=args.face_score_threshold,
171
+ label='Face Score Threshold'),
172
+ ],
173
+ gr.outputs.Image(type='numpy', label='Output'),
174
+ examples=examples,
175
+ title=TITLE,
176
+ description=DESCRIPTION,
177
+ article=ARTICLE,
178
+ theme=args.theme,
179
+ allow_screenshot=args.allow_screenshot,
180
+ allow_flagging=args.allow_flagging,
181
+ live=args.live,
182
+ ).launch(
183
+ enable_queue=args.enable_queue,
184
+ server_port=args.port,
185
+ share=args.share,
186
+ )
187
+
188
+
189
+ if __name__ == '__main__':
190
+ main()
insightface ADDED
@@ -0,0 +1 @@
 
 
1
+ Subproject commit eca1d9a6cd25653067e7293e27b8a2d0d2cd5415
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ Cython==0.29.28
2
+ #insightface==0.6.2
3
+ #mmcv-full==1.3.3
4
+ numpy==1.22.3
5
+ onnxruntime==1.11.0
6
+ opencv-python-headless==4.5.5.64
7
+ openmim==0.1.5
8
+ torch==1.10.2
9
+ torchvision==0.11.3