Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -7,25 +7,26 @@ import onnxruntime as rt
|
|
| 7 |
import pandas as pd
|
| 8 |
from PIL import Image
|
| 9 |
from huggingface_hub import login
|
| 10 |
-
|
| 11 |
-
from translator import translate_texts
|
| 12 |
|
| 13 |
# ------------------------------------------------------------------
|
| 14 |
-
#
|
| 15 |
# ------------------------------------------------------------------
|
| 16 |
MODEL_REPO = "SmilingWolf/wd-eva02-large-tagger-v3"
|
| 17 |
MODEL_FILENAME = "model.onnx"
|
| 18 |
LABEL_FILENAME = "selected_tags.csv"
|
|
|
|
| 19 |
|
| 20 |
HF_TOKEN = os.environ.get("HF_TOKEN", "")
|
| 21 |
if HF_TOKEN:
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
else:
|
| 24 |
print("⚠️ 未检测到 HF_TOKEN,私有模型可能下载失败")
|
| 25 |
|
| 26 |
-
# ------------------------------------------------------------------
|
| 27 |
-
# Tagger 类 (全局实例化)
|
| 28 |
-
# ------------------------------------------------------------------
|
| 29 |
class Tagger:
|
| 30 |
def __init__(self):
|
| 31 |
self.hf_token = HF_TOKEN
|
|
@@ -59,7 +60,6 @@ class Tagger:
|
|
| 59 |
raise RuntimeError(f"模型初始化失败: {e}")
|
| 60 |
|
| 61 |
|
| 62 |
-
# ------------------------- preprocess -------------------------
|
| 63 |
def _preprocess(self, img: Image.Image) -> np.ndarray:
|
| 64 |
if img is None:
|
| 65 |
raise ValueError("输入图像不能为空")
|
|
@@ -70,9 +70,8 @@ class Tagger:
|
|
| 70 |
canvas.paste(img, ((size - img.width) // 2, (size - img.height) // 2))
|
| 71 |
if size != self.input_size:
|
| 72 |
canvas = canvas.resize((self.input_size, self.input_size), Image.BICUBIC)
|
| 73 |
-
return np.array(canvas)[:, :, ::-1].astype(np.float32)
|
| 74 |
|
| 75 |
-
# --------------------------- predict --------------------------
|
| 76 |
def predict(self, img: Image.Image, gen_th: float = 0.35, char_th: float = 0.85):
|
| 77 |
if self.model is None:
|
| 78 |
raise RuntimeError("模型未成功加载,无法进行预测。")
|
|
@@ -111,125 +110,41 @@ class Tagger:
|
|
| 111 |
|
| 112 |
return res, tag_categories_for_translation
|
| 113 |
|
| 114 |
-
# 全局 Tagger 实例
|
| 115 |
try:
|
| 116 |
tagger_instance = Tagger()
|
| 117 |
except RuntimeError as e:
|
| 118 |
print(f"应用启动时Tagger初始化失败: {e}")
|
| 119 |
-
tagger_instance = None
|
| 120 |
|
| 121 |
-
# ------------------------------------------------------------------
|
| 122 |
-
# Gradio UI
|
| 123 |
-
# ------------------------------------------------------------------
|
| 124 |
custom_css = """
|
| 125 |
-
.label-container {
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
}
|
| 133 |
-
.tag-item {
|
| 134 |
-
display: flex;
|
| 135 |
-
justify-content: space-between;
|
| 136 |
-
align-items: center;
|
| 137 |
-
margin: 2px 0;
|
| 138 |
-
padding: 2px 5px;
|
| 139 |
-
border-radius: 3px;
|
| 140 |
-
background-color: #fff;
|
| 141 |
-
transition: background-color 0.2s;
|
| 142 |
-
}
|
| 143 |
-
.tag-item:hover {
|
| 144 |
-
background-color: #f0f0f0;
|
| 145 |
-
}
|
| 146 |
-
.tag-en {
|
| 147 |
-
font-weight: bold;
|
| 148 |
-
color: #333;
|
| 149 |
-
cursor: pointer; /* Indicates clickable */
|
| 150 |
-
}
|
| 151 |
-
.tag-zh {
|
| 152 |
-
color: #666;
|
| 153 |
-
margin-left: 10px;
|
| 154 |
-
}
|
| 155 |
-
.tag-score {
|
| 156 |
-
color: #999;
|
| 157 |
-
font-size: 0.9em;
|
| 158 |
-
}
|
| 159 |
-
.btn-analyze-container { /* Custom class for analyze button container */
|
| 160 |
-
margin-top: 15px;
|
| 161 |
-
margin-bottom: 15px;
|
| 162 |
-
}
|
| 163 |
"""
|
| 164 |
|
| 165 |
_js_functions = """
|
| 166 |
function copyToClipboard(text) {
|
| 167 |
-
// --- 调试信息 ---
|
| 168 |
-
console.log('copyToClipboard function was called.');
|
| 169 |
-
console.log('Received text:', text);
|
| 170 |
-
// console.trace(); // 如果需要更详细的调用栈信息,可以取消这行注释
|
| 171 |
-
|
| 172 |
-
// --- 保护性检查 ---
|
| 173 |
-
// 如果 text 未定义或为 null,则不执行后续操作,并打印警告
|
| 174 |
if (typeof text === 'undefined' || text === null) {
|
| 175 |
-
console.warn('copyToClipboard was called with undefined or null text.
|
| 176 |
-
// 在这种情况下,我们不应该尝试复制,也不应该显示“已复制”的提示
|
| 177 |
return;
|
| 178 |
}
|
| 179 |
-
|
| 180 |
navigator.clipboard.writeText(text).then(() => {
|
| 181 |
-
// console.log('Tag copied to clipboard: ' + text); // 成功复制的日志(可选)
|
| 182 |
const feedback = document.createElement('div');
|
| 183 |
-
|
| 184 |
-
// 确保 text 是���符串类型,再进行 substring 操作
|
| 185 |
-
let displayText = String(text); // 将 text 转换为字符串以防万一
|
| 186 |
displayText = displayText.substring(0, 30) + (displayText.length > 30 ? '...' : '');
|
| 187 |
-
|
| 188 |
feedback.textContent = '已复制: ' + displayText;
|
| 189 |
-
feedback.style.
|
| 190 |
-
feedback.style.bottom = '20px';
|
| 191 |
-
feedback.style.left = '50%';
|
| 192 |
-
feedback.style.transform = 'translateX(-50%)';
|
| 193 |
-
feedback.style.backgroundColor = '#4CAF50';
|
| 194 |
-
feedback.style.color = 'white';
|
| 195 |
-
feedback.style.padding = '10px 20px';
|
| 196 |
-
feedback.style.borderRadius = '5px';
|
| 197 |
-
feedback.style.zIndex = '10000';
|
| 198 |
-
feedback.style.transition = 'opacity 0.5s ease-out';
|
| 199 |
document.body.appendChild(feedback);
|
| 200 |
setTimeout(() => {
|
| 201 |
feedback.style.opacity = '0';
|
| 202 |
-
setTimeout(() => {
|
| 203 |
-
if (document.body.contains(feedback)) { // 确保元素还在DOM中
|
| 204 |
-
document.body.removeChild(feedback);
|
| 205 |
-
}
|
| 206 |
-
}, 500);
|
| 207 |
}, 1500);
|
| 208 |
}).catch(err => {
|
| 209 |
console.error('Failed to copy tag. Error:', err, 'Attempted to copy text:', text);
|
| 210 |
-
// 可以考虑也给用户一个错误提示,但原版 alert 可能体验不佳
|
| 211 |
-
// alert('复制失败: ' + err);
|
| 212 |
-
const errorFeedback = document.createElement('div');
|
| 213 |
-
errorFeedback.textContent = '复制操作失败!'; // 更友好的错误提示
|
| 214 |
-
errorFeedback.style.position = 'fixed';
|
| 215 |
-
errorFeedback.style.bottom = '20px';
|
| 216 |
-
errorFeedback.style.left = '50%';
|
| 217 |
-
errorFeedback.style.transform = 'translateX(-50%)';
|
| 218 |
-
errorFeedback.style.backgroundColor = '#D32F2F'; // 红色背景表示错误
|
| 219 |
-
errorFeedback.style.color = 'white';
|
| 220 |
-
errorFeedback.style.padding = '10px 20px';
|
| 221 |
-
errorFeedback.style.borderRadius = '5px';
|
| 222 |
-
errorFeedback.style.zIndex = '10000';
|
| 223 |
-
errorFeedback.style.transition = 'opacity 0.5s ease-out';
|
| 224 |
-
document.body.appendChild(errorFeedback);
|
| 225 |
-
setTimeout(() => {
|
| 226 |
-
errorFeedback.style.opacity = '0';
|
| 227 |
-
setTimeout(() => {
|
| 228 |
-
if (document.body.contains(errorFeedback)) {
|
| 229 |
-
document.body.removeChild(errorFeedback);
|
| 230 |
-
}
|
| 231 |
-
}, 500);
|
| 232 |
-
}, 2500);
|
| 233 |
});
|
| 234 |
}
|
| 235 |
"""
|
|
@@ -246,13 +161,22 @@ with gr.Blocks(theme=gr.themes.Soft(), title="AI 图像标签分析器", css=cus
|
|
| 246 |
with gr.Row():
|
| 247 |
with gr.Column(scale=1):
|
| 248 |
img_in = gr.Image(type="pil", label="上传图片", height=300)
|
| 249 |
-
|
| 250 |
btn = gr.Button("🚀 开始分析", variant="primary", elem_classes=["btn-analyze-container"])
|
| 251 |
|
| 252 |
with gr.Accordion("⚙️ 高级设置", open=False):
|
| 253 |
gen_slider = gr.Slider(0, 1, value=0.35, step=0.01, label="通用标签阈值", info="越高 → 标签更少更准")
|
| 254 |
char_slider = gr.Slider(0, 1, value=0.85, step=0.01, label="角色标签阈值", info="推荐保持较高阈值")
|
| 255 |
show_tag_scores = gr.Checkbox(True, label="在列表中显示标签置信度")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
|
| 257 |
with gr.Accordion("📊 标签汇总设置", open=True):
|
| 258 |
gr.Markdown("选择要包含在下方汇总文本框中的标签类别:")
|
|
@@ -283,209 +207,121 @@ with gr.Blocks(theme=gr.themes.Soft(), title="AI 图像标签分析器", css=cus
|
|
| 283 |
show_copy_button=True
|
| 284 |
)
|
| 285 |
|
| 286 |
-
# ----------------- 辅助函数 -----------------
|
| 287 |
def format_tags_html(tags_dict, translations_list, category_name, show_scores=True, show_translation_in_list=True):
|
| 288 |
-
if not tags_dict:
|
| 289 |
-
return "<p>暂无标签</p>"
|
| 290 |
-
|
| 291 |
html = '<div class="label-container">'
|
| 292 |
-
|
| 293 |
-
if not isinstance(translations_list, list):
|
| 294 |
-
translations_list = []
|
| 295 |
-
|
| 296 |
tag_keys = list(tags_dict.keys())
|
| 297 |
-
|
| 298 |
for i, tag in enumerate(tag_keys):
|
| 299 |
score = tags_dict[tag]
|
| 300 |
-
escaped_tag = tag.replace("'", "\\'")
|
| 301 |
-
|
| 302 |
html += '<div class="tag-item">'
|
| 303 |
tag_display_html = f'<span class="tag-en" onclick="copyToClipboard(\'{escaped_tag}\')">{tag}</span>'
|
| 304 |
-
|
| 305 |
if show_translation_in_list and i < len(translations_list) and translations_list[i]:
|
| 306 |
tag_display_html += f'<span class="tag-zh">({translations_list[i]})</span>'
|
| 307 |
-
|
| 308 |
html += f'<div>{tag_display_html}</div>'
|
| 309 |
-
if show_scores:
|
| 310 |
-
html += f'<span class="tag-score">{score:.3f}</span>'
|
| 311 |
html += '</div>'
|
| 312 |
html += '</div>'
|
| 313 |
return html
|
| 314 |
|
| 315 |
-
def generate_summary_text_content(
|
| 316 |
-
current_res
|
| 317 |
-
|
| 318 |
-
):
|
| 319 |
-
if not current_res:
|
| 320 |
-
return "请先分析图像或选择要汇总的标签类别。"
|
| 321 |
-
|
| 322 |
-
summary_parts = []
|
| 323 |
-
separators = {"逗号": ", ", "换行": "\n", "空格": " "}
|
| 324 |
-
separator = separators.get(s_sep_type, ", ")
|
| 325 |
-
|
| 326 |
categories_to_summarize = []
|
| 327 |
if s_gen: categories_to_summarize.append("general")
|
| 328 |
if s_char: categories_to_summarize.append("characters")
|
| 329 |
if s_rat: categories_to_summarize.append("ratings")
|
| 330 |
-
|
| 331 |
-
if not categories_to_summarize:
|
| 332 |
-
return "请至少选择一个标签类别进行汇总。"
|
| 333 |
|
| 334 |
for cat_key in categories_to_summarize:
|
| 335 |
if current_res.get(cat_key):
|
| 336 |
tags_to_join = []
|
| 337 |
cat_tags_en = list(current_res[cat_key].keys())
|
| 338 |
cat_translations = current_translations_dict.get(cat_key, [])
|
| 339 |
-
|
| 340 |
for i, en_tag in enumerate(cat_tags_en):
|
| 341 |
if s_show_zh and i < len(cat_translations) and cat_translations[i]:
|
| 342 |
tags_to_join.append(f"{en_tag}({cat_translations[i]})")
|
| 343 |
else:
|
| 344 |
tags_to_join.append(en_tag)
|
| 345 |
-
if tags_to_join:
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
# Join parts with double newline for readability if multiple categories present and separator is not newline
|
| 349 |
-
joiner = "\n\n" if separator != "\n" and len(summary_parts) > 1 else separator if separator == "\n" else " "
|
| 350 |
-
|
| 351 |
final_summary = joiner.join(summary_parts)
|
| 352 |
return final_summary if final_summary else "选定的类别中没有找到标签。"
|
| 353 |
|
| 354 |
-
|
| 355 |
-
# ----------------- 主要处理回调 -----------------
|
| 356 |
-
def process_image_and_generate_outputs(
|
| 357 |
-
img, g_th, c_th, s_scores, # Main inputs
|
| 358 |
-
s_gen, s_char, s_rat, s_sep, s_zh_in_sum
|
| 359 |
-
):
|
| 360 |
if img is None:
|
| 361 |
-
yield (
|
| 362 |
-
gr.update(interactive=True, value="🚀 开始分析"),
|
| 363 |
-
gr.update(visible=True, value="❌ 请先上传图片。"),
|
| 364 |
-
"", "", "", "",
|
| 365 |
-
gr.update(placeholder="请先上传图片并开始分析..."),
|
| 366 |
-
{}, {}, {}
|
| 367 |
-
)
|
| 368 |
return
|
| 369 |
-
|
| 370 |
if tagger_instance is None:
|
| 371 |
-
yield (
|
| 372 |
-
gr.update(interactive=True, value="🚀 开始分析"),
|
| 373 |
-
gr.update(visible=True, value="❌ 分析器未成功初始化,请检查控制台错误。"),
|
| 374 |
-
"", "", "", "",
|
| 375 |
-
gr.update(placeholder="分析器初始化失败..."),
|
| 376 |
-
{}, {}, {}
|
| 377 |
-
)
|
| 378 |
return
|
| 379 |
|
| 380 |
-
yield (
|
| 381 |
-
gr.update(interactive=False, value="🔄 处理中..."),
|
| 382 |
-
gr.update(visible=True, value="🔄 正在分析图像,请稍候..."),
|
| 383 |
-
gr.HTML(value="<p>分析中...</p>"), # General
|
| 384 |
-
gr.HTML(value="<p>分析中...</p>"), # Character
|
| 385 |
-
gr.HTML(value="<p>分析中...</p>"), # Rating
|
| 386 |
-
gr.update(value="分析中,请稍候..."), # Summary
|
| 387 |
-
{}, {}, {} # Clear states initially
|
| 388 |
-
)
|
| 389 |
|
| 390 |
try:
|
| 391 |
-
# 1. Predict tags
|
| 392 |
res, tag_categories_original_order = tagger_instance.predict(img, g_th, c_th)
|
| 393 |
-
|
| 394 |
-
all_tags_to_translate = []
|
| 395 |
-
for cat_key in ["general", "characters", "ratings"]:
|
| 396 |
-
all_tags_to_translate.extend(tag_categories_original_order.get(cat_key, []))
|
| 397 |
|
| 398 |
all_translations_flat = []
|
| 399 |
if all_tags_to_translate:
|
| 400 |
-
|
| 401 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 402 |
current_translations_dict = {}
|
| 403 |
offset = 0
|
| 404 |
for cat_key in ["general", "characters", "ratings"]:
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
current_translations_dict[cat_key] = all_translations_flat[offset : offset + num_tags_in_cat]
|
| 409 |
-
offset += num_tags_in_cat
|
| 410 |
-
else:
|
| 411 |
-
current_translations_dict[cat_key] = []
|
| 412 |
|
| 413 |
-
general_html = format_tags_html(res.get("general", {}), current_translations_dict.get("general", []), "general", s_scores
|
| 414 |
-
char_html = format_tags_html(res.get("characters", {}), current_translations_dict.get("characters", []), "characters", s_scores
|
| 415 |
-
rating_html = format_tags_html(res.get("ratings", {}), current_translations_dict.get("ratings", []), "ratings", s_scores
|
| 416 |
-
|
| 417 |
-
summary_text = generate_summary_text_content(
|
| 418 |
-
res, current_translations_dict,
|
| 419 |
-
s_gen, s_char, s_rat, s_sep, s_zh_in_sum
|
| 420 |
-
)
|
| 421 |
|
| 422 |
-
yield (
|
| 423 |
-
gr.update(interactive=True, value="🚀 开始分析"),
|
| 424 |
-
gr.update(visible=True, value="✅ 分析完成!"),
|
| 425 |
-
general_html,
|
| 426 |
-
char_html,
|
| 427 |
-
rating_html,
|
| 428 |
-
gr.update(value=summary_text),
|
| 429 |
-
res,
|
| 430 |
-
current_translations_dict,
|
| 431 |
-
tag_categories_original_order
|
| 432 |
-
)
|
| 433 |
|
| 434 |
except Exception as e:
|
| 435 |
import traceback
|
| 436 |
tb_str = traceback.format_exc()
|
| 437 |
print(f"处理时发生��误: {e}\n{tb_str}")
|
| 438 |
-
yield (
|
| 439 |
-
gr.update(interactive=True, value="🚀 开始分析"),
|
| 440 |
-
gr.update(visible=True, value=f"❌ 处理失败: {str(e)}"),
|
| 441 |
-
"<p>处理出错</p>", "<p>处理出错</p>", "<p>处理出错</p>",
|
| 442 |
-
gr.update(value=f"错误: {str(e)}", placeholder="分析失败..."),
|
| 443 |
-
{}, {}, {}
|
| 444 |
-
)
|
| 445 |
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
s_gen, s_char, s_rat, s_sep, s_zh_in_sum
|
| 449 |
-
current_res_from_state, current_translations_from_state
|
| 450 |
-
):
|
| 451 |
-
if not current_res_from_state:
|
| 452 |
-
return gr.update(placeholder="请先完成一次图像分析以生成汇总。", value="")
|
| 453 |
-
|
| 454 |
-
new_summary_text = generate_summary_text_content(
|
| 455 |
-
current_res_from_state, current_translations_from_state,
|
| 456 |
-
s_gen, s_char, s_rat, s_sep, s_zh_in_sum
|
| 457 |
-
)
|
| 458 |
return gr.update(value=new_summary_text)
|
| 459 |
|
| 460 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 461 |
btn.click(
|
| 462 |
process_image_and_generate_outputs,
|
| 463 |
-
inputs=[
|
| 464 |
-
|
| 465 |
-
sum_general, sum_char, sum_rating, sum_sep, sum_show_zh
|
| 466 |
-
],
|
| 467 |
-
outputs=[
|
| 468 |
-
btn, processing_info,
|
| 469 |
-
out_general, out_char, out_rating,
|
| 470 |
-
out_summary,
|
| 471 |
-
state_res, state_translations_dict, state_tag_categories_for_translation
|
| 472 |
-
],
|
| 473 |
-
# show_progress="full" # Gradio's built-in progress
|
| 474 |
)
|
| 475 |
|
| 476 |
summary_controls = [sum_general, sum_char, sum_rating, sum_sep, sum_show_zh]
|
| 477 |
for ctrl in summary_controls:
|
| 478 |
-
ctrl.change(
|
| 479 |
-
fn=update_summary_display,
|
| 480 |
-
inputs=summary_controls + [state_res, state_translations_dict],
|
| 481 |
-
outputs=[out_summary],
|
| 482 |
-
# show_progress=False # Typically fast, no need for progress indicator
|
| 483 |
-
)
|
| 484 |
|
| 485 |
-
# ------------------------------------------------------------------
|
| 486 |
-
# 启动
|
| 487 |
-
# ------------------------------------------------------------------
|
| 488 |
if __name__ == "__main__":
|
| 489 |
if tagger_instance is None:
|
| 490 |
print("CRITICAL: Tagger 未能初始化,应用功能将受限。请检查之前的错误信息。")
|
| 491 |
-
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
| 7 |
import pandas as pd
|
| 8 |
from PIL import Image
|
| 9 |
from huggingface_hub import login
|
| 10 |
+
from translator import translate_texts, translate_texts_with_dynamic_keys
|
|
|
|
| 11 |
|
| 12 |
# ------------------------------------------------------------------
|
| 13 |
+
# 模型与认证配置
|
| 14 |
# ------------------------------------------------------------------
|
| 15 |
MODEL_REPO = "SmilingWolf/wd-eva02-large-tagger-v3"
|
| 16 |
MODEL_FILENAME = "model.onnx"
|
| 17 |
LABEL_FILENAME = "selected_tags.csv"
|
| 18 |
+
OWNER_USERNAME = os.environ.get("OWNER_USERNAME", "")
|
| 19 |
|
| 20 |
HF_TOKEN = os.environ.get("HF_TOKEN", "")
|
| 21 |
if HF_TOKEN:
|
| 22 |
+
try:
|
| 23 |
+
login(token=HF_TOKEN)
|
| 24 |
+
print("✅ HF_TOKEN 登录成功")
|
| 25 |
+
except Exception as e:
|
| 26 |
+
print(f"⚠️ HF_TOKEN 登录失败: {e}")
|
| 27 |
else:
|
| 28 |
print("⚠️ 未检测到 HF_TOKEN,私有模型可能下载失败")
|
| 29 |
|
|
|
|
|
|
|
|
|
|
| 30 |
class Tagger:
|
| 31 |
def __init__(self):
|
| 32 |
self.hf_token = HF_TOKEN
|
|
|
|
| 60 |
raise RuntimeError(f"模型初始化失败: {e}")
|
| 61 |
|
| 62 |
|
|
|
|
| 63 |
def _preprocess(self, img: Image.Image) -> np.ndarray:
|
| 64 |
if img is None:
|
| 65 |
raise ValueError("输入图像不能为空")
|
|
|
|
| 70 |
canvas.paste(img, ((size - img.width) // 2, (size - img.height) // 2))
|
| 71 |
if size != self.input_size:
|
| 72 |
canvas = canvas.resize((self.input_size, self.input_size), Image.BICUBIC)
|
| 73 |
+
return np.array(canvas)[:, :, ::-1].astype(np.float32)
|
| 74 |
|
|
|
|
| 75 |
def predict(self, img: Image.Image, gen_th: float = 0.35, char_th: float = 0.85):
|
| 76 |
if self.model is None:
|
| 77 |
raise RuntimeError("模型未成功加载,无法进行预测。")
|
|
|
|
| 110 |
|
| 111 |
return res, tag_categories_for_translation
|
| 112 |
|
|
|
|
| 113 |
try:
|
| 114 |
tagger_instance = Tagger()
|
| 115 |
except RuntimeError as e:
|
| 116 |
print(f"应用启动时Tagger初始化失败: {e}")
|
| 117 |
+
tagger_instance = None
|
| 118 |
|
|
|
|
|
|
|
|
|
|
| 119 |
custom_css = """
|
| 120 |
+
.label-container { max-height: 300px; overflow-y: auto; border: 1px solid #ddd; padding: 10px; border-radius: 5px; background-color: #f9f9f9; }
|
| 121 |
+
.tag-item { display: flex; justify-content: space-between; align-items: center; margin: 2px 0; padding: 2px 5px; border-radius: 3px; background-color: #fff; transition: background-color 0.2s; }
|
| 122 |
+
.tag-item:hover { background-color: #f0f0f0; }
|
| 123 |
+
.tag-en { font-weight: bold; color: #333; cursor: pointer; }
|
| 124 |
+
.tag-zh { color: #666; margin-left: 10px; }
|
| 125 |
+
.tag-score { color: #999; font-size: 0.9em; }
|
| 126 |
+
.btn-analyze-container { margin-top: 15px; margin-bottom: 15px; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
"""
|
| 128 |
|
| 129 |
_js_functions = """
|
| 130 |
function copyToClipboard(text) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
if (typeof text === 'undefined' || text === null) {
|
| 132 |
+
console.warn('copyToClipboard was called with undefined or null text.');
|
|
|
|
| 133 |
return;
|
| 134 |
}
|
|
|
|
| 135 |
navigator.clipboard.writeText(text).then(() => {
|
|
|
|
| 136 |
const feedback = document.createElement('div');
|
| 137 |
+
let displayText = String(text);
|
|
|
|
|
|
|
| 138 |
displayText = displayText.substring(0, 30) + (displayText.length > 30 ? '...' : '');
|
|
|
|
| 139 |
feedback.textContent = '已复制: ' + displayText;
|
| 140 |
+
feedback.style.cssText = 'position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%); background-color: #4CAF50; color: white; padding: 10px 20px; border-radius: 5px; z-index: 10000; transition: opacity 0.5s ease-out;';
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
document.body.appendChild(feedback);
|
| 142 |
setTimeout(() => {
|
| 143 |
feedback.style.opacity = '0';
|
| 144 |
+
setTimeout(() => { if (document.body.contains(feedback)) document.body.removeChild(feedback); }, 500);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
}, 1500);
|
| 146 |
}).catch(err => {
|
| 147 |
console.error('Failed to copy tag. Error:', err, 'Attempted to copy text:', text);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
});
|
| 149 |
}
|
| 150 |
"""
|
|
|
|
| 161 |
with gr.Row():
|
| 162 |
with gr.Column(scale=1):
|
| 163 |
img_in = gr.Image(type="pil", label="上传图片", height=300)
|
|
|
|
| 164 |
btn = gr.Button("🚀 开始分析", variant="primary", elem_classes=["btn-analyze-container"])
|
| 165 |
|
| 166 |
with gr.Accordion("⚙️ 高级设置", open=False):
|
| 167 |
gen_slider = gr.Slider(0, 1, value=0.35, step=0.01, label="通用标签阈值", info="越高 → 标签更少更准")
|
| 168 |
char_slider = gr.Slider(0, 1, value=0.85, step=0.01, label="角色标签阈值", info="推荐保持较高阈值")
|
| 169 |
show_tag_scores = gr.Checkbox(True, label="在列表中显示标签置信度")
|
| 170 |
+
|
| 171 |
+
with gr.Group(visible=False) as guest_api_group:
|
| 172 |
+
gr.Markdown("### 访客翻译API配置\n由于您不是本空间所有者,需要提供自己的翻译API密钥才能使用翻译功能。")
|
| 173 |
+
guest_tencent_id = gr.Textbox(label="腾讯云 Secret ID", type="password")
|
| 174 |
+
guest_tencent_key = gr.Textbox(label="腾讯云 Secret Key", type="password")
|
| 175 |
+
guest_baidu_json = gr.TextArea(
|
| 176 |
+
label="百度翻译凭证 JSON",
|
| 177 |
+
placeholder='[{"app_id": "...", "secret_key": "..."}, ...]',
|
| 178 |
+
lines=3
|
| 179 |
+
)
|
| 180 |
|
| 181 |
with gr.Accordion("📊 标签汇总设置", open=True):
|
| 182 |
gr.Markdown("选择要包含在下方汇总文本框中的标签类别:")
|
|
|
|
| 207 |
show_copy_button=True
|
| 208 |
)
|
| 209 |
|
|
|
|
| 210 |
def format_tags_html(tags_dict, translations_list, category_name, show_scores=True, show_translation_in_list=True):
|
| 211 |
+
if not tags_dict: return "<p>暂无标签</p>"
|
|
|
|
|
|
|
| 212 |
html = '<div class="label-container">'
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
tag_keys = list(tags_dict.keys())
|
|
|
|
| 214 |
for i, tag in enumerate(tag_keys):
|
| 215 |
score = tags_dict[tag]
|
| 216 |
+
escaped_tag = tag.replace("'", "\\'")
|
|
|
|
| 217 |
html += '<div class="tag-item">'
|
| 218 |
tag_display_html = f'<span class="tag-en" onclick="copyToClipboard(\'{escaped_tag}\')">{tag}</span>'
|
|
|
|
| 219 |
if show_translation_in_list and i < len(translations_list) and translations_list[i]:
|
| 220 |
tag_display_html += f'<span class="tag-zh">({translations_list[i]})</span>'
|
|
|
|
| 221 |
html += f'<div>{tag_display_html}</div>'
|
| 222 |
+
if show_scores: html += f'<span class="tag-score">{score:.3f}</span>'
|
|
|
|
| 223 |
html += '</div>'
|
| 224 |
html += '</div>'
|
| 225 |
return html
|
| 226 |
|
| 227 |
+
def generate_summary_text_content(current_res, current_translations_dict, s_gen, s_char, s_rat, s_sep_type, s_show_zh):
|
| 228 |
+
if not current_res: return "请先分析图像或选择要汇总的标签类别。"
|
| 229 |
+
summary_parts, separator = [], {"逗号": ", ", "换行": "\n", "空格": " "}.get(s_sep_type, ", ")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 230 |
categories_to_summarize = []
|
| 231 |
if s_gen: categories_to_summarize.append("general")
|
| 232 |
if s_char: categories_to_summarize.append("characters")
|
| 233 |
if s_rat: categories_to_summarize.append("ratings")
|
| 234 |
+
if not categories_to_summarize: return "请至少选择一个标签类别进行汇总。"
|
|
|
|
|
|
|
| 235 |
|
| 236 |
for cat_key in categories_to_summarize:
|
| 237 |
if current_res.get(cat_key):
|
| 238 |
tags_to_join = []
|
| 239 |
cat_tags_en = list(current_res[cat_key].keys())
|
| 240 |
cat_translations = current_translations_dict.get(cat_key, [])
|
|
|
|
| 241 |
for i, en_tag in enumerate(cat_tags_en):
|
| 242 |
if s_show_zh and i < len(cat_translations) and cat_translations[i]:
|
| 243 |
tags_to_join.append(f"{en_tag}({cat_translations[i]})")
|
| 244 |
else:
|
| 245 |
tags_to_join.append(en_tag)
|
| 246 |
+
if tags_to_join: summary_parts.append(separator.join(tags_to_join))
|
| 247 |
+
joiner = "\n\n" if separator != "\n" and len(summary_parts) > 1 else separator
|
|
|
|
|
|
|
|
|
|
|
|
|
| 248 |
final_summary = joiner.join(summary_parts)
|
| 249 |
return final_summary if final_summary else "选定的类别中没有找到标签。"
|
| 250 |
|
| 251 |
+
def process_image_and_generate_outputs(img, g_th, c_th, s_scores, s_gen, s_char, s_rat, s_sep, s_zh_in_sum, guest_tc_id, guest_tc_key, guest_bd_json, request: gr.Request):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
if img is None:
|
| 253 |
+
yield (gr.update(interactive=True, value="🚀 开始分析"), gr.update(visible=True, value="❌ 请先上传图片。"), "", "", "", "", gr.update(placeholder="请先上传图片并开始分析..."), {}, {}, {})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
return
|
|
|
|
| 255 |
if tagger_instance is None:
|
| 256 |
+
yield (gr.update(interactive=True, value="🚀 开始分析"), gr.update(visible=True, value="❌ 分析器未成功初始化,请检查控制台错误。"), "", "", "", "", gr.update(placeholder="分析器初始化失败..."), {}, {}, {})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
return
|
| 258 |
|
| 259 |
+
yield (gr.update(interactive=False, value="🔄 处理中..."), gr.update(visible=True, value="🔄 正在分析图像..."), gr.HTML(value="<p>分析中...</p>"), gr.HTML(value="<p>分析中...</p>"), gr.HTML(value="<p>分析中...</p>"), gr.update(value="分析中..."), {}, {}, {})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 260 |
|
| 261 |
try:
|
|
|
|
| 262 |
res, tag_categories_original_order = tagger_instance.predict(img, g_th, c_th)
|
| 263 |
+
all_tags_to_translate = [tag for cat_key in ["general", "characters", "ratings"] for tag in tag_categories_original_order.get(cat_key, [])]
|
|
|
|
|
|
|
|
|
|
| 264 |
|
| 265 |
all_translations_flat = []
|
| 266 |
if all_tags_to_translate:
|
| 267 |
+
is_owner = request.username and request.username == OWNER_USERNAME
|
| 268 |
+
if is_owner:
|
| 269 |
+
print("- [Auth] 所有者身份,使用预置密钥进行翻译。")
|
| 270 |
+
all_translations_flat = translate_texts(all_tags_to_translate)
|
| 271 |
+
else:
|
| 272 |
+
print("- [Auth] 访客身份,使用用户提供的密钥进行翻译。")
|
| 273 |
+
if not guest_tc_id and not guest_bd_json:
|
| 274 |
+
print(" - [Warning] 访客未提供任何API密钥,将跳过翻译。")
|
| 275 |
+
all_translations_flat = all_tags_to_translate
|
| 276 |
+
else:
|
| 277 |
+
all_translations_flat = translate_texts_with_dynamic_keys(all_tags_to_translate, guest_tc_id, guest_tc_key, guest_bd_json)
|
| 278 |
+
|
| 279 |
current_translations_dict = {}
|
| 280 |
offset = 0
|
| 281 |
for cat_key in ["general", "characters", "ratings"]:
|
| 282 |
+
num_tags = len(tag_categories_original_order.get(cat_key, []))
|
| 283 |
+
current_translations_dict[cat_key] = all_translations_flat[offset : offset + num_tags]
|
| 284 |
+
offset += num_tags
|
|
|
|
|
|
|
|
|
|
|
|
|
| 285 |
|
| 286 |
+
general_html = format_tags_html(res.get("general", {}), current_translations_dict.get("general", []), "general", s_scores)
|
| 287 |
+
char_html = format_tags_html(res.get("characters", {}), current_translations_dict.get("characters", []), "characters", s_scores)
|
| 288 |
+
rating_html = format_tags_html(res.get("ratings", {}), current_translations_dict.get("ratings", []), "ratings", s_scores)
|
| 289 |
+
summary_text = generate_summary_text_content(res, current_translations_dict, s_gen, s_char, s_rat, s_sep, s_zh_in_sum)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
|
| 291 |
+
yield (gr.update(interactive=True, value="🚀 开始分析"), gr.update(visible=True, value="✅ 分析完成!"), general_html, char_html, rating_html, gr.update(value=summary_text), res, current_translations_dict, tag_categories_original_order)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
|
| 293 |
except Exception as e:
|
| 294 |
import traceback
|
| 295 |
tb_str = traceback.format_exc()
|
| 296 |
print(f"处理时发生��误: {e}\n{tb_str}")
|
| 297 |
+
yield (gr.update(interactive=True, value="🚀 开始分析"), gr.update(visible=True, value=f"❌ 处理失败: {str(e)}"), "<p>处理出错</p>", "<p>处理出错</p>", "<p>处理出错</p>", gr.update(value=f"错误: {str(e)}", placeholder="分析失败..."), {}, {}, {})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
|
| 299 |
+
def update_summary_display(s_gen, s_char, s_rat, s_sep, s_zh_in_sum, current_res, current_translations):
|
| 300 |
+
if not current_res: return gr.update(placeholder="请先完成一次图像分析以生成汇总。", value="")
|
| 301 |
+
new_summary_text = generate_summary_text_content(current_res, current_translations, s_gen, s_char, s_rat, s_sep, s_zh_in_sum)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
return gr.update(value=new_summary_text)
|
| 303 |
|
| 304 |
+
def check_user_auth(request: gr.Request):
|
| 305 |
+
if not OWNER_USERNAME: print("⚠️ 警告: 未设置 OWNER_USERNAME 环境变量。所有用户都将被视为访客。")
|
| 306 |
+
if not request.username or request.username != OWNER_USERNAME:
|
| 307 |
+
print(f"- [Auth] 访客 '{request.username}' 已连接,显示 API Key 输入框。")
|
| 308 |
+
return gr.update(visible=True)
|
| 309 |
+
print(f"- [Auth] 所有者 '{request.username}' 已连接。")
|
| 310 |
+
return gr.update(visible=False)
|
| 311 |
+
|
| 312 |
+
demo.load(fn=check_user_auth, inputs=None, outputs=[guest_api_group])
|
| 313 |
+
|
| 314 |
btn.click(
|
| 315 |
process_image_and_generate_outputs,
|
| 316 |
+
inputs=[img_in, gen_slider, char_slider, show_tag_scores, sum_general, sum_char, sum_rating, sum_sep, sum_show_zh, guest_tencent_id, guest_tencent_key, guest_baidu_json],
|
| 317 |
+
outputs=[btn, processing_info, out_general, out_char, out_rating, out_summary, state_res, state_translations_dict, state_tag_categories_for_translation]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 318 |
)
|
| 319 |
|
| 320 |
summary_controls = [sum_general, sum_char, sum_rating, sum_sep, sum_show_zh]
|
| 321 |
for ctrl in summary_controls:
|
| 322 |
+
ctrl.change(fn=update_summary_display, inputs=summary_controls + [state_res, state_translations_dict], outputs=[out_summary])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 323 |
|
|
|
|
|
|
|
|
|
|
| 324 |
if __name__ == "__main__":
|
| 325 |
if tagger_instance is None:
|
| 326 |
print("CRITICAL: Tagger 未能初始化,应用功能将受限。请检查之前的错误信息。")
|
| 327 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|