Plana-Archive commited on
Commit
9a6281d
·
verified ·
1 Parent(s): b44daf3

Upload deepdanbooru_online/app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. deepdanbooru_online/app.py +114 -0
deepdanbooru_online/app.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ from functools import lru_cache
4
+ from typing import List, Mapping, Tuple
5
+
6
+ import gradio as gr
7
+ import numpy as np
8
+ import onnxruntime as ort
9
+ from PIL import Image
10
+ from huggingface_hub import hf_hub_download
11
+
12
+
13
+ def _yield_tags_from_txt_file(txt_file: str):
14
+ with open(txt_file, 'r') as f:
15
+ for line in f:
16
+ if line:
17
+ yield line.strip()
18
+
19
+
20
+ @lru_cache()
21
+ def get_deepdanbooru_tags() -> List[str]:
22
+ tags_file = hf_hub_download('chinoll/deepdanbooru', 'tags.txt')
23
+ return list(_yield_tags_from_txt_file(tags_file))
24
+
25
+
26
+ @lru_cache()
27
+ def get_deepdanbooru_onnx() -> ort.InferenceSession:
28
+ onnx_file = hf_hub_download('chinoll/deepdanbooru', 'deepdanbooru.onnx')
29
+ return ort.InferenceSession(onnx_file)
30
+
31
+
32
+ def image_preprocess(image: Image.Image) -> np.ndarray:
33
+ if image.mode != 'RGB':
34
+ image = image.convert('RGB')
35
+
36
+ o_width, o_height = image.size
37
+ scale = 512.0 / max(o_width, o_height)
38
+ f_width, f_height = map(lambda x: int(x * scale), (o_width, o_height))
39
+ image = image.resize((f_width, f_height))
40
+
41
+ data = np.asarray(image).astype(np.float32) / 255 # H x W x C
42
+ height_pad_left = (512 - f_height) // 2
43
+ height_pad_right = 512 - f_height - height_pad_left
44
+ width_pad_left = (512 - f_width) // 2
45
+ width_pad_right = 512 - f_width - width_pad_left
46
+ data = np.pad(data, ((height_pad_left, height_pad_right), (width_pad_left, width_pad_right), (0, 0)),
47
+ mode='constant', constant_values=0.0)
48
+
49
+ assert data.shape == (512, 512, 3), f'Shape (512, 512, 3) expected, but {data.shape!r} found.'
50
+ return data.reshape((1, 512, 512, 3)) # B x H x W x C
51
+
52
+
53
+ RE_SPECIAL = re.compile(r'([\\()])')
54
+
55
+
56
+ def image_to_deepdanbooru_tags(image: Image.Image, threshold: float,
57
+ use_spaces: bool, use_escape: bool, include_ranks: bool, score_descend: bool) \
58
+ -> Tuple[str, Mapping[str, float]]:
59
+ tags = get_deepdanbooru_tags()
60
+ session = get_deepdanbooru_onnx()
61
+ input_name = session.get_inputs()[0].name
62
+ output_names = [output.name for output in session.get_outputs()]
63
+
64
+ result = session.run(output_names, {input_name: image_preprocess(image)})[0]
65
+ filtered_tags = {
66
+ tag: float(score) for tag, score in zip(tags, result[0])
67
+ if score >= threshold
68
+ }
69
+
70
+ text_items = []
71
+ tags_pairs = filtered_tags.items()
72
+ if score_descend:
73
+ tags_pairs = sorted(tags_pairs, key=lambda x: (-x[1], x[0]))
74
+ for tag, score in tags_pairs:
75
+ tag_outformat = tag
76
+ if use_spaces:
77
+ tag_outformat = tag_outformat.replace('_', ' ')
78
+ if use_escape:
79
+ tag_outformat = re.sub(RE_SPECIAL, r'\\\1', tag_outformat)
80
+ if include_ranks:
81
+ tag_outformat = f"({tag_outformat}:{score:.3f})"
82
+ text_items.append(tag_outformat)
83
+ output_text = ', '.join(text_items)
84
+
85
+ return output_text, filtered_tags
86
+
87
+
88
+ if __name__ == '__main__':
89
+ with gr.Blocks() as demo:
90
+ with gr.Row():
91
+ with gr.Column():
92
+ gr_input_image = gr.Image(type='pil', label='Original Image')
93
+ gr_threshold = gr.Slider(0.0, 1.0, 0.5, label='Tagging Confidence Threshold')
94
+ with gr.Row():
95
+ gr_space = gr.Checkbox(value=False, label='Use Space Instead Of _')
96
+ gr_escape = gr.Checkbox(value=True, label='Use Text Escape')
97
+ gr_confidence = gr.Checkbox(value=False, label='Keep Confidences')
98
+ gr_order = gr.Checkbox(value=True, label='Descend By Confidence')
99
+
100
+ gr_btn_submit = gr.Button(value='Tagging', variant='primary')
101
+
102
+ with gr.Column():
103
+ with gr.Tabs():
104
+ with gr.Tab("Tags"):
105
+ gr_tags = gr.Label(label='Tags')
106
+ with gr.Tab("Exported Text"):
107
+ gr_output_text = gr.TextArea(label='Exported Text')
108
+
109
+ gr_btn_submit.click(
110
+ image_to_deepdanbooru_tags,
111
+ inputs=[gr_input_image, gr_threshold, gr_space, gr_escape, gr_confidence, gr_order],
112
+ outputs=[gr_output_text, gr_tags],
113
+ )
114
+ demo.queue(os.cpu_count()).launch()