File size: 13,767 Bytes
fcde2f2
d5894b1
fcde2f2
d5894b1
4412065
d5894b1
fcde2f2
 
 
d5894b1
fcde2f2
1eb8a26
fcde2f2
 
d5894b1
fcde2f2
 
 
4412065
fcde2f2
d5894b1
fcde2f2
 
 
d5894b1
 
fcde2f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5894b1
 
fcde2f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5894b1
fcde2f2
 
d5894b1
fcde2f2
 
 
d5894b1
fcde2f2
 
 
 
 
 
 
 
 
 
 
7c7be00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf2d24e
 
 
 
7c7be00
1eb8a26
7c7be00
 
 
1eb8a26
 
 
 
7c7be00
 
 
 
1eb8a26
 
7c7be00
cf2d24e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c7be00
 
cf2d24e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c7be00
fcde2f2
cf2d24e
fcde2f2
d5894b1
 
fcde2f2
cf2d24e
fcde2f2
 
d5894b1
fcde2f2
1eb8a26
7c7be00
 
 
 
 
 
 
fcde2f2
1eb8a26
 
 
d5894b1
 
7c7be00
 
 
 
 
 
 
 
cf2d24e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fcde2f2
 
1eb8a26
cf2d24e
7c7be00
 
 
 
 
cf2d24e
 
 
1eb8a26
cf2d24e
 
 
 
7c7be00
1eb8a26
7c7be00
1eb8a26
 
7c7be00
 
 
1eb8a26
7c7be00
 
 
 
 
 
 
 
 
 
 
 
 
 
1eb8a26
 
 
 
 
 
 
 
 
7c7be00
 
 
 
 
 
 
1eb8a26
7c7be00
 
 
 
 
 
1eb8a26
 
 
7c7be00
cf2d24e
1eb8a26
7c7be00
 
 
cf2d24e
1eb8a26
cf2d24e
7c7be00
1eb8a26
cf2d24e
7c7be00
 
cf2d24e
7c7be00
cf2d24e
7c7be00
1eb8a26
7c7be00
 
 
 
 
 
1eb8a26
7c7be00
 
 
1eb8a26
7c7be00
 
 
1eb8a26
7c7be00
d5894b1
7c7be00
fcde2f2
 
1eb8a26
 
7c7be00
d5894b1
 
fcde2f2
 
 
d5894b1
7c7be00
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import os, json
import gradio as gr
import huggingface_hub, numpy as np, onnxruntime as rt, pandas as pd
from PIL import Image
from huggingface_hub import login

from translator import translate_texts

# ------------------------------------------------------------------
# 模型配置
# ------------------------------------------------------------------
MODEL_REPO      = "SmilingWolf/wd-eva02-large-tagger-v3"
MODEL_FILENAME  = "model.onnx"
LABEL_FILENAME  = "selected_tags.csv"

HF_TOKEN = os.environ.get("HF_TOKEN", "")
if HF_TOKEN:
    login(token=HF_TOKEN)
else:
    print("⚠️ 未检测到 HF_TOKEN,私有模型可能下载失败")

# ------------------------------------------------------------------
# Tagger 类
# ------------------------------------------------------------------
class Tagger:
    def __init__(self):
        self.hf_token   = HF_TOKEN
        self._load_model_and_labels()

    def _load_model_and_labels(self):
        label_path = huggingface_hub.hf_hub_download(
            MODEL_REPO, LABEL_FILENAME, token=self.hf_token
        )
        model_path = huggingface_hub.hf_hub_download(
            MODEL_REPO, MODEL_FILENAME, token=self.hf_token
        )

        tags_df           = pd.read_csv(label_path)
        self.tag_names    = tags_df["name"].tolist()
        self.categories   = {
            "rating":    np.where(tags_df["category"] == 9)[0],
            "general":   np.where(tags_df["category"] == 0)[0],
            "character": np.where(tags_df["category"] == 4)[0],
        }
        self.model        = rt.InferenceSession(model_path)
        self.input_size   = self.model.get_inputs()[0].shape[1]

    # ------------------------- preprocess -------------------------
    def _preprocess(self, img: Image.Image) -> np.ndarray:
        if img.mode != "RGB":
            img = img.convert("RGB")
        size   = max(img.size)
        canvas = Image.new("RGB", (size, size), (255, 255, 255))
        canvas.paste(img, ((size - img.width)//2, (size - img.height)//2))
        if size != self.input_size:
            canvas = canvas.resize((self.input_size, self.input_size), Image.BICUBIC)
        return np.array(canvas)[:, :, ::-1].astype(np.float32)  # to BGR

    # --------------------------- predict --------------------------
    def predict(self, img: Image.Image,
                gen_th: float = 0.35,
                char_th: float = 0.85):
        inp_name  = self.model.get_inputs()[0].name
        outputs   = self.model.run(None, {inp_name: self._preprocess(img)[None, ...]})[0][0]

        res = {"ratings": {}, "general": {}, "characters": {}}

        for idx in self.categories["rating"]:
            res["ratings"][self.tag_names[idx].replace("_", " ")] = float(outputs[idx])

        for idx in self.categories["general"]:
            if outputs[idx] > gen_th:
                res["general"][self.tag_names[idx].replace("_", " ")] = float(outputs[idx])

        for idx in self.categories["character"]:
            if outputs[idx] > char_th:
                res["characters"][self.tag_names[idx].replace("_", " ")] = float(outputs[idx])

        res["general"] = dict(sorted(res["general"].items(),
                                     key=lambda kv: kv[1],
                                     reverse=True))
        return res

# ------------------------------------------------------------------
# Gradio UI
# ------------------------------------------------------------------
custom_css = """
.label-container {
    max-height: 300px;
    overflow-y: auto;
    border: 1px solid #ddd;
    padding: 10px;
    border-radius: 5px;
    background-color: #f9f9f9;
}
.tag-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 2px 0;
    padding: 2px 5px;
    border-radius: 3px;
    background-color: #fff;
    cursor: pointer;
}
.tag-item:hover {
    background-color: #f0f0f0;
}
.tag-en {
    font-weight: bold;
    color: #333;
}
.tag-zh {
    color: #666;
    margin-left: 10px;
}
.tag-score {
    color: #999;
    font-size: 0.9em;
}
.btn-container {
    margin-top: 20px;
}
.copy-btn {
    margin-top: 10px;
    padding: 5px 10px;
    background-color: #f0f0f0;
    border: 1px solid #ddd;
    border-radius: 4px;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    font-size: 0.9em;
}
.copy-btn:hover {
    background-color: #e0e0e0;
}
.copy-icon {
    margin-right: 5px;
    width: 16px;
    height: 16px;
}
.copied-message {
    display: none;
    color: #4CAF50;
    margin-left: 10px;
    font-size: 0.9em;
}
.note-text {
    color: #ff6b6b;
    font-size: 0.9em;
    padding: 5px;
    border-left: 3px solid #ff6b6b;
    margin-top: 15px;
    background-color: #fff5f5;
}
"""

js_code = """
function setupCopyFunctions() {
    // 为标签项设置点击复制
    document.querySelectorAll('.tag-item').forEach(item => {
        item.addEventListener('click', function() {
            const tagText = this.querySelector('.tag-en').textContent;
            navigator.clipboard.writeText(tagText).then(() => {
                // 显示临时复制成功提示
                const msg = document.createElement('span');
                msg.textContent = '已复制!';
                msg.style.color = '#4CAF50';
                msg.style.marginLeft = '5px';
                msg.style.fontSize = '0.8em';
                this.appendChild(msg);
                setTimeout(() => msg.remove(), 1000);
            });
        });
    });

    // 为汇总区域的复制按钮设置功能
    document.getElementById('copy-tags-btn').addEventListener('click', function() {
        const tagsText = document.getElementById('summary-text').value;
        navigator.clipboard.writeText(tagsText).then(() => {
            const copiedMsg = document.getElementById('copied-message');
            copiedMsg.style.display = 'inline';
            setTimeout(() => {
                copiedMsg.style.display = 'none';
            }, 2000);
        });
    });
}

// 在DOM加载完成或更新后调用设置函数
function onUiUpdate() {
    setupCopyFunctions();
}

document.addEventListener('DOMContentLoaded', onUiUpdate);
"""

with gr.Blocks(theme=gr.themes.Soft(), title="AI 图像标签分析器", css=custom_css, js=js_code) as demo:
    gr.Markdown("# 🖼️ AI 图像标签分析器")
    gr.Markdown("上传图片自动识别标签,并可一键翻译成中文")
    gr.Markdown("<div class='note-text'>⚠️ 注意:角色识别仅支持推测2024年2月以前的角色</div>", elem_id="character-notice")

    with gr.Row():
        with gr.Column(scale=1):
            img_in = gr.Image(type="pil", label="上传图片")
            with gr.Accordion("⚙️ 高级设置", open=False):
                gen_slider  = gr.Slider(0, 1, 0.35,
                                        label="通用标签阈值", info="越高→标签更少更准")
                char_slider = gr.Slider(0, 1, 0.85,
                                        label="角色标签阈值", info="推荐保持较高阈值")
                show_zh = gr.Checkbox(True, label="显示中文翻译")
                
                gr.Markdown("### 汇总设置")
                with gr.Row():
                    sum_general = gr.Checkbox(True, label="通用标签")
                    sum_char = gr.Checkbox(True, label="角色标签")
                    sum_rating = gr.Checkbox(False, label="评分标签")
                sum_sep = gr.Dropdown(["逗号", "换行", "空格"], value="逗号", label="分隔符")

            btn = gr.Button("开始分析", variant="primary", elem_classes=["btn-container"])
            processing_info = gr.Markdown("", visible=False)

        with gr.Column(scale=2):
            with gr.Tabs():
                with gr.TabItem("🏷️ 通用标签"):
                    out_general = gr.HTML(label="General Tags")
                with gr.TabItem("👤 角色标签"):
                    out_char = gr.HTML(label="Character Tags")
                with gr.TabItem("⭐ 评分标签"):
                    out_rating = gr.HTML(label="Rating Tags")
            
            gr.Markdown("### 标签汇总")
            with gr.Row():
                out_summary = gr.Textbox(label="标签汇总", 
                                         placeholder="选择需要汇总的标签类别...",
                                         lines=3,
                                         elem_id="summary-text")
            
            # 添加复制按钮的HTML
            copy_btn_html = gr.HTML("""
            <div style="display: flex; align-items: center;">
                <button id="copy-tags-btn" class="copy-btn">
                    <svg class="copy-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
                        <path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"></path>
                    </svg>
                    复制标签
                </button>
                <span id="copied-message" class="copied-message">已复制!</span>
            </div>
            """)

    # ----------------- 处理回调 -----------------
    def format_tags_html(tags_dict, translations, show_translation=True):
        """格式化标签为HTML格式,添加点击复制功能"""
        if not tags_dict:
            return "<p>暂无标签</p>"
        
        html = '<div class="label-container">'
        for i, (tag, score) in enumerate(tags_dict.items()):
            # 添加可点击复制的标签项
            html += f'<div class="tag-item" title="点击复制标签">'
            html += f'<div><span class="tag-en">{tag}</span>'
            if show_translation and i < len(translations):
                html += f'<span class="tag-zh">({translations[i]})</span>'
            html += '</div>'
            html += f'<span class="tag-score">{score:.3f}</span>'
            html += '</div>'
        html += '</div>'
        return html

    def process(img, g_th, c_th, show_zh, sum_gen, sum_char, sum_rat, sep_type):
        # 开始处理,返回更新
        yield (
            gr.update(interactive=False, value="处理中..."),
            gr.update(visible=True, value="🔄 正在分析图像..."),
            "", "", "", ""
        )
        
        try:
            tagger = Tagger()
            res = tagger.predict(img, g_th, c_th)

            # 收集所有需要翻译的标签
            all_tags = []
            tag_categories = {
                "general": list(res["general"].keys()),
                "characters": list(res["characters"].keys()),
                "ratings": list(res["ratings"].keys())
            }
            
            if show_zh:
                for tags in tag_categories.values():
                    all_tags.extend(tags)
                
                # 批量翻译
                if all_tags:
                    translations = translate_texts(all_tags, src_lang="auto", tgt_lang="zh")
                else:
                    translations = []
            else:
                translations = []

            # 分配翻译结果
            translations_dict = {}
            offset = 0
            for category, tags in tag_categories.items():
                if show_zh and tags:
                    translations_dict[category] = translations[offset:offset+len(tags)]
                    offset += len(tags)
                else:
                    translations_dict[category] = []

            # 生成HTML输出
            general_html = format_tags_html(res["general"], translations_dict["general"], show_zh)
            char_html = format_tags_html(res["characters"], translations_dict["characters"], show_zh)
            rating_html = format_tags_html(res["ratings"], translations_dict["ratings"], show_zh)

            # 生成汇总文本 - 修改为仅显示英文标签,无注释
            summary_parts = []
            separators = {"逗号": ", ", "换行": "\n", "空格": " "}
            separator = separators[sep_type]
            
            all_tags = []
            if sum_gen and res["general"]:
                all_tags.extend(list(res["general"].keys()))
            
            if sum_char and res["characters"]:
                all_tags.extend(list(res["characters"].keys()))
            
            if sum_rat and res["ratings"]:
                all_tags.extend(list(res["ratings"].keys()))
            
            summary_text = separator.join(all_tags) if all_tags else "请选择要汇总的标签类别"

            # 完成处理,返回最终结果
            yield (
                gr.update(interactive=True, value="开始分析"),
                gr.update(visible=False),
                general_html,
                char_html,
                rating_html,
                summary_text
            )
            
        except Exception as e:
            # 出错时的处理
            yield (
                gr.update(interactive=True, value="开始分析"),
                gr.update(visible=True, value=f"❌ 处理失败: {str(e)}"),
                "", "", "", ""
            )

    # 绑定事件
    btn.click(
        process,
        inputs=[img_in, gen_slider, char_slider, show_zh, sum_general, sum_char, sum_rating, sum_sep],
        outputs=[btn, processing_info, out_general, out_char, out_rating, out_summary],
        show_progress=True
    )

# ------------------------------------------------------------------
# 启动
# ------------------------------------------------------------------
if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0", server_port=7860)