Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,26 +6,15 @@ import numpy as np
|
|
| 6 |
import onnxruntime as rt
|
| 7 |
import pandas as pd
|
| 8 |
from PIL import Image
|
| 9 |
-
from huggingface_hub import
|
| 10 |
-
|
|
|
|
| 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):
|
|
@@ -59,12 +48,9 @@ class Tagger:
|
|
| 59 |
print(f"❌ 模型或标签加载失败: {e}")
|
| 60 |
raise RuntimeError(f"模型初始化失败: {e}")
|
| 61 |
|
| 62 |
-
|
| 63 |
def _preprocess(self, img: Image.Image) -> np.ndarray:
|
| 64 |
-
if img is None:
|
| 65 |
-
|
| 66 |
-
if img.mode != "RGB":
|
| 67 |
-
img = img.convert("RGB")
|
| 68 |
size = max(img.size)
|
| 69 |
canvas = Image.new("RGB", (size, size), (255, 255, 255))
|
| 70 |
canvas.paste(img, ((size - img.width) // 2, (size - img.height) // 2))
|
|
@@ -73,43 +59,32 @@ class Tagger:
|
|
| 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("模型未成功加载,无法进行预测。")
|
| 78 |
inp_name = self.model.get_inputs()[0].name
|
| 79 |
outputs = self.model.run(None, {inp_name: self._preprocess(img)[None, ...]})[0][0]
|
| 80 |
|
| 81 |
res = {"ratings": {}, "general": {}, "characters": {}}
|
| 82 |
tag_categories_for_translation = {"ratings": [], "general": [], "characters": []}
|
| 83 |
|
| 84 |
-
for
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
res["general"] = dict(sorted(res["general"].items(), key=lambda kv: kv[1], reverse=True))
|
| 103 |
-
res["characters"] = dict(sorted(res["characters"].items(), key=lambda kv: kv[1], reverse=True))
|
| 104 |
-
res["ratings"] = dict(sorted(res["ratings"].items(), key=lambda kv: kv[1], reverse=True))
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
tag_categories_for_translation["general"] = list(res["general"].keys())
|
| 108 |
-
tag_categories_for_translation["characters"] = list(res["characters"].keys())
|
| 109 |
-
tag_categories_for_translation["ratings"] = list(res["ratings"].keys())
|
| 110 |
|
| 111 |
return res, tag_categories_for_translation
|
| 112 |
-
|
| 113 |
try:
|
| 114 |
tagger_instance = Tagger()
|
| 115 |
except RuntimeError as e:
|
|
@@ -134,10 +109,13 @@ function copyToClipboard(text) {
|
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
document.body.appendChild(feedback);
|
| 142 |
setTimeout(() => {
|
| 143 |
feedback.style.opacity = '0';
|
|
@@ -152,11 +130,14 @@ function copyToClipboard(text) {
|
|
| 152 |
with gr.Blocks(theme=gr.themes.Soft(), title="AI 图像标签分析器", css=custom_css, js=_js_functions) as demo:
|
| 153 |
gr.Markdown("# 🖼️ AI 图像标签分析器")
|
| 154 |
gr.Markdown("上传图片自动识别标签,支持中英文显示和一键复制。[NovelAI在线绘画](https://nai.idlecloud.cc/)")
|
| 155 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
state_res = gr.State({})
|
| 157 |
state_translations_dict = gr.State({})
|
| 158 |
-
state_tag_categories_for_translation = gr.State({})
|
| 159 |
-
|
| 160 |
|
| 161 |
with gr.Row():
|
| 162 |
with gr.Column(scale=1):
|
|
@@ -164,164 +145,158 @@ with gr.Blocks(theme=gr.themes.Soft(), title="AI 图像标签分析器", css=cus
|
|
| 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="通用标签阈值"
|
| 168 |
-
char_slider = gr.Slider(0, 1, value=0.85, step=0.01, label="角色标签阈值"
|
| 169 |
show_tag_scores = gr.Checkbox(True, label="在列表中显示标签置信度")
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
placeholder='[{"app_id": "...", "secret_key": "..."}, ...]',
|
| 178 |
-
lines=3
|
| 179 |
-
)
|
| 180 |
-
|
| 181 |
with gr.Accordion("📊 标签汇总设置", open=True):
|
| 182 |
-
gr.
|
| 183 |
-
|
| 184 |
-
sum_general = gr.Checkbox(True, label="通用标签", min_width=50)
|
| 185 |
-
sum_char = gr.Checkbox(True, label="角色标签", min_width=50)
|
| 186 |
-
sum_rating = gr.Checkbox(False, label="评分标签", min_width=50)
|
| 187 |
-
sum_sep = gr.Dropdown(["逗号", "换行", "空格"], value="逗号", label="标签之间的分隔符")
|
| 188 |
sum_show_zh = gr.Checkbox(False, label="在汇总中显示中文翻译")
|
| 189 |
|
| 190 |
processing_info = gr.Markdown("", visible=False)
|
| 191 |
|
| 192 |
with gr.Column(scale=2):
|
| 193 |
with gr.Tabs():
|
| 194 |
-
with gr.TabItem("🏷️ 通用标签"):
|
| 195 |
-
|
| 196 |
-
with gr.TabItem("
|
| 197 |
-
gr.Markdown("<p style='color:gray; font-size:small;'>提示:角色标签推测基于截至2024年2月的数据。</p>")
|
| 198 |
-
out_char = gr.HTML(label="Character Tags")
|
| 199 |
-
with gr.TabItem("⭐ 评分标签"):
|
| 200 |
-
out_rating = gr.HTML(label="Rating Tags")
|
| 201 |
-
|
| 202 |
gr.Markdown("### 标签汇总结果")
|
| 203 |
-
out_summary = gr.Textbox(
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
if not tags_dict: return "<p>暂无标签</p>"
|
| 212 |
html = '<div class="label-container">'
|
| 213 |
-
|
| 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
|
| 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
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 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 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 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 |
-
|
| 254 |
-
return
|
| 255 |
if tagger_instance is None:
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 260 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 261 |
try:
|
| 262 |
-
res,
|
| 263 |
-
|
| 264 |
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 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 |
-
|
| 287 |
-
|
| 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
|
| 292 |
|
| 293 |
except Exception as e:
|
| 294 |
import traceback
|
| 295 |
-
|
| 296 |
-
|
| 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=[
|
| 317 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 318 |
)
|
| 319 |
|
| 320 |
-
summary_controls = [sum_general,
|
| 321 |
for ctrl in summary_controls:
|
| 322 |
-
ctrl.change(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|
|
|
|
| 6 |
import onnxruntime as rt
|
| 7 |
import pandas as pd
|
| 8 |
from PIL import Image
|
| 9 |
+
from huggingface_hub import whoami, get_space_runtime
|
| 10 |
+
|
| 11 |
+
from translator import translate_texts
|
| 12 |
|
|
|
|
|
|
|
|
|
|
| 13 |
MODEL_REPO = "SmilingWolf/wd-eva02-large-tagger-v3"
|
| 14 |
MODEL_FILENAME = "model.onnx"
|
| 15 |
LABEL_FILENAME = "selected_tags.csv"
|
|
|
|
| 16 |
|
| 17 |
+
HF_TOKEN = os.environ.get("HF_TOKEN")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
class Tagger:
|
| 20 |
def __init__(self):
|
|
|
|
| 48 |
print(f"❌ 模型或标签加载失败: {e}")
|
| 49 |
raise RuntimeError(f"模型初始化失败: {e}")
|
| 50 |
|
|
|
|
| 51 |
def _preprocess(self, img: Image.Image) -> np.ndarray:
|
| 52 |
+
if img is None: raise ValueError("输入图像不能为空")
|
| 53 |
+
if img.mode != "RGB": img = img.convert("RGB")
|
|
|
|
|
|
|
| 54 |
size = max(img.size)
|
| 55 |
canvas = Image.new("RGB", (size, size), (255, 255, 255))
|
| 56 |
canvas.paste(img, ((size - img.width) // 2, (size - img.height) // 2))
|
|
|
|
| 59 |
return np.array(canvas)[:, :, ::-1].astype(np.float32)
|
| 60 |
|
| 61 |
def predict(self, img: Image.Image, gen_th: float = 0.35, char_th: float = 0.85):
|
| 62 |
+
if self.model is None: raise RuntimeError("模型未成功加载,无法进行预测。")
|
|
|
|
| 63 |
inp_name = self.model.get_inputs()[0].name
|
| 64 |
outputs = self.model.run(None, {inp_name: self._preprocess(img)[None, ...]})[0][0]
|
| 65 |
|
| 66 |
res = {"ratings": {}, "general": {}, "characters": {}}
|
| 67 |
tag_categories_for_translation = {"ratings": [], "general": [], "characters": []}
|
| 68 |
|
| 69 |
+
for cat_key, cat_indices in self.categories.items():
|
| 70 |
+
sub_res = {}
|
| 71 |
+
if cat_key == "rating":
|
| 72 |
+
for idx in cat_indices:
|
| 73 |
+
tag_name = self.tag_names[idx].replace("_", " ")
|
| 74 |
+
sub_res[tag_name] = float(outputs[idx])
|
| 75 |
+
else:
|
| 76 |
+
threshold = char_th if cat_key == "character" else gen_th
|
| 77 |
+
for idx in cat_indices:
|
| 78 |
+
if outputs[idx] > threshold:
|
| 79 |
+
tag_name = self.tag_names[idx].replace("_", " ")
|
| 80 |
+
sub_res[tag_name] = float(outputs[idx])
|
| 81 |
+
|
| 82 |
+
# Use the correct key for 'character'
|
| 83 |
+
res_key = "characters" if cat_key == "character" else cat_key
|
| 84 |
+
res[res_key] = dict(sorted(sub_res.items(), key=lambda kv: kv[1], reverse=True))
|
| 85 |
+
tag_categories_for_translation[res_key] = list(res[res_key].keys())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
return res, tag_categories_for_translation
|
|
|
|
| 88 |
try:
|
| 89 |
tagger_instance = Tagger()
|
| 90 |
except RuntimeError as e:
|
|
|
|
| 109 |
}
|
| 110 |
navigator.clipboard.writeText(text).then(() => {
|
| 111 |
const feedback = document.createElement('div');
|
| 112 |
+
let displayText = String(text).substring(0, 30) + (String(text).length > 30 ? '...' : '');
|
|
|
|
| 113 |
feedback.textContent = '已复制: ' + displayText;
|
| 114 |
+
Object.assign(feedback.style, {
|
| 115 |
+
position: 'fixed', bottom: '20px', left: '50%', transform: 'translateX(-50%)',
|
| 116 |
+
backgroundColor: '#4CAF50', color: 'white', padding: '10px 20px',
|
| 117 |
+
borderRadius: '5px', zIndex: '10000', transition: 'opacity 0.5s ease-out'
|
| 118 |
+
});
|
| 119 |
document.body.appendChild(feedback);
|
| 120 |
setTimeout(() => {
|
| 121 |
feedback.style.opacity = '0';
|
|
|
|
| 130 |
with gr.Blocks(theme=gr.themes.Soft(), title="AI 图像标签分析器", css=custom_css, js=_js_functions) as demo:
|
| 131 |
gr.Markdown("# 🖼️ AI 图像标签分析器")
|
| 132 |
gr.Markdown("上传图片自动识别标签,支持中英文显示和一键复制。[NovelAI在线绘画](https://nai.idlecloud.cc/)")
|
| 133 |
+
|
| 134 |
+
with gr.Row():
|
| 135 |
+
with gr.Column(scale=1):
|
| 136 |
+
login_button = gr.LoginButton(value="🤗 通过 Hugging Face 登录")
|
| 137 |
+
user_status_md = gr.Markdown("ℹ️ 正在检查登录状态...")
|
| 138 |
+
|
| 139 |
state_res = gr.State({})
|
| 140 |
state_translations_dict = gr.State({})
|
|
|
|
|
|
|
| 141 |
|
| 142 |
with gr.Row():
|
| 143 |
with gr.Column(scale=1):
|
|
|
|
| 145 |
btn = gr.Button("🚀 开始分析", variant="primary", elem_classes=["btn-analyze-container"])
|
| 146 |
|
| 147 |
with gr.Accordion("⚙️ 高级设置", open=False):
|
| 148 |
+
gen_slider = gr.Slider(0, 1, value=0.35, step=0.01, label="通用标签阈值")
|
| 149 |
+
char_slider = gr.Slider(0, 1, value=0.85, step=0.01, label="角色标签阈值")
|
| 150 |
show_tag_scores = gr.Checkbox(True, label="在列表中显示标签置信度")
|
| 151 |
+
|
| 152 |
+
with gr.Accordion("🔑 自定义翻译密钥 (可选)", open=False, visible=False) as api_key_accordion:
|
| 153 |
+
gr.Markdown("如果你不是空间所有者,需要在这里提供自己的API密钥才能使用翻译功能。")
|
| 154 |
+
tencent_id_in = gr.Textbox(label="腾讯云 Secret ID", lines=1)
|
| 155 |
+
tencent_key_in = gr.Textbox(label="腾讯云 Secret Key", lines=1, type="password")
|
| 156 |
+
baidu_json_in = gr.Textbox(label="百度翻译凭证 (JSON 格式)", lines=3, placeholder='[{"app_id": "...", "secret_key": "..."}]')
|
| 157 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
with gr.Accordion("📊 标签汇总设置", open=True):
|
| 159 |
+
gr.CheckboxGroup(["通用标签", "角色标签", "评分标签"], value=["通用标签", "角色标签"], label="汇总类别")
|
| 160 |
+
sum_sep = gr.Dropdown(["逗号", "换行", "空格"], value="逗号", label="标签分隔符")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
sum_show_zh = gr.Checkbox(False, label="在汇总中显示中文翻译")
|
| 162 |
|
| 163 |
processing_info = gr.Markdown("", visible=False)
|
| 164 |
|
| 165 |
with gr.Column(scale=2):
|
| 166 |
with gr.Tabs():
|
| 167 |
+
with gr.TabItem("🏷️ 通用标签"): out_general = gr.HTML(label="General Tags")
|
| 168 |
+
with gr.TabItem("👤 角色标签"): out_char = gr.HTML(label="Character Tags")
|
| 169 |
+
with gr.TabItem("⭐ 评分标签"): out_rating = gr.HTML(label="Rating Tags")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
gr.Markdown("### 标签汇总结果")
|
| 171 |
+
out_summary = gr.Textbox(label="标签汇总", lines=5, show_copy_button=True)
|
| 172 |
+
|
| 173 |
+
def check_user_status(request: gr.Request):
|
| 174 |
+
token = request.token
|
| 175 |
+
if token:
|
| 176 |
+
try:
|
| 177 |
+
user_info = whoami(token=token)
|
| 178 |
+
space_runtime = get_space_runtime()
|
| 179 |
+
if space_runtime and user_info and user_info["name"] == space_runtime.owner:
|
| 180 |
+
return f"✅ 以所有者 **{user_info['fullname']}** 身份登录,将使用空间配置的密钥。", gr.update(visible=False)
|
| 181 |
+
else:
|
| 182 |
+
return f"👋 你好, **{user_info.get('fullname', '用户')}**!请在下方提供你自己的翻译 API 密钥。", gr.update(visible=True, open=True)
|
| 183 |
+
except Exception as e:
|
| 184 |
+
print(f"获取用户信息时出错: {e}")
|
| 185 |
+
return "⚠️ 无法验证您的登录状态。请提供 API 密钥。", gr.update(visible=True, open=True)
|
| 186 |
+
return "ℹ️ **访客模式**。如需使用翻译功能,请<a href='/login?redirect=/'>登录</a>或提供 API 密钥。", gr.update(visible=True, open=True)
|
| 187 |
+
|
| 188 |
+
def format_tags_html(tags_dict, translations_list, show_scores):
|
| 189 |
if not tags_dict: return "<p>暂无标签</p>"
|
| 190 |
html = '<div class="label-container">'
|
| 191 |
+
for i, (tag, score) in enumerate(tags_dict.items()):
|
|
|
|
|
|
|
| 192 |
escaped_tag = tag.replace("'", "\\'")
|
| 193 |
html += '<div class="tag-item">'
|
| 194 |
tag_display_html = f'<span class="tag-en" onclick="copyToClipboard(\'{escaped_tag}\')">{tag}</span>'
|
| 195 |
+
if i < len(translations_list) and translations_list[i]:
|
| 196 |
tag_display_html += f'<span class="tag-zh">({translations_list[i]})</span>'
|
| 197 |
html += f'<div>{tag_display_html}</div>'
|
| 198 |
if show_scores: html += f'<span class="tag-score">{score:.3f}</span>'
|
| 199 |
html += '</div>'
|
| 200 |
+
return html + '</div>'
|
| 201 |
+
|
| 202 |
+
def generate_summary_text_content(current_res, translations, sum_cats, sep_type, show_zh):
|
| 203 |
+
if not current_res: return "请先分析图像。"
|
| 204 |
+
parts, sep = [], {"逗号": ", ", "换行": "\n", "空格": " "}.get(sep_type, ", ")
|
| 205 |
+
cat_map = {"通用标签": "general", "角色标签": "characters", "评分标签": "ratings"}
|
| 206 |
+
for cat_name in sum_cats:
|
| 207 |
+
cat_key = cat_map[cat_name]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
if current_res.get(cat_key):
|
| 209 |
+
tags_en, trans = list(current_res[cat_key].keys()), translations.get(cat_key, [])
|
| 210 |
+
tags_to_join = [f"{en}({zh})" if show_zh and i < len(trans) and trans[i] else en for i, en in enumerate(tags_en)]
|
| 211 |
+
if tags_to_join: parts.append(sep.join(tags_to_join))
|
| 212 |
+
return "\n".join(parts) if parts else "选定的类别中没有找到标签。"
|
| 213 |
+
|
| 214 |
+
def process_image_and_generate_outputs(
|
| 215 |
+
img, g_th, c_th, s_scores,
|
| 216 |
+
user_tencent_id, user_tencent_key, user_baidu_json,
|
| 217 |
+
sum_cats, s_sep, s_zh_in_sum,
|
| 218 |
+
request: gr.Request
|
| 219 |
+
):
|
|
|
|
|
|
|
|
|
|
| 220 |
if img is None:
|
| 221 |
+
raise gr.Error("请先上传图片。")
|
|
|
|
| 222 |
if tagger_instance is None:
|
| 223 |
+
raise gr.Error("分析器未成功初始化,请检查后台错误。")
|
| 224 |
+
|
| 225 |
+
yield gr.update(interactive=False, value="🔄 处理中..."), gr.update(visible=True, value="🔄 正在分析..."), *["<p>分析中...</p>"]*3, "分析中...", {}, {}
|
| 226 |
+
|
| 227 |
+
token, is_owner = request.token, False
|
| 228 |
+
if token:
|
| 229 |
+
try:
|
| 230 |
+
user_info = whoami(token=token)
|
| 231 |
+
space_runtime = get_space_runtime()
|
| 232 |
+
if space_runtime and user_info and user_info["name"] == space_runtime.owner:
|
| 233 |
+
is_owner = True
|
| 234 |
+
except Exception: pass
|
| 235 |
|
| 236 |
+
final_tencent_id, final_tencent_key, baidu_json_str = (
|
| 237 |
+
(os.environ.get("TENCENT_SECRET_ID"), os.environ.get("TENCENT_SECRET_KEY"), os.environ.get("BAIDU_CREDENTIALS_JSON", "[]"))
|
| 238 |
+
if is_owner else (user_tencent_id, user_tencent_key, user_baidu_json)
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
final_baidu_creds_list = []
|
| 242 |
+
if baidu_json_str and baidu_json_str.strip():
|
| 243 |
+
try:
|
| 244 |
+
parsed_data = json.loads(baidu_json_str)
|
| 245 |
+
if isinstance(parsed_data, list): final_baidu_creds_list = parsed_data
|
| 246 |
+
except json.JSONDecodeError: print("提供的百度凭证JSON无效。")
|
| 247 |
+
|
| 248 |
try:
|
| 249 |
+
res, tag_cats_original = tagger_instance.predict(img, g_th, c_th)
|
| 250 |
+
all_tags = [tag for cat in tag_cats_original.values() for tag in cat]
|
| 251 |
|
| 252 |
+
translations_flat = translate_texts(
|
| 253 |
+
all_tags,
|
| 254 |
+
tencent_secret_id=final_tencent_id,
|
| 255 |
+
tencent_secret_key=final_tencent_key,
|
| 256 |
+
baidu_credentials_list=final_baidu_creds_list
|
| 257 |
+
) if all_tags else []
|
| 258 |
+
|
| 259 |
+
translations, offset = {}, 0
|
| 260 |
+
for cat_key, tags in tag_cats_original.items():
|
| 261 |
+
translations[cat_key] = translations_flat[offset : offset + len(tags)]
|
| 262 |
+
offset += len(tags)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 263 |
|
| 264 |
+
outputs_html = {k: format_tags_html(res.get(k, {}), translations.get(k, []), s_scores) for k in ["general", "characters", "ratings"]}
|
| 265 |
+
summary = generate_summary_text_content(res, translations, sum_cats, s_sep, s_zh_in_sum)
|
|
|
|
|
|
|
| 266 |
|
| 267 |
+
yield gr.update(interactive=True, value="🚀 开始分析"), gr.update(visible=True, value="✅ 分析完成!"), outputs_html["general"], outputs_html["characters"], outputs_html["ratings"], summary, res, translations
|
| 268 |
|
| 269 |
except Exception as e:
|
| 270 |
import traceback
|
| 271 |
+
traceback.print_exc()
|
| 272 |
+
raise gr.Error(f"处理时发生错误: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 273 |
|
| 274 |
+
demo.load(fn=check_user_status, outputs=[user_status_md, api_key_accordion], queue=False)
|
| 275 |
+
|
| 276 |
btn.click(
|
| 277 |
process_image_and_generate_outputs,
|
| 278 |
+
inputs=[
|
| 279 |
+
img_in, gen_slider, char_slider, show_tag_scores,
|
| 280 |
+
tencent_id_in, tencent_key_in, baidu_json_in,
|
| 281 |
+
sum_general, sum_sep, sum_show_zh
|
| 282 |
+
],
|
| 283 |
+
outputs=[
|
| 284 |
+
btn, processing_info,
|
| 285 |
+
out_general, out_char, out_rating,
|
| 286 |
+
out_summary,
|
| 287 |
+
state_res, state_translations_dict
|
| 288 |
+
],
|
| 289 |
)
|
| 290 |
|
| 291 |
+
summary_controls = [sum_general, sum_sep, sum_show_zh]
|
| 292 |
for ctrl in summary_controls:
|
| 293 |
+
ctrl.change(
|
| 294 |
+
fn=lambda r, t, c, s, z: generate_summary_text_content(r, t, c, s, z),
|
| 295 |
+
inputs=[state_res, state_translations_dict] + summary_controls,
|
| 296 |
+
outputs=[out_summary],
|
| 297 |
+
)
|
| 298 |
|
| 299 |
if __name__ == "__main__":
|
| 300 |
if tagger_instance is None:
|
| 301 |
+
print("CRITICAL: Tagger 未能初始化,应用功能将受限。")
|
| 302 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|