Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,8 +6,7 @@ import numpy as np
|
|
| 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 |
-
from huggingface_hub.hf_api import SpaceRuntime
|
| 11 |
|
| 12 |
from translator import translate_texts
|
| 13 |
|
|
@@ -19,6 +18,8 @@ MODEL_FILENAME = "model.onnx"
|
|
| 19 |
LABEL_FILENAME = "selected_tags.csv"
|
| 20 |
|
| 21 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
|
|
|
|
|
|
| 22 |
|
| 23 |
# ------------------------------------------------------------------
|
| 24 |
# Tagger 类 (全局实例化)
|
|
@@ -89,7 +90,6 @@ class Tagger:
|
|
| 89 |
tag_name = self.tag_names[idx].replace("_", " ")
|
| 90 |
sub_res[tag_name] = float(outputs[idx])
|
| 91 |
|
| 92 |
-
# Use the correct key for 'character'
|
| 93 |
res_key = "characters" if cat_key == "character" else cat_key
|
| 94 |
res[res_key] = dict(sorted(sub_res.items(), key=lambda kv: kv[1], reverse=True))
|
| 95 |
tag_categories_for_translation[res_key] = list(res[res_key].keys())
|
|
@@ -146,15 +146,13 @@ with gr.Blocks(theme=gr.themes.Soft(), title="AI 图像标签分析器", css=cus
|
|
| 146 |
gr.Markdown("# 🖼️ AI 图像标签分析器")
|
| 147 |
gr.Markdown("上传图片自动识别标签,支持中英文显示和一键复制。[NovelAI在线绘画](https://nai.idlecloud.cc/)")
|
| 148 |
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
login_button = gr.LoginButton(value="🤗 通过 Hugging Face 登录")
|
| 152 |
-
user_status_md = gr.Markdown("ℹ️ 正在检查登录状态...")
|
| 153 |
|
| 154 |
state_res = gr.State({})
|
| 155 |
state_translations_dict = gr.State({})
|
| 156 |
|
| 157 |
-
with gr.Row():
|
| 158 |
with gr.Column(scale=1):
|
| 159 |
img_in = gr.Image(type="pil", label="上传图片", height=300)
|
| 160 |
btn = gr.Button("🚀 开始分析", variant="primary", elem_classes=["btn-analyze-container"])
|
|
@@ -164,8 +162,9 @@ with gr.Blocks(theme=gr.themes.Soft(), title="AI 图像标签分析器", css=cus
|
|
| 164 |
char_slider = gr.Slider(0, 1, value=0.85, step=0.01, label="角色标签阈值")
|
| 165 |
show_tag_scores = gr.Checkbox(True, label="在列表中显示标签置信度")
|
| 166 |
|
| 167 |
-
with gr.Accordion("🔑
|
| 168 |
-
gr.Markdown("
|
|
|
|
| 169 |
tencent_id_in = gr.Textbox(label="腾讯云 Secret ID", lines=1)
|
| 170 |
tencent_key_in = gr.Textbox(label="腾讯云 Secret Key", lines=1, type="password")
|
| 171 |
baidu_json_in = gr.Textbox(label="百度翻译凭证 (JSON 格式)", lines=3, placeholder='[{"app_id": "...", "secret_key": "..."}]')
|
|
@@ -192,37 +191,20 @@ with gr.Blocks(theme=gr.themes.Soft(), title="AI 图像标签分析器", css=cus
|
|
| 192 |
return auth_header.split(" ")[1]
|
| 193 |
return None
|
| 194 |
|
| 195 |
-
def check_user_is_owner(user_info: dict | None, space_runtime: SpaceRuntime | None) -> bool:
|
| 196 |
-
"""检查用户是否是空间的所有者(处理个人和组织空间)。"""
|
| 197 |
-
if not user_info or not space_runtime:
|
| 198 |
-
return False
|
| 199 |
-
|
| 200 |
-
# 情况1:空间由用户直接拥有
|
| 201 |
-
if user_info.get("name") == space_runtime.owner:
|
| 202 |
-
return True
|
| 203 |
-
|
| 204 |
-
# 情况2:空间由用户所属的组织拥有
|
| 205 |
-
user_orgs = user_info.get("orgs", [])
|
| 206 |
-
if any(org.get("name") == space_runtime.owner for org in user_orgs):
|
| 207 |
-
return True
|
| 208 |
-
|
| 209 |
-
return False
|
| 210 |
-
|
| 211 |
def check_user_status(request: gr.Request):
|
| 212 |
token = get_token_from_request(request)
|
| 213 |
if token:
|
| 214 |
try:
|
| 215 |
user_info = whoami(token=token)
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
if check_user_is_owner(user_info, space_runtime):
|
| 219 |
-
return f"✅ 以所有者 **{user_info.get('fullname', user_info.get('name'))}** 身份登录,将使用空间配置的密钥。", gr.update(visible=False)
|
| 220 |
-
else:
|
| 221 |
-
return f"👋 你好, **{user_info.get('fullname', '用户')}**!请在下方提供你自己的翻译 API 密钥。", gr.update(visible=True, open=True)
|
| 222 |
except Exception as e:
|
| 223 |
-
print(f"
|
| 224 |
-
|
| 225 |
-
|
|
|
|
|
|
|
|
|
|
| 226 |
|
| 227 |
def format_tags_html(tags_dict, translations_list, show_scores):
|
| 228 |
if not tags_dict: return "<p>暂无标签</p>"
|
|
@@ -253,10 +235,12 @@ with gr.Blocks(theme=gr.themes.Soft(), title="AI 图像标签分析器", css=cus
|
|
| 253 |
# ----------------- 主要处理回调 -----------------
|
| 254 |
def process_image_and_generate_outputs(
|
| 255 |
img, g_th, c_th, s_scores,
|
| 256 |
-
user_tencent_id, user_tencent_key, user_baidu_json,
|
| 257 |
sum_cats, s_sep, s_zh_in_sum,
|
| 258 |
request: gr.Request
|
| 259 |
):
|
|
|
|
|
|
|
| 260 |
if img is None:
|
| 261 |
raise gr.Error("请先上传图片。")
|
| 262 |
if tagger_instance is None:
|
|
@@ -264,19 +248,12 @@ with gr.Blocks(theme=gr.themes.Soft(), title="AI 图像标签分析器", css=cus
|
|
| 264 |
|
| 265 |
yield gr.update(interactive=False, value="🔄 处理中..."), gr.update(visible=True, value="🔄 正在分析..."), *["<p>分析中...</p>"]*3, "分析中...", {}, {}
|
| 266 |
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
if token:
|
| 270 |
-
try:
|
| 271 |
-
user_info = whoami(token=token)
|
| 272 |
-
space_runtime = get_space_runtime()
|
| 273 |
-
if check_user_is_owner(user_info, space_runtime):
|
| 274 |
-
is_owner = True
|
| 275 |
-
except Exception: pass
|
| 276 |
|
| 277 |
final_tencent_id, final_tencent_key, baidu_json_str = (
|
| 278 |
(os.environ.get("TENCENT_SECRET_ID"), os.environ.get("TENCENT_SECRET_KEY"), os.environ.get("BAIDU_CREDENTIALS_JSON", "[]"))
|
| 279 |
-
if
|
| 280 |
)
|
| 281 |
|
| 282 |
final_baidu_creds_list = []
|
|
@@ -305,7 +282,7 @@ with gr.Blocks(theme=gr.themes.Soft(), title="AI 图像标签分析器", css=cus
|
|
| 305 |
outputs_html = {k: format_tags_html(res.get(k, {}), translations.get(k, []), s_scores) for k in ["general", "characters", "ratings"]}
|
| 306 |
summary = generate_summary_text_content(res, translations, sum_cats, s_sep, s_zh_in_sum)
|
| 307 |
|
| 308 |
-
yield gr.update(interactive=True, value="🚀 开始分析"), gr.update(visible=True, value="✅ 分析完成!"), outputs_html["general"], outputs_html["characters"], outputs_html["ratings"], summary, res, translations
|
| 309 |
|
| 310 |
except Exception as e:
|
| 311 |
import traceback
|
|
@@ -313,13 +290,13 @@ with gr.Blocks(theme=gr.themes.Soft(), title="AI 图像标签分析器", css=cus
|
|
| 313 |
raise gr.Error(f"处理时发生错误: {e}")
|
| 314 |
|
| 315 |
# ----------------- 绑定事件 -----------------
|
| 316 |
-
demo.load(fn=check_user_status, inputs=None, outputs=[user_status_md,
|
| 317 |
|
| 318 |
btn.click(
|
| 319 |
process_image_and_generate_outputs,
|
| 320 |
inputs=[
|
| 321 |
img_in, gen_slider, char_slider, show_tag_scores,
|
| 322 |
-
tencent_id_in, tencent_key_in, baidu_json_in,
|
| 323 |
sum_cats, sum_sep, sum_show_zh
|
| 324 |
],
|
| 325 |
outputs=[
|
|
@@ -341,5 +318,4 @@ with gr.Blocks(theme=gr.themes.Soft(), title="AI 图像标签分析器", css=cus
|
|
| 341 |
if __name__ == "__main__":
|
| 342 |
if tagger_instance is None:
|
| 343 |
print("CRITICAL: Tagger 未能初始化,应用功能将受限。")
|
| 344 |
-
demo.launch(server_name="0.0.0.0", server_port=7860)
|
| 345 |
-
|
|
|
|
| 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 |
|
|
|
|
| 18 |
LABEL_FILENAME = "selected_tags.csv"
|
| 19 |
|
| 20 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 21 |
+
# 新增:从环境变量读取访问密码
|
| 22 |
+
ACCESS_PASSWORD = os.environ.get("ACCESS_PASSWORD")
|
| 23 |
|
| 24 |
# ------------------------------------------------------------------
|
| 25 |
# Tagger 类 (全局实例化)
|
|
|
|
| 90 |
tag_name = self.tag_names[idx].replace("_", " ")
|
| 91 |
sub_res[tag_name] = float(outputs[idx])
|
| 92 |
|
|
|
|
| 93 |
res_key = "characters" if cat_key == "character" else cat_key
|
| 94 |
res[res_key] = dict(sorted(sub_res.items(), key=lambda kv: kv[1], reverse=True))
|
| 95 |
tag_categories_for_translation[res_key] = list(res[res_key].keys())
|
|
|
|
| 146 |
gr.Markdown("# 🖼️ AI 图像标签分析器")
|
| 147 |
gr.Markdown("上传图片自动识别标签,支持中英文显示和一键复制。[NovelAI在线绘画](https://nai.idlecloud.cc/)")
|
| 148 |
|
| 149 |
+
# 登录状态显示
|
| 150 |
+
user_status_md = gr.Markdown("ℹ️ 正在检查登录状态...")
|
|
|
|
|
|
|
| 151 |
|
| 152 |
state_res = gr.State({})
|
| 153 |
state_translations_dict = gr.State({})
|
| 154 |
|
| 155 |
+
with gr.Row(visible=False) as main_interface: # 默认隐藏主界面
|
| 156 |
with gr.Column(scale=1):
|
| 157 |
img_in = gr.Image(type="pil", label="上传图片", height=300)
|
| 158 |
btn = gr.Button("🚀 开始分析", variant="primary", elem_classes=["btn-analyze-container"])
|
|
|
|
| 162 |
char_slider = gr.Slider(0, 1, value=0.85, step=0.01, label="角色标签阈值")
|
| 163 |
show_tag_scores = gr.Checkbox(True, label="在列表中显示标签置信度")
|
| 164 |
|
| 165 |
+
with gr.Accordion("🔑 翻译密钥设置", open=True):
|
| 166 |
+
gr.Markdown("输入访问密码可使用空间配置的密钥,否则请提供您自己的密钥。")
|
| 167 |
+
access_password_in = gr.Textbox(label="访问密码 (可选)", type="password", lines=1)
|
| 168 |
tencent_id_in = gr.Textbox(label="腾讯云 Secret ID", lines=1)
|
| 169 |
tencent_key_in = gr.Textbox(label="腾讯云 Secret Key", lines=1, type="password")
|
| 170 |
baidu_json_in = gr.Textbox(label="百度翻译凭证 (JSON 格式)", lines=3, placeholder='[{"app_id": "...", "secret_key": "..."}]')
|
|
|
|
| 191 |
return auth_header.split(" ")[1]
|
| 192 |
return None
|
| 193 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
def check_user_status(request: gr.Request):
|
| 195 |
token = get_token_from_request(request)
|
| 196 |
if token:
|
| 197 |
try:
|
| 198 |
user_info = whoami(token=token)
|
| 199 |
+
welcome_msg = f"✅ 您好, **{user_info.get('fullname', user_info.get('name'))}**!欢迎使用本应用。"
|
| 200 |
+
return welcome_msg, gr.update(visible=True) # 显示主界面
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
except Exception as e:
|
| 202 |
+
print(f"Token 无效或已过期: {e}")
|
| 203 |
+
|
| 204 |
+
# 未登录或Token无效
|
| 205 |
+
login_url = "/login?redirect=/"
|
| 206 |
+
msg = f"**<p style='color:red; text-align:center;'>🚫 检测到您尚未登录,请先 <a href='{login_url}' target='_top'>[点击此处登录]</a> 后刷新页面。</p>**"
|
| 207 |
+
return msg, gr.update(visible=False) # 隐藏主界面
|
| 208 |
|
| 209 |
def format_tags_html(tags_dict, translations_list, show_scores):
|
| 210 |
if not tags_dict: return "<p>暂无标签</p>"
|
|
|
|
| 235 |
# ----------------- 主要处理回调 -----------------
|
| 236 |
def process_image_and_generate_outputs(
|
| 237 |
img, g_th, c_th, s_scores,
|
| 238 |
+
access_pwd, user_tencent_id, user_tencent_key, user_baidu_json,
|
| 239 |
sum_cats, s_sep, s_zh_in_sum,
|
| 240 |
request: gr.Request
|
| 241 |
):
|
| 242 |
+
if get_token_from_request(request) is None:
|
| 243 |
+
raise gr.Error("错误:您的登录会话已失效,请刷新页面后重试。")
|
| 244 |
if img is None:
|
| 245 |
raise gr.Error("请先上传图片。")
|
| 246 |
if tagger_instance is None:
|
|
|
|
| 248 |
|
| 249 |
yield gr.update(interactive=False, value="🔄 处理中..."), gr.update(visible=True, value="🔄 正在分析..."), *["<p>分析中...</p>"]*3, "分析中...", {}, {}
|
| 250 |
|
| 251 |
+
# 密钥决策逻辑
|
| 252 |
+
use_space_keys = bool(ACCESS_PASSWORD and access_pwd == ACCESS_PASSWORD)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
|
| 254 |
final_tencent_id, final_tencent_key, baidu_json_str = (
|
| 255 |
(os.environ.get("TENCENT_SECRET_ID"), os.environ.get("TENCENT_SECRET_KEY"), os.environ.get("BAIDU_CREDENTIALS_JSON", "[]"))
|
| 256 |
+
if use_space_keys else (user_tencent_id, user_tencent_key, user_baidu_json)
|
| 257 |
)
|
| 258 |
|
| 259 |
final_baidu_creds_list = []
|
|
|
|
| 282 |
outputs_html = {k: format_tags_html(res.get(k, {}), translations.get(k, []), s_scores) for k in ["general", "characters", "ratings"]}
|
| 283 |
summary = generate_summary_text_content(res, translations, sum_cats, s_sep, s_zh_in_sum)
|
| 284 |
|
| 285 |
+
yield gr.update(interactive=True, value="🚀 开始分析"), gr.update(visible=True, value="✅ 分析完成! " + ("(使用空间密钥)" if use_space_keys else "(使用自定义密钥)")), outputs_html["general"], outputs_html["characters"], outputs_html["ratings"], summary, res, translations
|
| 286 |
|
| 287 |
except Exception as e:
|
| 288 |
import traceback
|
|
|
|
| 290 |
raise gr.Error(f"处理时发生错误: {e}")
|
| 291 |
|
| 292 |
# ----------------- 绑定事件 -----------------
|
| 293 |
+
demo.load(fn=check_user_status, inputs=None, outputs=[user_status_md, main_interface], queue=False)
|
| 294 |
|
| 295 |
btn.click(
|
| 296 |
process_image_and_generate_outputs,
|
| 297 |
inputs=[
|
| 298 |
img_in, gen_slider, char_slider, show_tag_scores,
|
| 299 |
+
access_password_in, tencent_id_in, tencent_key_in, baidu_json_in,
|
| 300 |
sum_cats, sum_sep, sum_show_zh
|
| 301 |
],
|
| 302 |
outputs=[
|
|
|
|
| 318 |
if __name__ == "__main__":
|
| 319 |
if tagger_instance is None:
|
| 320 |
print("CRITICAL: Tagger 未能初始化,应用功能将受限。")
|
| 321 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|