narugo commited on
Commit
92125df
1 Parent(s): 5879f7c

dev(narugo): upgrade this space

Browse files
Files changed (15) hide show
  1. README.md +8 -0
  2. app.py +32 -201
  3. app2.py +0 -34
  4. censor.py +0 -47
  5. detection/halfbody.py +33 -0
  6. eye.py +0 -50
  7. face.py +0 -52
  8. halfbody.py +0 -44
  9. hand.py +0 -49
  10. head.py +0 -43
  11. manbits.py +0 -45
  12. onnx_.py +0 -59
  13. person.py +0 -46
  14. plot.py +0 -76
  15. yolo_.py +0 -110
README.md CHANGED
@@ -8,6 +8,14 @@ sdk_version: 4.44.0
8
  app_file: app.py
9
  pinned: false
10
  license: mit
 
 
 
 
 
 
 
 
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
8
  app_file: app.py
9
  pinned: false
10
  license: mit
11
+ models:
12
+ - deepghs/anime_face_detection
13
+ - deepghs/anime_censor_detection
14
+ - deepghs/anime_eye_detection
15
+ - deepghs/anime_halfbody_detection
16
+ - deepghs/anime_hand_detection
17
+ - deepghs/anime_head_detection
18
+ - deepghs/anime_person_detection
19
  ---
20
 
21
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py CHANGED
@@ -2,208 +2,39 @@ import os
2
 
3
  import gradio as gr
4
 
5
- from censor import _CENSOR_MODELS, _DEFAULT_CENSOR_MODEL, _gr_detect_censors
6
- from eye import _EYE_MODELS, _DEFAULT_EYE_MODEL, _gr_detect_eyes
7
- from face import _FACE_MODELS, _DEFAULT_FACE_MODEL, _gr_detect_faces
8
- from halfbody import _HALFBODY_MODELS, _DEFAULT_HALFBODY_MODEL, _gr_detect_halfbodies
9
- from hand import _gr_detect_hands, _HAND_MODELS, _DEFAULT_HAND_MODEL
10
- from head import _gr_detect_heads, _HEAD_MODELS, _DEFAULT_HEAD_MODEL
11
- from manbits import _MANBIT_MODELS, _DEFAULT_MANBIT_MODEL, _gr_detect_manbits
12
- from person import _PERSON_MODELS, _DEFAULT_PERSON_MODEL, _gr_detect_person
13
 
14
- if __name__ == '__main__':
15
- with gr.Blocks() as demo:
16
- with gr.Tabs():
17
- with gr.Tab('Face Detection'):
18
- with gr.Row():
19
- with gr.Column():
20
- gr_face_input_image = gr.Image(type='pil', label='Original Image')
21
- gr_face_model = gr.Dropdown(_FACE_MODELS, value=_DEFAULT_FACE_MODEL, label='Model')
22
- gr_face_infer_size = gr.Slider(480, 960, value=640, step=32, label='Max Infer Size')
23
- with gr.Row():
24
- gr_face_iou_threshold = gr.Slider(0.0, 1.0, 0.7, label='IOU Threshold')
25
- gr_face_score_threshold = gr.Slider(0.0, 1.0, 0.25, label='Score Threshold')
26
-
27
- gr_face_submit = gr.Button(value='Submit', variant='primary')
28
-
29
- with gr.Column():
30
- gr_face_output_image = gr.Image(type='pil', label="Labeled")
31
-
32
- gr_face_submit.click(
33
- _gr_detect_faces,
34
- inputs=[
35
- gr_face_input_image, gr_face_model,
36
- gr_face_infer_size, gr_face_score_threshold, gr_face_iou_threshold,
37
- ],
38
- outputs=[gr_face_output_image],
39
- )
40
-
41
- with gr.Tab('Head Detection'):
42
- with gr.Row():
43
- with gr.Column():
44
- gr_head_input_image = gr.Image(type='pil', label='Original Image')
45
- gr_head_model = gr.Dropdown(_HEAD_MODELS, value=_DEFAULT_HEAD_MODEL, label='Model')
46
- gr_head_infer_size = gr.Slider(480, 960, value=640, step=32, label='Max Infer Size')
47
- with gr.Row():
48
- gr_head_iou_threshold = gr.Slider(0.0, 1.0, 0.7, label='IOU Threshold')
49
- gr_head_score_threshold = gr.Slider(0.0, 1.0, 0.3, label='Score Threshold')
50
-
51
- gr_head_submit = gr.Button(value='Submit', variant='primary')
52
-
53
- with gr.Column():
54
- gr_head_output_image = gr.Image(type='pil', label="Labeled")
55
-
56
- gr_head_submit.click(
57
- _gr_detect_heads,
58
- inputs=[
59
- gr_head_input_image, gr_head_model,
60
- gr_head_infer_size, gr_head_score_threshold, gr_head_iou_threshold,
61
- ],
62
- outputs=[gr_head_output_image],
63
- )
64
-
65
- with gr.Tab('Person Detection'):
66
- with gr.Row():
67
- with gr.Column():
68
- gr_person_input_image = gr.Image(type='pil', label='Original Image')
69
- gr_person_model = gr.Dropdown(_PERSON_MODELS, value=_DEFAULT_PERSON_MODEL, label='Model')
70
- gr_person_infer_size = gr.Slider(480, 960, value=640, step=32, label='Max Infer Size')
71
- with gr.Row():
72
- gr_person_iou_threshold = gr.Slider(0.0, 1.0, 0.5, label='IOU Threshold')
73
- gr_person_score_threshold = gr.Slider(0.0, 1.0, 0.3, label='Score Threshold')
74
-
75
- gr_person_submit = gr.Button(value='Submit', variant='primary')
76
-
77
- with gr.Column():
78
- gr_person_output_image = gr.Image(type='pil', label="Labeled")
79
-
80
- gr_person_submit.click(
81
- _gr_detect_person,
82
- inputs=[
83
- gr_person_input_image, gr_person_model,
84
- gr_person_infer_size, gr_person_score_threshold, gr_person_iou_threshold,
85
- ],
86
- outputs=[gr_person_output_image],
87
- )
88
-
89
- with gr.Tab('Half Body Detection'):
90
- with gr.Row():
91
- with gr.Column():
92
- gr_halfbody_input_image = gr.Image(type='pil', label='Original Image')
93
- gr_halfbody_model = gr.Dropdown(_HALFBODY_MODELS, value=_DEFAULT_HALFBODY_MODEL, label='Model')
94
- gr_halfbody_infer_size = gr.Slider(480, 960, value=640, step=32, label='Max Infer Size')
95
- with gr.Row():
96
- gr_halfbody_iou_threshold = gr.Slider(0.0, 1.0, 0.7, label='IOU Threshold')
97
- gr_halfbody_score_threshold = gr.Slider(0.0, 1.0, 0.25, label='Score Threshold')
98
-
99
- gr_halfbody_submit = gr.Button(value='Submit', variant='primary')
100
-
101
- with gr.Column():
102
- gr_halfbody_output_image = gr.Image(type='pil', label="Labeled")
103
-
104
- gr_halfbody_submit.click(
105
- _gr_detect_halfbodies,
106
- inputs=[
107
- gr_halfbody_input_image, gr_halfbody_model,
108
- gr_halfbody_infer_size, gr_halfbody_score_threshold, gr_halfbody_iou_threshold,
109
- ],
110
- outputs=[gr_halfbody_output_image],
111
- )
112
 
113
- with gr.Tab('Eyes Detection'):
114
- with gr.Row():
115
- with gr.Column():
116
- gr_eye_input_image = gr.Image(type='pil', label='Original Image')
117
- gr_eye_model = gr.Dropdown(_EYE_MODELS, value=_DEFAULT_EYE_MODEL, label='Model')
118
- gr_eye_infer_size = gr.Slider(480, 960, value=640, step=32, label='Max Infer Size')
119
- with gr.Row():
120
- gr_eye_iou_threshold = gr.Slider(0.0, 1.0, 0.3, label='IOU Threshold')
121
- gr_eye_score_threshold = gr.Slider(0.0, 1.0, 0.3, label='Score Threshold')
122
-
123
- gr_eye_submit = gr.Button(value='Submit', variant='primary')
124
-
125
- with gr.Column():
126
- gr_eye_output_image = gr.Image(type='pil', label="Labeled")
127
-
128
- gr_eye_submit.click(
129
- _gr_detect_eyes,
130
- inputs=[
131
- gr_eye_input_image, gr_eye_model,
132
- gr_eye_infer_size, gr_eye_score_threshold, gr_eye_iou_threshold,
133
- ],
134
- outputs=[gr_eye_output_image],
135
- )
136
-
137
- with gr.Tab('Hand Detection'):
138
- with gr.Row():
139
- with gr.Column():
140
- gr_hand_input_image = gr.Image(type='pil', label='Original Image')
141
- gr_hand_model = gr.Dropdown(_HAND_MODELS, value=_DEFAULT_HAND_MODEL, label='Model')
142
- gr_hand_infer_size = gr.Slider(480, 960, value=640, step=32, label='Max Infer Size')
143
- with gr.Row():
144
- gr_hand_iou_threshold = gr.Slider(0.0, 1.0, 0.7, label='IOU Threshold')
145
- gr_hand_score_threshold = gr.Slider(0.0, 1.0, 0.35, label='Score Threshold')
146
-
147
- gr_hand_submit = gr.Button(value='Submit', variant='primary')
148
-
149
- with gr.Column():
150
- gr_hand_output_image = gr.Image(type='pil', label="Labeled")
151
-
152
- gr_hand_submit.click(
153
- _gr_detect_hands,
154
- inputs=[
155
- gr_hand_input_image, gr_hand_model,
156
- gr_hand_infer_size, gr_hand_score_threshold, gr_hand_iou_threshold,
157
- ],
158
- outputs=[gr_hand_output_image],
159
- )
160
-
161
- with gr.Tab('Censor Point Detection'):
162
- with gr.Row():
163
- with gr.Column():
164
- gr_censor_input_image = gr.Image(type='pil', label='Original Image')
165
- gr_censor_model = gr.Dropdown(_CENSOR_MODELS, value=_DEFAULT_CENSOR_MODEL, label='Model')
166
- gr_censor_infer_size = gr.Slider(480, 960, value=640, step=32, label='Max Infer Size')
167
- with gr.Row():
168
- gr_censor_iou_threshold = gr.Slider(0.0, 1.0, 0.5, label='IOU Threshold')
169
- gr_censor_score_threshold = gr.Slider(0.0, 1.0, 0.25, label='Score Threshold')
170
-
171
- gr_censor_submit = gr.Button(value='Submit', variant='primary')
172
-
173
- with gr.Column():
174
- gr_censor_output_image = gr.Image(type='pil', label="Labeled")
175
-
176
- gr_censor_submit.click(
177
- _gr_detect_censors,
178
- inputs=[
179
- gr_censor_input_image, gr_censor_model,
180
- gr_censor_infer_size, gr_censor_score_threshold, gr_censor_iou_threshold,
181
- ],
182
- outputs=[gr_censor_output_image],
183
- )
184
-
185
- with gr.Tab('Manbits Detection\n(Deprecated)'):
186
- with gr.Row():
187
- with gr.Column():
188
- gr_manbit_input_image = gr.Image(type='pil', label='Original Image')
189
- gr_manbit_model = gr.Dropdown(_MANBIT_MODELS, value=_DEFAULT_MANBIT_MODEL, label='Model')
190
- gr_manbit_infer_size = gr.Slider(480, 960, value=640, step=32, label='Max Infer Size')
191
- with gr.Row():
192
- gr_manbit_iou_threshold = gr.Slider(0.0, 1.0, 0.7, label='IOU Threshold')
193
- gr_manbit_score_threshold = gr.Slider(0.0, 1.0, 0.25, label='Score Threshold')
194
-
195
- gr_manbit_submit = gr.Button(value='Submit', variant='primary')
196
-
197
- with gr.Column():
198
- gr_manbit_output_image = gr.Image(type='pil', label="Labeled")
199
-
200
- gr_manbit_submit.click(
201
- _gr_detect_manbits,
202
- inputs=[
203
- gr_manbit_input_image, gr_manbit_model,
204
- gr_manbit_infer_size, gr_manbit_score_threshold, gr_manbit_iou_threshold,
205
- ],
206
- outputs=[gr_manbit_output_image],
207
- )
208
 
209
  demo.queue(os.cpu_count()).launch()
 
2
 
3
  import gradio as gr
4
 
5
+ from detection import EyesDetection, FaceDetection, HeadDetection, PersonDetection, HandDetection, CensorDetection, \
6
+ HalfBodyDetection
 
 
 
 
 
 
7
 
8
+ _GLOBAL_CSS = """
9
+ .limit-height {
10
+ max-height: 55vh;
11
+ }
12
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ if __name__ == '__main__':
15
+ with gr.Blocks(css=_GLOBAL_CSS) as demo:
16
+ with gr.Row():
17
+ with gr.Column():
18
+ gr.HTML('<h2 style="text-align: center;">Object Detections For Anime</h2>')
19
+ gr.Markdown('This is the online demo for detection functions of '
20
+ '[imgutils.detect](https://dghs-imgutils.deepghs.org/main/api_doc/detect/index.html). '
21
+ 'You can try them yourselves with `pip install dghs-imgutils`.')
22
+
23
+ with gr.Row():
24
+ with gr.Tabs():
25
+ with gr.Tab('Face Detection'):
26
+ FaceDetection().make_ui()
27
+ with gr.Tab('Head Detection'):
28
+ HeadDetection().make_ui()
29
+ with gr.Tab('Person Detection'):
30
+ PersonDetection().make_ui()
31
+ with gr.Tab('Half Body Detection'):
32
+ HalfBodyDetection().make_ui()
33
+ with gr.Tab('Eyes Detection'):
34
+ EyesDetection().make_ui()
35
+ with gr.Tab('Hand Detection'):
36
+ HandDetection().make_ui()
37
+ with gr.Tab('Censor Point Detection'):
38
+ CensorDetection().make_ui()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
  demo.queue(os.cpu_count()).launch()
app2.py DELETED
@@ -1,34 +0,0 @@
1
- import os
2
-
3
- import gradio as gr
4
-
5
- from detection import EyesDetection, FaceDetection, HeadDetection, PersonDetection, HandDetection, CensorDetection, \
6
- HalfBodyDetection
7
-
8
- _GLOBAL_CSS = """
9
- .limit-height {
10
- max-height: 55vh;
11
- }
12
- """
13
-
14
- if __name__ == '__main__':
15
- with gr.Blocks(css=_GLOBAL_CSS) as demo:
16
- with gr.Tabs():
17
- with gr.Tab('Face Detection'):
18
- FaceDetection().make_ui()
19
- with gr.Tab('Head Detection'):
20
- HeadDetection().make_ui()
21
- with gr.Tab('Person Detection'):
22
- PersonDetection().make_ui()
23
- with gr.Tab('Half Body Detection'):
24
- HalfBodyDetection().make_ui()
25
- with gr.Tab('Eyes Detection'):
26
- EyesDetection().make_ui()
27
- with gr.Tab('Hand Detection'):
28
- HandDetection().make_ui()
29
- with gr.Tab('Censor Point Detection'):
30
- CensorDetection().make_ui()
31
- with gr.Tab('Manbits Detection\n(Deprecated)'):
32
- pass
33
-
34
- demo.queue(os.cpu_count()).launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
censor.py DELETED
@@ -1,47 +0,0 @@
1
- from functools import lru_cache
2
- from typing import List, Tuple
3
-
4
- from huggingface_hub import hf_hub_download
5
- from imgutils.data import ImageTyping, load_image, rgb_encode
6
-
7
- from onnx_ import _open_onnx_model
8
- from plot import detection_visualize
9
- from yolo_ import _image_preprocess, _data_postprocess
10
-
11
- _CENSOR_MODELS = [
12
- 'censor_detect_v1.0_s',
13
- 'censor_detect_v1.0_n',
14
- 'censor_detect_v0.10_s',
15
- 'censor_detect_v0.9_s',
16
- 'censor_detect_v0.8_s',
17
- 'censor_detect_v0.7_s',
18
- ]
19
- _DEFAULT_CENSOR_MODEL = _CENSOR_MODELS[0]
20
-
21
-
22
- @lru_cache()
23
- def _open_censor_detect_model(model_name):
24
- return _open_onnx_model(hf_hub_download(
25
- f'deepghs/anime_censor_detection',
26
- f'{model_name}/model.onnx'
27
- ))
28
-
29
-
30
- _LABELS = ['nipple_f', 'penis', 'pussy']
31
-
32
-
33
- def detect_censors(image: ImageTyping, model_name: str, max_infer_size=640,
34
- conf_threshold: float = 0.25, iou_threshold: float = 0.5) \
35
- -> List[Tuple[Tuple[int, int, int, int], str, float]]:
36
- image = load_image(image, mode='RGB')
37
- new_image, old_size, new_size = _image_preprocess(image, max_infer_size)
38
-
39
- data = rgb_encode(new_image)[None, ...]
40
- output, = _open_censor_detect_model(model_name).run(['output0'], {'images': data})
41
- return _data_postprocess(output[0], conf_threshold, iou_threshold, old_size, new_size, _LABELS)
42
-
43
-
44
- def _gr_detect_censors(image: ImageTyping, model_name: str, max_infer_size=640,
45
- conf_threshold: float = 0.25, iou_threshold: float = 0.5):
46
- ret = detect_censors(image, model_name, max_infer_size, conf_threshold, iou_threshold)
47
- return detection_visualize(image, ret, _LABELS)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
detection/halfbody.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from typing import List, Tuple
3
+
4
+ from imgutils.data import ImageTyping
5
+ from imgutils.detect.halfbody import detect_halfbody, _LABELS
6
+
7
+ from .base import DeepGHSObjectDetection
8
+
9
+
10
+ def _parse_model_name(model_name: str):
11
+ matching = re.fullmatch(r'^halfbody_detect_(?P<version>[\s\S]+?)_(?P<level>[\s\S]+?)$', model_name)
12
+ return matching.group('version'), matching.group('level')
13
+
14
+
15
+ class HalfBodyDetection(DeepGHSObjectDetection):
16
+ def __init__(self):
17
+ DeepGHSObjectDetection.__init__(self, repo_id='deepghs/anime_halfbody_detection')
18
+
19
+ def _get_default_model(self) -> str:
20
+ return 'halfbody_detect_v1.0_s'
21
+
22
+ def _get_default_iou_and_score(self, model_name: str) -> Tuple[float, float]:
23
+ return 0.7, 0.5
24
+
25
+ def _get_labels(self, model_name: str) -> List[str]:
26
+ return _LABELS
27
+
28
+ def detect(self, image: ImageTyping, model_name: str,
29
+ iou_threshold: float = 0.7, score_threshold: float = 0.25) \
30
+ -> List[Tuple[Tuple[float, float, float, float], str, float]]:
31
+ version, level = _parse_model_name(model_name)
32
+ return detect_halfbody(image, level=level, version=version,
33
+ conf_threshold=score_threshold, iou_threshold=iou_threshold)
eye.py DELETED
@@ -1,50 +0,0 @@
1
- from functools import lru_cache
2
- from typing import List, Tuple
3
-
4
- from huggingface_hub import hf_hub_download
5
- from imgutils.data import ImageTyping, load_image, rgb_encode
6
-
7
- from onnx_ import _open_onnx_model
8
- from plot import detection_visualize
9
- from yolo_ import _image_preprocess, _data_postprocess
10
-
11
- _EYE_MODELS = [
12
- 'eye_detect_v1.0_s',
13
- 'eye_detect_v1.0_n',
14
- 'eye_detect_v0.8_s',
15
- 'eye_detect_v0.7_s',
16
- 'eye_detect_v0.6_s',
17
- 'eye_detect_v0.5_s',
18
- 'eye_detect_v0.4_s',
19
- 'eye_detect_v0.3_s',
20
- 'eye_detect_v0.2_s',
21
- ]
22
- _DEFAULT_EYE_MODEL = _EYE_MODELS[0]
23
-
24
-
25
- @lru_cache()
26
- def _open_eye_detect_model(model_name):
27
- return _open_onnx_model(hf_hub_download(
28
- f'deepghs/anime_eye_detection',
29
- f'{model_name}/model.onnx'
30
- ))
31
-
32
-
33
- _LABELS = ['eye']
34
-
35
-
36
- def detect_eyes(image: ImageTyping, model_name: str, max_infer_size=640,
37
- conf_threshold: float = 0.3, iou_threshold: float = 0.3) \
38
- -> List[Tuple[Tuple[int, int, int, int], str, float]]:
39
- image = load_image(image, mode='RGB')
40
- new_image, old_size, new_size = _image_preprocess(image, max_infer_size)
41
-
42
- data = rgb_encode(new_image)[None, ...]
43
- output, = _open_eye_detect_model(model_name).run(['output0'], {'images': data})
44
- return _data_postprocess(output[0], conf_threshold, iou_threshold, old_size, new_size, _LABELS)
45
-
46
-
47
- def _gr_detect_eyes(image: ImageTyping, model_name: str, max_infer_size=640,
48
- conf_threshold: float = 0.3, iou_threshold: float = 0.3):
49
- ret = detect_eyes(image, model_name, max_infer_size, conf_threshold, iou_threshold)
50
- return detection_visualize(image, ret, _LABELS)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
face.py DELETED
@@ -1,52 +0,0 @@
1
- from functools import lru_cache
2
- from typing import List, Tuple
3
-
4
- from huggingface_hub import hf_hub_download
5
- from imgutils.data import ImageTyping, load_image, rgb_encode
6
-
7
- from onnx_ import _open_onnx_model
8
- from plot import detection_visualize
9
- from yolo_ import _image_preprocess, _data_postprocess
10
-
11
- _FACE_MODELS = [
12
- 'face_detect_v1.4_s',
13
- 'face_detect_v1.4_n',
14
- 'face_detect_v1.3_s',
15
- 'face_detect_v1.3_n',
16
- 'face_detect_v1.2_s',
17
- 'face_detect_v1.1_s',
18
- 'face_detect_v1.1_n',
19
- 'face_detect_v1_s',
20
- 'face_detect_v1_n',
21
- 'face_detect_v0_s',
22
- 'face_detect_v0_n',
23
- ]
24
- _DEFAULT_FACE_MODEL = _FACE_MODELS[0]
25
-
26
-
27
- @lru_cache()
28
- def _open_face_detect_model(model_name):
29
- return _open_onnx_model(hf_hub_download(
30
- f'deepghs/anime_face_detection',
31
- f'{model_name}/model.onnx',
32
- ))
33
-
34
-
35
- _LABELS = ['face']
36
-
37
-
38
- def detect_faces(image: ImageTyping, model_name: str, max_infer_size=640,
39
- conf_threshold: float = 0.25, iou_threshold: float = 0.7) \
40
- -> List[Tuple[Tuple[int, int, int, int], str, float]]:
41
- image = load_image(image, mode='RGB')
42
- new_image, old_size, new_size = _image_preprocess(image, max_infer_size)
43
-
44
- data = rgb_encode(new_image)[None, ...]
45
- output, = _open_face_detect_model(model_name).run(['output0'], {'images': data})
46
- return _data_postprocess(output[0], conf_threshold, iou_threshold, old_size, new_size, _LABELS)
47
-
48
-
49
- def _gr_detect_faces(image: ImageTyping, model_name: str, max_infer_size=640,
50
- conf_threshold: float = 0.25, iou_threshold: float = 0.7):
51
- ret = detect_faces(image, model_name, max_infer_size, conf_threshold, iou_threshold)
52
- return detection_visualize(image, ret, _LABELS)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
halfbody.py DELETED
@@ -1,44 +0,0 @@
1
- from functools import lru_cache
2
- from typing import List, Tuple
3
-
4
- from huggingface_hub import hf_hub_download
5
- from imgutils.data import ImageTyping, load_image, rgb_encode
6
-
7
- from onnx_ import _open_onnx_model
8
- from plot import detection_visualize
9
- from yolo_ import _image_preprocess, _data_postprocess
10
-
11
- _HALFBODY_MODELS = [
12
- 'halfbody_detect_v0.4_s',
13
- 'halfbody_detect_v0.3_s',
14
- 'halfbody_detect_v0.2_s',
15
- ]
16
- _DEFAULT_HALFBODY_MODEL = _HALFBODY_MODELS[0]
17
-
18
-
19
- @lru_cache()
20
- def _open_halfbody_detect_model(model_name):
21
- return _open_onnx_model(hf_hub_download(
22
- f'deepghs/anime_halfbody_detection',
23
- f'{model_name}/model.onnx'
24
- ))
25
-
26
-
27
- _LABELS = ['haldbody']
28
-
29
-
30
- def detect_halfbodies(image: ImageTyping, model_name: str, max_infer_size=640,
31
- conf_threshold: float = 0.25, iou_threshold: float = 0.5) \
32
- -> List[Tuple[Tuple[int, int, int, int], str, float]]:
33
- image = load_image(image, mode='RGB')
34
- new_image, old_size, new_size = _image_preprocess(image, max_infer_size)
35
-
36
- data = rgb_encode(new_image)[None, ...]
37
- output, = _open_halfbody_detect_model(model_name).run(['output0'], {'images': data})
38
- return _data_postprocess(output[0], conf_threshold, iou_threshold, old_size, new_size, _LABELS)
39
-
40
-
41
- def _gr_detect_halfbodies(image: ImageTyping, model_name: str, max_infer_size=640,
42
- conf_threshold: float = 0.25, iou_threshold: float = 0.5):
43
- ret = detect_halfbodies(image, model_name, max_infer_size, conf_threshold, iou_threshold)
44
- return detection_visualize(image, ret, _LABELS)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
hand.py DELETED
@@ -1,49 +0,0 @@
1
- from functools import lru_cache
2
- from typing import List, Tuple
3
-
4
- from huggingface_hub import hf_hub_download
5
- from imgutils.data import ImageTyping, load_image, rgb_encode
6
-
7
- from onnx_ import _open_onnx_model
8
- from plot import detection_visualize
9
- from yolo_ import _image_preprocess, _data_postprocess
10
-
11
- _HAND_MODELS = [
12
- 'hand_detect_v0.7_s',
13
- 'hand_detect_v0.6_s',
14
- 'hand_detect_v0.5_s',
15
- 'hand_detect_v0.4_s',
16
- 'hand_detect_v0.3_s',
17
- 'hand_detect_v0.2_s',
18
- 'hand_detect_v0.1_s',
19
- 'hand_detect_v0.1_n',
20
- ]
21
- _DEFAULT_HAND_MODEL = _HAND_MODELS[0]
22
-
23
-
24
- @lru_cache()
25
- def _open_hand_detect_model(model_name):
26
- return _open_onnx_model(hf_hub_download(
27
- f'deepghs/anime_hand_detection',
28
- f'{model_name}/model.onnx'
29
- ))
30
-
31
-
32
- _LABELS = ['hand']
33
-
34
-
35
- def detect_hands(image: ImageTyping, model_name: str, max_infer_size=640,
36
- conf_threshold: float = 0.35, iou_threshold: float = 0.7) \
37
- -> List[Tuple[Tuple[int, int, int, int], str, float]]:
38
- image = load_image(image, mode='RGB')
39
- new_image, old_size, new_size = _image_preprocess(image, max_infer_size)
40
-
41
- data = rgb_encode(new_image)[None, ...]
42
- output, = _open_hand_detect_model(model_name).run(['output0'], {'images': data})
43
- return _data_postprocess(output[0], conf_threshold, iou_threshold, old_size, new_size, _LABELS)
44
-
45
-
46
- def _gr_detect_hands(image: ImageTyping, model_name: str, max_infer_size=640,
47
- conf_threshold: float = 0.35, iou_threshold: float = 0.7):
48
- ret = detect_hands(image, model_name, max_infer_size, conf_threshold, iou_threshold)
49
- return detection_visualize(image, ret, _LABELS)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
head.py DELETED
@@ -1,43 +0,0 @@
1
- from functools import lru_cache
2
- from typing import List, Tuple
3
-
4
- from huggingface_hub import hf_hub_download
5
- from imgutils.data import ImageTyping, load_image, rgb_encode
6
-
7
- from onnx_ import _open_onnx_model
8
- from plot import detection_visualize
9
- from yolo_ import _image_preprocess, _data_postprocess
10
-
11
- _HEAD_MODELS = [
12
- 'head_detect_best_s.onnx',
13
- 'head_detect_best_n.onnx',
14
- ]
15
- _DEFAULT_HEAD_MODEL = _HEAD_MODELS[0]
16
-
17
-
18
- @lru_cache()
19
- def _open_head_detect_model(model_name):
20
- return _open_onnx_model(hf_hub_download(
21
- 'deepghs/imgutils-models',
22
- f'head_detect/{model_name}'
23
- ))
24
-
25
-
26
- _LABELS = ['head']
27
-
28
-
29
- def detect_heads(image: ImageTyping, model_name: str, max_infer_size=640,
30
- conf_threshold: float = 0.45, iou_threshold: float = 0.7) \
31
- -> List[Tuple[Tuple[int, int, int, int], str, float]]:
32
- image = load_image(image, mode='RGB')
33
- new_image, old_size, new_size = _image_preprocess(image, max_infer_size)
34
-
35
- data = rgb_encode(new_image)[None, ...]
36
- output, = _open_head_detect_model(model_name).run(['output0'], {'images': data})
37
- return _data_postprocess(output[0], conf_threshold, iou_threshold, old_size, new_size, _LABELS)
38
-
39
-
40
- def _gr_detect_heads(image: ImageTyping, model_name: str, max_infer_size=640,
41
- conf_threshold: float = 0.45, iou_threshold: float = 0.7):
42
- ret = detect_heads(image, model_name, max_infer_size, conf_threshold, iou_threshold)
43
- return detection_visualize(image, ret, _LABELS)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
manbits.py DELETED
@@ -1,45 +0,0 @@
1
- from functools import lru_cache
2
- from typing import List, Tuple
3
-
4
- from huggingface_hub import hf_hub_download
5
- from imgutils.data import ImageTyping, load_image, rgb_encode
6
-
7
- from onnx_ import _open_onnx_model
8
- from plot import detection_visualize
9
- from yolo_ import _image_preprocess, _data_postprocess
10
-
11
- _MANBIT_MODELS = [
12
- 'manbits_detect_best_m.onnx',
13
- ]
14
- _DEFAULT_MANBIT_MODEL = _MANBIT_MODELS[0]
15
-
16
-
17
- @lru_cache()
18
- def _open_manbits_detect_model(model_name):
19
- return _open_onnx_model(hf_hub_download(
20
- 'deepghs/imgutils-models',
21
- f'manbits_detect/{model_name}'
22
- ))
23
-
24
-
25
- _LABELS = [
26
- 'EXPOSED_BELLY', 'EXPOSED_BREAST_F', 'EXPOSED_BREAST_M',
27
- 'EXPOSED_BUTTOCKS', 'EXPOSED_GENITALIA_F', 'EXPOSED_GENITALIA_M'
28
- ]
29
-
30
-
31
- def detect_manbits(image: ImageTyping, model_name: str, max_infer_size=640,
32
- conf_threshold: float = 0.25, iou_threshold: float = 0.7) \
33
- -> List[Tuple[Tuple[int, int, int, int], str, float]]:
34
- image = load_image(image, mode='RGB')
35
- new_image, old_size, new_size = _image_preprocess(image, max_infer_size)
36
-
37
- data = rgb_encode(new_image)[None, ...]
38
- output, = _open_manbits_detect_model(model_name).run(['output0'], {'images': data})
39
- return _data_postprocess(output[0], conf_threshold, iou_threshold, old_size, new_size, _LABELS)
40
-
41
-
42
- def _gr_detect_manbits(image: ImageTyping, model_name: str, max_infer_size=640,
43
- conf_threshold: float = 0.25, iou_threshold: float = 0.7):
44
- ret = detect_manbits(image, model_name, max_infer_size, conf_threshold, iou_threshold)
45
- return detection_visualize(image, ret, _LABELS)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
onnx_.py DELETED
@@ -1,59 +0,0 @@
1
- import logging
2
- import os
3
- import shutil
4
- from functools import lru_cache
5
- from typing import Optional
6
-
7
- from hbutils.system import pip_install
8
-
9
-
10
- def _ensure_onnxruntime():
11
- try:
12
- import onnxruntime
13
- except (ImportError, ModuleNotFoundError):
14
- logging.warning('Onnx runtime not installed, preparing to install ...')
15
- if shutil.which('nvidia-smi'):
16
- logging.info('Installing onnxruntime-gpu ...')
17
- pip_install(['onnxruntime-gpu'], silent=True)
18
- else:
19
- logging.info('Installing onnxruntime (cpu) ...')
20
- pip_install(['onnxruntime'], silent=True)
21
-
22
-
23
- _ensure_onnxruntime()
24
- from onnxruntime import get_available_providers, get_all_providers, InferenceSession, SessionOptions, \
25
- GraphOptimizationLevel
26
-
27
- alias = {
28
- 'gpu': "CUDAExecutionProvider",
29
- "trt": "TensorrtExecutionProvider",
30
- }
31
-
32
-
33
- def get_onnx_provider(provider: Optional[str] = None):
34
- if not provider:
35
- if "CUDAExecutionProvider" in get_available_providers():
36
- return "CUDAExecutionProvider"
37
- else:
38
- return "CPUExecutionProvider"
39
- elif provider.lower() in alias:
40
- return alias[provider.lower()]
41
- else:
42
- for p in get_all_providers():
43
- if provider.lower() == p.lower() or f'{provider}ExecutionProvider'.lower() == p.lower():
44
- return p
45
-
46
- raise ValueError(f'One of the {get_all_providers()!r} expected, '
47
- f'but unsupported provider {provider!r} found.')
48
-
49
-
50
- @lru_cache()
51
- def _open_onnx_model(ckpt: str, provider: str = None) -> InferenceSession:
52
- options = SessionOptions()
53
- options.graph_optimization_level = GraphOptimizationLevel.ORT_ENABLE_ALL
54
- provider = provider or get_onnx_provider()
55
- if provider == "CPUExecutionProvider":
56
- options.intra_op_num_threads = os.cpu_count()
57
-
58
- logging.info(f'Model {ckpt!r} loaded with provider {provider!r}')
59
- return InferenceSession(ckpt, options, [provider])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
person.py DELETED
@@ -1,46 +0,0 @@
1
- from functools import lru_cache
2
-
3
- from huggingface_hub import hf_hub_download
4
- from imgutils.data import ImageTyping, load_image, rgb_encode
5
-
6
- from onnx_ import _open_onnx_model
7
- from plot import detection_visualize
8
- from yolo_ import _image_preprocess, _data_postprocess
9
-
10
- _PERSON_MODELS = [
11
- 'person_detect_plus_v1.1_best_m.onnx',
12
- 'person_detect_plus_v1.1_best_s.onnx',
13
- 'person_detect_plus_v1.1_best_n.onnx',
14
- 'person_detect_plus_best_m.onnx',
15
- 'person_detect_best_m.onnx',
16
- 'person_detect_best_x.onnx',
17
- 'person_detect_best_s.onnx',
18
- ]
19
- _DEFAULT_PERSON_MODEL = _PERSON_MODELS[0]
20
-
21
-
22
- @lru_cache()
23
- def _open_person_detect_model(model_name):
24
- return _open_onnx_model(hf_hub_download(
25
- 'deepghs/imgutils-models',
26
- f'person_detect/{model_name}'
27
- ))
28
-
29
-
30
- _LABELS = ['person']
31
-
32
-
33
- def detect_person(image: ImageTyping, model_name: str, max_infer_size=640,
34
- conf_threshold: float = 0.3, iou_threshold: float = 0.5):
35
- image = load_image(image, mode='RGB')
36
- new_image, old_size, new_size = _image_preprocess(image, max_infer_size)
37
-
38
- data = rgb_encode(new_image)[None, ...]
39
- output, = _open_person_detect_model(model_name).run(['output0'], {'images': data})
40
- return _data_postprocess(output[0], conf_threshold, iou_threshold, old_size, new_size, _LABELS)
41
-
42
-
43
- def _gr_detect_person(image: ImageTyping, model_name: str, max_infer_size=640,
44
- conf_threshold: float = 0.3, iou_threshold: float = 0.5):
45
- ret = detect_person(image, model_name, max_infer_size, conf_threshold, iou_threshold)
46
- return detection_visualize(image, ret, _LABELS)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
plot.py DELETED
@@ -1,76 +0,0 @@
1
- """
2
- Overview:
3
- Visualize the detection results.
4
-
5
- See :func:`imgutils.detect.face.detect_faces` and :func:`imgutils.detect.person.detect_person` for examples.
6
- """
7
- from typing import List, Tuple, Optional
8
-
9
- from PIL import ImageFont, ImageDraw
10
- from hbutils.color import rnd_colors, Color
11
- from imgutils.data import ImageTyping, load_image
12
-
13
-
14
- def _try_get_font_from_matplotlib(fontsize: int = 12):
15
- try:
16
- # noinspection PyPackageRequirements
17
- import matplotlib
18
- except (ModuleNotFoundError, ImportError):
19
- return None
20
- else:
21
- # noinspection PyPackageRequirements
22
- from matplotlib.font_manager import findfont, FontProperties
23
- font = findfont(FontProperties(family=['sans-serif']))
24
- return ImageFont.truetype(font, fontsize)
25
-
26
-
27
- def detection_visualize(image: ImageTyping, detection: List[Tuple[Tuple[float, float, float, float], str, float]],
28
- labels: Optional[List[str]] = None, text_padding: int = 6, fontsize: int = 12,
29
- no_label: bool = False):
30
- """
31
- Overview:
32
- Visualize the results of the object detection.
33
-
34
- :param image: Image be detected.
35
- :param detection: The detection results list, each item includes the detected area `(x0, y0, x1, y1)`,
36
- the target type (always `head`) and the target confidence score.
37
- :param labels: An array of known labels. If not provided, the labels will be automatically detected
38
- from the given ``detection``.
39
- :param text_padding: Text padding of the labels. Default is ``6``.
40
- :param fontsize: Font size of the labels. At runtime, an attempt will be made to retrieve the font used
41
- for rendering from `matplotlib`. Therefore, if `matplotlib` is not installed, only the default pixel font
42
- provided with `Pillow` can be used, and the font size cannot be changed.
43
- :param no_label: Do not show labels. Default is ``False``.
44
- :return: A `PIL` image with the same size as the provided image `image`, which contains the original image
45
- content as well as the visualized bounding boxes.
46
-
47
- Examples::
48
- See :func:`imgutils.detect.face.detect_faces` and :func:`imgutils.detect.person.detect_person` for examples.
49
- """
50
- image = load_image(image, force_background=None, mode='RGBA')
51
- visual_image = image.copy()
52
- draw = ImageDraw.Draw(visual_image, mode='RGBA')
53
- font = _try_get_font_from_matplotlib(fontsize) or ImageFont.load_default()
54
-
55
- labels = sorted(labels or {label for _, label, _ in detection})
56
- _colors = list(map(str, rnd_colors(len(labels))))
57
- _color_map = dict(zip(labels, _colors))
58
- for (xmin, ymin, xmax, ymax), label, score in detection:
59
- box_color = _color_map[label]
60
- draw.rectangle((xmin, ymin, xmax, ymax), outline=box_color, width=2)
61
-
62
- if not no_label:
63
- label_text = f'{label}: {score * 100:.2f}%'
64
- _t_x0, _t_y0, _t_x1, _t_y1 = draw.textbbox((xmin, ymin), label_text, font=font)
65
- _t_width, _t_height = _t_x1 - _t_x0, _t_y1 - _t_y0
66
- if ymin - _t_height - text_padding < 0:
67
- _t_text_rect = (xmin, ymin, xmin + _t_width + text_padding * 2, ymin + _t_height + text_padding * 2)
68
- _t_text_co = (xmin + text_padding, ymin + text_padding)
69
- else:
70
- _t_text_rect = (xmin, ymin - _t_height - text_padding * 2, xmin + _t_width + text_padding * 2, ymin)
71
- _t_text_co = (xmin + text_padding, ymin - _t_height - text_padding)
72
-
73
- draw.rectangle(_t_text_rect, fill=str(Color(box_color, alpha=0.5)))
74
- draw.text(_t_text_co, label_text, fill="black", font=font)
75
-
76
- return visual_image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
yolo_.py DELETED
@@ -1,110 +0,0 @@
1
- import math
2
- from typing import List
3
-
4
- import numpy as np
5
- from PIL import Image
6
-
7
-
8
- def _yolo_xywh2xyxy(x: np.ndarray) -> np.ndarray:
9
- """
10
- Copied from yolov8.
11
-
12
- Convert bounding box coordinates from (x, y, width, height) format to (x1, y1, x2, y2) format where (x1, y1) is the
13
- top-left corner and (x2, y2) is the bottom-right corner.
14
-
15
- Args:
16
- x (np.ndarray) or (torch.Tensor): The input bounding box coordinates in (x, y, width, height) format.
17
- Returns:
18
- y (np.ndarray) or (torch.Tensor): The bounding box coordinates in (x1, y1, x2, y2) format.
19
- """
20
- y = np.copy(x)
21
- y[..., 0] = x[..., 0] - x[..., 2] / 2 # top left x
22
- y[..., 1] = x[..., 1] - x[..., 3] / 2 # top left y
23
- y[..., 2] = x[..., 0] + x[..., 2] / 2 # bottom right x
24
- y[..., 3] = x[..., 1] + x[..., 3] / 2 # bottom right y
25
- return y
26
-
27
-
28
- def _yolo_nms(boxes, scores, thresh: float = 0.7) -> List[int]:
29
- """
30
- dets: ndarray, (num_boxes, 5)
31
- 每一行表示一个bounding box:[xmin, ymin, xmax, ymax, score]
32
- 其中xmin, ymin, xmax, ymax分别表示框的左上角和右下角坐标,score表示框的分数
33
- thresh: float
34
- 两个框的IoU阈值
35
- """
36
- x1 = boxes[:, 0]
37
- y1 = boxes[:, 1]
38
- x2 = boxes[:, 2]
39
- y2 = boxes[:, 3]
40
- areas = (x2 - x1 + 1) * (y2 - y1 + 1)
41
-
42
- # 按照score降序排列
43
- order = scores.argsort()[::-1]
44
-
45
- keep = []
46
- while order.size > 0:
47
- i = order[0]
48
- keep.append(i)
49
- # 计算其他所有框与当前框的IoU
50
- xx1 = np.maximum(x1[i], x1[order[1:]])
51
- yy1 = np.maximum(y1[i], y1[order[1:]])
52
- xx2 = np.minimum(x2[i], x2[order[1:]])
53
- yy2 = np.minimum(y2[i], y2[order[1:]])
54
-
55
- w = np.maximum(0.0, xx2 - xx1 + 1)
56
- h = np.maximum(0.0, yy2 - yy1 + 1)
57
-
58
- inter = w * h
59
- iou = inter / (areas[i] + areas[order[1:]] - inter)
60
-
61
- # 保留IoU小于阈值的框
62
- inds = np.where(iou <= thresh)[0]
63
- order = order[inds + 1]
64
-
65
- return keep
66
-
67
-
68
- def _image_preprocess(image: Image.Image, max_infer_size: int = 640, align: int = 32):
69
- old_width, old_height = image.width, image.height
70
- new_width, new_height = old_width, old_height
71
- r = max_infer_size / max(new_width, new_height)
72
- if r < 1:
73
- new_width, new_height = new_width * r, new_height * r
74
- new_width = int(math.ceil(new_width / align) * align)
75
- new_height = int(math.ceil(new_height / align) * align)
76
- image = image.resize((new_width, new_height))
77
- return image, (old_width, old_height), (new_width, new_height)
78
-
79
-
80
- def _xy_postprocess(x, y, old_size, new_size):
81
- old_width, old_height = old_size
82
- new_width, new_height = new_size
83
- x, y = x / new_width * old_width, y / new_height * old_height
84
- x = int(np.clip(x, a_min=0, a_max=old_width).round())
85
- y = int(np.clip(y, a_min=0, a_max=old_height).round())
86
- return x, y
87
-
88
-
89
- def _data_postprocess(output, conf_threshold, iou_threshold, old_size, new_size, labels: List[str]):
90
- max_scores = output[4:, :].max(axis=0)
91
- output = output[:, max_scores > conf_threshold].transpose(1, 0)
92
- boxes = output[:, :4]
93
- scores = output[:, 4:]
94
- filtered_max_scores = scores.max(axis=1)
95
-
96
- if not boxes.size:
97
- return []
98
-
99
- boxes = _yolo_xywh2xyxy(boxes)
100
- idx = _yolo_nms(boxes, filtered_max_scores, thresh=iou_threshold)
101
- boxes, scores = boxes[idx], scores[idx]
102
-
103
- detections = []
104
- for box, score in zip(boxes, scores):
105
- x0, y0 = _xy_postprocess(box[0], box[1], old_size, new_size)
106
- x1, y1 = _xy_postprocess(box[2], box[3], old_size, new_size)
107
- max_score_id = score.argmax()
108
- detections.append(((x0, y0, x1, y1), labels[max_score_id], float(score[max_score_id])))
109
-
110
- return detections