Spaces:
Running on Zero
Running on Zero
Commit Β·
cdff22b
1
Parent(s): ff3cad5
fixed lookup file for tag-category
Browse files- app.py +89 -188
- requirements.txt +0 -2
- tag_category.json +0 -0
app.py
CHANGED
|
@@ -12,10 +12,8 @@ from __future__ import annotations
|
|
| 12 |
|
| 13 |
import json
|
| 14 |
import os
|
| 15 |
-
import sqlite3
|
| 16 |
import sys
|
| 17 |
import tempfile
|
| 18 |
-
import threading
|
| 19 |
import time
|
| 20 |
from pathlib import Path
|
| 21 |
|
|
@@ -39,6 +37,7 @@ def _import_hf_hub():
|
|
| 39 |
|
| 40 |
HF_REPO = "realphongha/danbooru-tag-query"
|
| 41 |
MODELS_DIR = "models"
|
|
|
|
| 42 |
|
| 43 |
IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)
|
| 44 |
IMAGENET_STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)
|
|
@@ -54,73 +53,51 @@ CATEGORY_MAP = {
|
|
| 54 |
DEFAULT_TOP_K = None
|
| 55 |
DEFAULT_MIN_SCORE = 0.2
|
| 56 |
|
| 57 |
-
# ββ
|
| 58 |
|
| 59 |
-
|
|
|
|
| 60 |
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
-
|
| 79 |
-
with self._lock:
|
| 80 |
-
cur = self._conn.execute(
|
| 81 |
-
"SELECT category, wiki_body FROM tag_cache WHERE name = ?", (name,)
|
| 82 |
-
)
|
| 83 |
-
return cur.fetchone()
|
| 84 |
-
|
| 85 |
-
def set(self, name: str, category: int | None, wiki_body: str | None):
|
| 86 |
-
with self._lock:
|
| 87 |
-
self._conn.execute(
|
| 88 |
-
"""INSERT OR REPLACE INTO tag_cache (name, category, wiki_body, fetched_at)
|
| 89 |
-
VALUES (?, ?, ?, ?)""",
|
| 90 |
-
(name, category, wiki_body, time.time()),
|
| 91 |
-
)
|
| 92 |
-
self._conn.commit()
|
| 93 |
-
|
| 94 |
-
def get_many(self, names: list[str]) -> dict[str, tuple[int | None, str | None]]:
|
| 95 |
-
if not names:
|
| 96 |
-
return {}
|
| 97 |
-
with self._lock:
|
| 98 |
-
placeholders = ",".join("?" for _ in names)
|
| 99 |
-
cur = self._conn.execute(
|
| 100 |
-
f"SELECT name, category, wiki_body FROM tag_cache "
|
| 101 |
-
f"WHERE name IN ({placeholders})", names,
|
| 102 |
-
)
|
| 103 |
-
return {row[0]: (row[1], row[2]) for row in cur}
|
| 104 |
-
|
| 105 |
-
def bulk_set(self, items: list[tuple[str, int | None, str | None]]):
|
| 106 |
-
with self._lock:
|
| 107 |
-
now = time.time()
|
| 108 |
-
self._conn.executemany(
|
| 109 |
-
"""INSERT OR REPLACE INTO tag_cache (name, category, wiki_body, fetched_at)
|
| 110 |
-
VALUES (?, ?, ?, ?)""",
|
| 111 |
-
[(name, cat, body, now) for name, cat, body in items],
|
| 112 |
-
)
|
| 113 |
-
self._conn.commit()
|
| 114 |
|
| 115 |
-
def clear(self):
|
| 116 |
-
with self._lock:
|
| 117 |
-
self._conn.execute("DELETE FROM tag_cache")
|
| 118 |
-
self._conn.commit()
|
| 119 |
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
return cur.fetchone()[0]
|
| 124 |
|
| 125 |
|
| 126 |
# ββ image preprocessing ββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
@@ -144,12 +121,6 @@ def preprocess(image: Image.Image, image_size: int = 448) -> np.ndarray:
|
|
| 144 |
|
| 145 |
# ββ sidecar loading ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 146 |
|
| 147 |
-
def _sidecar_path(checkpoint: Path, suffix: str) -> Path:
|
| 148 |
-
if checkpoint.suffix == ".onnx":
|
| 149 |
-
return checkpoint.with_name(checkpoint.stem + suffix)
|
| 150 |
-
return checkpoint / suffix.lstrip(".")
|
| 151 |
-
|
| 152 |
-
|
| 153 |
def load_tag_to_id(checkpoint: str | Path) -> dict[str, int]:
|
| 154 |
ckpt = Path(checkpoint)
|
| 155 |
path = _sidecar_path(ckpt, ".tag_to_id.json")
|
|
@@ -170,6 +141,12 @@ def load_config(checkpoint: str | Path) -> dict:
|
|
| 170 |
return json.loads(path.read_text())
|
| 171 |
|
| 172 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
# ββ Predictor (ONNX) ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 174 |
|
| 175 |
class Predictor:
|
|
@@ -180,6 +157,7 @@ class Predictor:
|
|
| 180 |
self.tag_to_id = load_tag_to_id(self.checkpoint)
|
| 181 |
cfg = load_config(self.checkpoint)
|
| 182 |
self.image_size = cfg.get("image_size", 448)
|
|
|
|
| 183 |
|
| 184 |
providers = [
|
| 185 |
("CUDAExecutionProvider", {}),
|
|
@@ -203,6 +181,9 @@ class Predictor:
|
|
| 203 |
def num_classes(self) -> int:
|
| 204 |
return len(self.tag_to_id)
|
| 205 |
|
|
|
|
|
|
|
|
|
|
| 206 |
|
| 207 |
# ββ model discovery & loading (HF hub) βββββββββββββββββββββββββββββββββββββ
|
| 208 |
|
|
@@ -223,100 +204,24 @@ def discover_model_variants() -> list[str]:
|
|
| 223 |
return []
|
| 224 |
|
| 225 |
|
| 226 |
-
def
|
| 227 |
-
onnx_path = f"{MODELS_DIR}/{variant}/model.onnx"
|
| 228 |
-
hf = _import_hf_hub()
|
| 229 |
-
return hf.hf_hub_download(
|
| 230 |
-
repo_id=HF_REPO,
|
| 231 |
-
filename=onnx_path,
|
| 232 |
-
repo_type="model",
|
| 233 |
-
)
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
def resolve_sidecar_paths(variant: str) -> tuple[str, str]:
|
| 237 |
hf = _import_hf_hub()
|
| 238 |
-
|
| 239 |
-
repo_id=HF_REPO,
|
| 240 |
-
filename=f"{MODELS_DIR}/{variant}/config.json",
|
| 241 |
-
repo_type="model",
|
| 242 |
-
)
|
| 243 |
-
tagmap_path = hf.hf_hub_download(
|
| 244 |
repo_id=HF_REPO,
|
| 245 |
-
filename=f"{MODELS_DIR}/{variant}/
|
| 246 |
repo_type="model",
|
| 247 |
)
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
#
|
| 258 |
-
|
| 259 |
-
_CACHE = TagCache()
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
def prebuild_cache(tag_to_id: dict[str, int]):
|
| 263 |
-
"""Pre-populate tag cache from HF dataset.
|
| 264 |
-
|
| 265 |
-
Every tag gets a category (defaults to 0 = general).
|
| 266 |
-
No lazy API calls needed.
|
| 267 |
-
"""
|
| 268 |
-
try:
|
| 269 |
-
from datasets import load_dataset
|
| 270 |
-
except ImportError:
|
| 271 |
-
return 0, 0
|
| 272 |
-
|
| 273 |
-
tags = sorted(tag_to_id.keys(), key=lambda t: tag_to_id[t])
|
| 274 |
-
|
| 275 |
-
try:
|
| 276 |
-
ds = load_dataset("qdlabs/danbooru-tags", split="train")
|
| 277 |
-
cat_map = {row["name"]: row["category"] for row in ds}
|
| 278 |
-
except Exception:
|
| 279 |
-
return 0, 0
|
| 280 |
-
|
| 281 |
-
found = sum(1 for t in tags if t in cat_map)
|
| 282 |
-
todo = []
|
| 283 |
-
already = 0
|
| 284 |
-
for tag in tags:
|
| 285 |
-
cached = _CACHE.get(tag)
|
| 286 |
-
if cached is not None and cached[0] is not None:
|
| 287 |
-
already += 1
|
| 288 |
-
continue
|
| 289 |
-
cat = cat_map.get(tag, 0) # 0 = general for unknown
|
| 290 |
-
existing_wiki = cached[1] if cached else None
|
| 291 |
-
todo.append((tag, cat, existing_wiki))
|
| 292 |
-
|
| 293 |
-
if todo:
|
| 294 |
-
_CACHE.bulk_set(todo)
|
| 295 |
-
|
| 296 |
-
return already + len(todo), found
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
def enrich_tags(tags_scores: list[tuple[str, float]]) -> dict[str, dict]:
|
| 300 |
-
"""Attach category info to each tag. No API calls."""
|
| 301 |
-
tags = [t for t, _ in tags_scores]
|
| 302 |
-
cached_map = _CACHE.get_many(tags)
|
| 303 |
-
result: dict[str, dict] = {}
|
| 304 |
-
for tag, score in tags_scores:
|
| 305 |
-
cached = cached_map.get(tag)
|
| 306 |
-
if cached is not None:
|
| 307 |
-
cat_id, _ = cached
|
| 308 |
-
else:
|
| 309 |
-
cat_id = None
|
| 310 |
-
result[tag] = {
|
| 311 |
-
"score": score,
|
| 312 |
-
"category": cat_id,
|
| 313 |
-
"category_name": CATEGORY_MAP.get(cat_id, "general"),
|
| 314 |
-
}
|
| 315 |
-
return result
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
def format_tag(tag: str, use_underscore: bool) -> str:
|
| 319 |
-
return tag if use_underscore else tag.replace("_", " ")
|
| 320 |
|
| 321 |
|
| 322 |
# ββ Gradio UI ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
@@ -343,7 +248,6 @@ def build_app(predict_fn, model_choices: list[str]) -> gr.Blocks:
|
|
| 343 |
gr.Markdown("# π·οΈ DanbooruTagQuery")
|
| 344 |
|
| 345 |
with gr.Row():
|
| 346 |
-
# ββ left: image + model ββ
|
| 347 |
with gr.Column(scale=1):
|
| 348 |
image_input = gr.Image(
|
| 349 |
label="Image",
|
|
@@ -368,7 +272,6 @@ def build_app(predict_fn, model_choices: list[str]) -> gr.Blocks:
|
|
| 368 |
)
|
| 369 |
model_status = gr.Markdown("Ready")
|
| 370 |
|
| 371 |
-
# ββ right: params + categories ββ
|
| 372 |
with gr.Column(scale=1):
|
| 373 |
top_k = gr.Number(
|
| 374 |
label="Top-K", value=DEFAULT_TOP_K, minimum=0, step=1
|
|
@@ -392,7 +295,6 @@ def build_app(predict_fn, model_choices: list[str]) -> gr.Blocks:
|
|
| 392 |
value=["general"],
|
| 393 |
)
|
| 394 |
|
| 395 |
-
# ββ outputs ββ
|
| 396 |
with gr.Tabs():
|
| 397 |
with gr.TabItem("π Tag list"):
|
| 398 |
tag_table = gr.HTML(label="Tags")
|
|
@@ -401,12 +303,9 @@ def build_app(predict_fn, model_choices: list[str]) -> gr.Blocks:
|
|
| 401 |
tag_string = gr.Textbox(label="Tags", lines=6, elem_id="csv-text")
|
| 402 |
copy_btn = gr.Button("π", elem_id="copy-csv-btn")
|
| 403 |
|
| 404 |
-
# ββ status row ββ
|
| 405 |
with gr.Row():
|
| 406 |
status = gr.Markdown("Ready. Load an image and click **Analyze**.")
|
| 407 |
-
clear_cache_btn = gr.Button("π§Ή Clear cache", size="sm", elem_id="clear-cache-btn")
|
| 408 |
|
| 409 |
-
# ββ tag score query ββ
|
| 410 |
gr.Markdown("### π Tag score query")
|
| 411 |
with gr.Row():
|
| 412 |
tag_query = gr.Textbox(
|
|
@@ -458,7 +357,7 @@ def build_app(predict_fn, model_choices: list[str]) -> gr.Blocks:
|
|
| 458 |
f"<td>{link}</td>"
|
| 459 |
f"<td>{display}</td>"
|
| 460 |
f"<td style='text-align:right'>{score:.4f}</td>"
|
| 461 |
-
f"<td><code>{m['category_name']
|
| 462 |
f"</tr>"
|
| 463 |
)
|
| 464 |
table = (
|
|
@@ -503,7 +402,9 @@ def build_app(predict_fn, model_choices: list[str]) -> gr.Blocks:
|
|
| 503 |
t0 = time.time()
|
| 504 |
all_logits = fn(pil)
|
| 505 |
state["all_logits"] = all_logits
|
| 506 |
-
state["tag_metadata"] = enrich_tags(
|
|
|
|
|
|
|
| 507 |
|
| 508 |
table, csv = refresh_results(
|
| 509 |
top_k.value, min_score.value,
|
|
@@ -512,8 +413,7 @@ def build_app(predict_fn, model_choices: list[str]) -> gr.Blocks:
|
|
| 512 |
)
|
| 513 |
elapsed = time.time() - t0
|
| 514 |
n = len(state["tag_metadata"])
|
| 515 |
-
|
| 516 |
-
return table, csv, f"β
{n} tags Β· {cached} cached Β· {elapsed:.2f}s"
|
| 517 |
|
| 518 |
analyze_btn.click(
|
| 519 |
fn=on_analyze,
|
|
@@ -540,12 +440,6 @@ def build_app(predict_fn, model_choices: list[str]) -> gr.Blocks:
|
|
| 540 |
status, tag_query, tag_query_output],
|
| 541 |
)
|
| 542 |
|
| 543 |
-
def on_clear_cache():
|
| 544 |
-
_CACHE.clear()
|
| 545 |
-
return "π§Ή Cache cleared (0 entries)"
|
| 546 |
-
|
| 547 |
-
clear_cache_btn.click(fn=on_clear_cache, inputs=[], outputs=[status])
|
| 548 |
-
|
| 549 |
for widget in [top_k, min_score, sort_by, use_underscore, categories]:
|
| 550 |
widget.change(
|
| 551 |
fn=refresh_results,
|
|
@@ -566,7 +460,7 @@ def build_app(predict_fn, model_choices: list[str]) -> gr.Blocks:
|
|
| 566 |
return "<i>No matching tags.</i>"
|
| 567 |
rows = "".join(
|
| 568 |
f"<tr><td>{t}</td><td>{s:.4f}</td>"
|
| 569 |
-
f"<td><code>{meta[t]['category_name']
|
| 570 |
for t, s in matches
|
| 571 |
)
|
| 572 |
return (f"<table style='width:100%'>"
|
|
@@ -609,7 +503,6 @@ def build_app(predict_fn, model_choices: list[str]) -> gr.Blocks:
|
|
| 609 |
state["predict_fn"] = new_predict_fn
|
| 610 |
state["all_logits"] = None
|
| 611 |
state["tag_metadata"] = None
|
| 612 |
-
_try_prebuild(predictor)
|
| 613 |
return f"β
Switched to {variant} ({predictor.num_classes} tags)"
|
| 614 |
except Exception as exc:
|
| 615 |
return f"β Failed to load model: {exc}"
|
|
@@ -623,16 +516,27 @@ def build_app(predict_fn, model_choices: list[str]) -> gr.Blocks:
|
|
| 623 |
return app
|
| 624 |
|
| 625 |
|
| 626 |
-
# ββ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 627 |
|
| 628 |
-
def _try_prebuild(predictor: Predictor):
|
| 629 |
-
try:
|
| 630 |
-
total, found = prebuild_cache(predictor.tag_to_id)
|
| 631 |
-
if total:
|
| 632 |
-
print(f"Cache prebuilt: {total} tags ({found} with category from HF dataset)")
|
| 633 |
-
except Exception as exc:
|
| 634 |
-
print(f"Cache prebuild skipped: {exc}")
|
| 635 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 636 |
|
| 637 |
def main():
|
| 638 |
model_arg = sys.argv[1] if len(sys.argv) > 1 else None
|
|
@@ -647,7 +551,6 @@ def main():
|
|
| 647 |
sys.exit(1)
|
| 648 |
print(f"Loading local model: {onnx}")
|
| 649 |
predictor = Predictor(onnx)
|
| 650 |
-
_try_prebuild(predictor)
|
| 651 |
|
| 652 |
def _predict(image: Image.Image) -> list[tuple[str, float]]:
|
| 653 |
tensor = preprocess(image, predictor.image_size)
|
|
@@ -669,7 +572,6 @@ def main():
|
|
| 669 |
onnx = onnx_files[0]
|
| 670 |
print(f"Loading local model from MODEL_DIR: {onnx}")
|
| 671 |
predictor = Predictor(onnx)
|
| 672 |
-
_try_prebuild(predictor)
|
| 673 |
|
| 674 |
def _predict(image: Image.Image) -> list[tuple[str, float]]:
|
| 675 |
tensor = preprocess(image, predictor.image_size)
|
|
@@ -691,7 +593,6 @@ def main():
|
|
| 691 |
try:
|
| 692 |
onnx_path = download_model_variant(default)
|
| 693 |
predictor = Predictor(onnx_path)
|
| 694 |
-
_try_prebuild(predictor)
|
| 695 |
|
| 696 |
def _predict(image: Image.Image) -> list[tuple[str, float]]:
|
| 697 |
tensor = preprocess(image, predictor.image_size)
|
|
|
|
| 12 |
|
| 13 |
import json
|
| 14 |
import os
|
|
|
|
| 15 |
import sys
|
| 16 |
import tempfile
|
|
|
|
| 17 |
import time
|
| 18 |
from pathlib import Path
|
| 19 |
|
|
|
|
| 37 |
|
| 38 |
HF_REPO = "realphongha/danbooru-tag-query"
|
| 39 |
MODELS_DIR = "models"
|
| 40 |
+
CATEGORY_JSON = "tag_category.json"
|
| 41 |
|
| 42 |
IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)
|
| 43 |
IMAGENET_STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)
|
|
|
|
| 53 |
DEFAULT_TOP_K = None
|
| 54 |
DEFAULT_MIN_SCORE = 0.2
|
| 55 |
|
| 56 |
+
# ββ category lookup βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 57 |
|
| 58 |
+
def load_category_map(checkpoint: str | Path) -> dict[str, int]:
|
| 59 |
+
"""Load tagβcategory map. Tries HF hub download, then sidecar file.
|
| 60 |
|
| 61 |
+
Returns {tag: category_id} β all tags default to 0 (general).
|
| 62 |
+
"""
|
| 63 |
+
ckpt = Path(checkpoint)
|
| 64 |
|
| 65 |
+
# 1) sidecar: model.onnx β tag_category.json beside it
|
| 66 |
+
if ckpt.suffix == ".onnx":
|
| 67 |
+
sidecar = ckpt.with_name(CATEGORY_JSON)
|
| 68 |
+
if sidecar.exists():
|
| 69 |
+
return json.loads(sidecar.read_text())
|
| 70 |
+
|
| 71 |
+
# 2) parent dir: dir/model.onnx β dir/tag_category.json
|
| 72 |
+
parent_sidecar = ckpt.parent / CATEGORY_JSON
|
| 73 |
+
if parent_sidecar.exists():
|
| 74 |
+
return json.loads(parent_sidecar.read_text())
|
| 75 |
+
|
| 76 |
+
# 3) HF hub: download alongside model variant
|
| 77 |
+
if ckpt.suffix == ".onnx":
|
| 78 |
+
# try to infer variant from path
|
| 79 |
+
parts = ckpt.parts
|
| 80 |
+
for i, p in enumerate(parts):
|
| 81 |
+
if p == MODELS_DIR and i + 2 < len(parts):
|
| 82 |
+
variant = parts[i + 1]
|
| 83 |
+
try:
|
| 84 |
+
hf = _import_hf_hub()
|
| 85 |
+
path = hf.hf_hub_download(
|
| 86 |
+
repo_id=HF_REPO,
|
| 87 |
+
filename=f"{MODELS_DIR}/{variant}/{CATEGORY_JSON}",
|
| 88 |
+
repo_type="model",
|
| 89 |
+
)
|
| 90 |
+
return json.loads(Path(path).read_text())
|
| 91 |
+
except Exception:
|
| 92 |
+
pass
|
| 93 |
+
break
|
| 94 |
|
| 95 |
+
return {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
+
def get_category_name(cat_map: dict[str, int], tag: str) -> str:
|
| 99 |
+
cat_id = cat_map.get(tag, 0)
|
| 100 |
+
return CATEGORY_MAP.get(cat_id, "general")
|
|
|
|
| 101 |
|
| 102 |
|
| 103 |
# ββ image preprocessing ββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 121 |
|
| 122 |
# ββ sidecar loading ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 123 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
def load_tag_to_id(checkpoint: str | Path) -> dict[str, int]:
|
| 125 |
ckpt = Path(checkpoint)
|
| 126 |
path = _sidecar_path(ckpt, ".tag_to_id.json")
|
|
|
|
| 141 |
return json.loads(path.read_text())
|
| 142 |
|
| 143 |
|
| 144 |
+
def _sidecar_path(checkpoint: Path, suffix: str) -> Path:
|
| 145 |
+
if checkpoint.suffix == ".onnx":
|
| 146 |
+
return checkpoint.with_name(checkpoint.stem + suffix)
|
| 147 |
+
return checkpoint / suffix.lstrip(".")
|
| 148 |
+
|
| 149 |
+
|
| 150 |
# ββ Predictor (ONNX) ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 151 |
|
| 152 |
class Predictor:
|
|
|
|
| 157 |
self.tag_to_id = load_tag_to_id(self.checkpoint)
|
| 158 |
cfg = load_config(self.checkpoint)
|
| 159 |
self.image_size = cfg.get("image_size", 448)
|
| 160 |
+
self.cat_map = load_category_map(self.checkpoint)
|
| 161 |
|
| 162 |
providers = [
|
| 163 |
("CUDAExecutionProvider", {}),
|
|
|
|
| 181 |
def num_classes(self) -> int:
|
| 182 |
return len(self.tag_to_id)
|
| 183 |
|
| 184 |
+
def category_name(self, tag: str) -> str:
|
| 185 |
+
return get_category_name(self.cat_map, tag)
|
| 186 |
+
|
| 187 |
|
| 188 |
# ββ model discovery & loading (HF hub) βββββββββββββββββββββββββββββββββββββ
|
| 189 |
|
|
|
|
| 204 |
return []
|
| 205 |
|
| 206 |
|
| 207 |
+
def download_model_variant(variant: str) -> Path:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
hf = _import_hf_hub()
|
| 209 |
+
onnx_path = hf.hf_hub_download(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
repo_id=HF_REPO,
|
| 211 |
+
filename=f"{MODELS_DIR}/{variant}/model.onnx",
|
| 212 |
repo_type="model",
|
| 213 |
)
|
| 214 |
+
# download sidecars (config, tag_to_id, tag_category) if they exist
|
| 215 |
+
for sidecar in ["config.json", "tag_to_id.json", CATEGORY_JSON]:
|
| 216 |
+
try:
|
| 217 |
+
hf.hf_hub_download(
|
| 218 |
+
repo_id=HF_REPO,
|
| 219 |
+
filename=f"{MODELS_DIR}/{variant}/{sidecar}",
|
| 220 |
+
repo_type="model",
|
| 221 |
+
)
|
| 222 |
+
except Exception:
|
| 223 |
+
pass # optional β missing is fine
|
| 224 |
+
return Path(onnx_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
|
| 226 |
|
| 227 |
# ββ Gradio UI ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 248 |
gr.Markdown("# π·οΈ DanbooruTagQuery")
|
| 249 |
|
| 250 |
with gr.Row():
|
|
|
|
| 251 |
with gr.Column(scale=1):
|
| 252 |
image_input = gr.Image(
|
| 253 |
label="Image",
|
|
|
|
| 272 |
)
|
| 273 |
model_status = gr.Markdown("Ready")
|
| 274 |
|
|
|
|
| 275 |
with gr.Column(scale=1):
|
| 276 |
top_k = gr.Number(
|
| 277 |
label="Top-K", value=DEFAULT_TOP_K, minimum=0, step=1
|
|
|
|
| 295 |
value=["general"],
|
| 296 |
)
|
| 297 |
|
|
|
|
| 298 |
with gr.Tabs():
|
| 299 |
with gr.TabItem("π Tag list"):
|
| 300 |
tag_table = gr.HTML(label="Tags")
|
|
|
|
| 303 |
tag_string = gr.Textbox(label="Tags", lines=6, elem_id="csv-text")
|
| 304 |
copy_btn = gr.Button("π", elem_id="copy-csv-btn")
|
| 305 |
|
|
|
|
| 306 |
with gr.Row():
|
| 307 |
status = gr.Markdown("Ready. Load an image and click **Analyze**.")
|
|
|
|
| 308 |
|
|
|
|
| 309 |
gr.Markdown("### π Tag score query")
|
| 310 |
with gr.Row():
|
| 311 |
tag_query = gr.Textbox(
|
|
|
|
| 357 |
f"<td>{link}</td>"
|
| 358 |
f"<td>{display}</td>"
|
| 359 |
f"<td style='text-align:right'>{score:.4f}</td>"
|
| 360 |
+
f"<td><code>{m['category_name']}</code></td>"
|
| 361 |
f"</tr>"
|
| 362 |
)
|
| 363 |
table = (
|
|
|
|
| 402 |
t0 = time.time()
|
| 403 |
all_logits = fn(pil)
|
| 404 |
state["all_logits"] = all_logits
|
| 405 |
+
state["tag_metadata"] = enrich_tags(
|
| 406 |
+
all_logits, state["predictor"].cat_map
|
| 407 |
+
)
|
| 408 |
|
| 409 |
table, csv = refresh_results(
|
| 410 |
top_k.value, min_score.value,
|
|
|
|
| 413 |
)
|
| 414 |
elapsed = time.time() - t0
|
| 415 |
n = len(state["tag_metadata"])
|
| 416 |
+
return table, csv, f"β
{n} tags Β· {elapsed:.2f}s"
|
|
|
|
| 417 |
|
| 418 |
analyze_btn.click(
|
| 419 |
fn=on_analyze,
|
|
|
|
| 440 |
status, tag_query, tag_query_output],
|
| 441 |
)
|
| 442 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 443 |
for widget in [top_k, min_score, sort_by, use_underscore, categories]:
|
| 444 |
widget.change(
|
| 445 |
fn=refresh_results,
|
|
|
|
| 460 |
return "<i>No matching tags.</i>"
|
| 461 |
rows = "".join(
|
| 462 |
f"<tr><td>{t}</td><td>{s:.4f}</td>"
|
| 463 |
+
f"<td><code>{meta[t]['category_name']}</code></td></tr>"
|
| 464 |
for t, s in matches
|
| 465 |
)
|
| 466 |
return (f"<table style='width:100%'>"
|
|
|
|
| 503 |
state["predict_fn"] = new_predict_fn
|
| 504 |
state["all_logits"] = None
|
| 505 |
state["tag_metadata"] = None
|
|
|
|
| 506 |
return f"β
Switched to {variant} ({predictor.num_classes} tags)"
|
| 507 |
except Exception as exc:
|
| 508 |
return f"β Failed to load model: {exc}"
|
|
|
|
| 516 |
return app
|
| 517 |
|
| 518 |
|
| 519 |
+
# ββ helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 520 |
+
|
| 521 |
+
def enrich_tags(
|
| 522 |
+
tags_scores: list[tuple[str, float]], cat_map: dict[str, int]
|
| 523 |
+
) -> dict[str, dict]:
|
| 524 |
+
result: dict[str, dict] = {}
|
| 525 |
+
for tag, score in tags_scores:
|
| 526 |
+
cat_id = cat_map.get(tag, 0)
|
| 527 |
+
result[tag] = {
|
| 528 |
+
"score": score,
|
| 529 |
+
"category": cat_id,
|
| 530 |
+
"category_name": CATEGORY_MAP.get(cat_id, "general"),
|
| 531 |
+
}
|
| 532 |
+
return result
|
| 533 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 534 |
|
| 535 |
+
def format_tag(tag: str, use_underscore: bool) -> str:
|
| 536 |
+
return tag if use_underscore else tag.replace("_", " ")
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
# ββ main ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 540 |
|
| 541 |
def main():
|
| 542 |
model_arg = sys.argv[1] if len(sys.argv) > 1 else None
|
|
|
|
| 551 |
sys.exit(1)
|
| 552 |
print(f"Loading local model: {onnx}")
|
| 553 |
predictor = Predictor(onnx)
|
|
|
|
| 554 |
|
| 555 |
def _predict(image: Image.Image) -> list[tuple[str, float]]:
|
| 556 |
tensor = preprocess(image, predictor.image_size)
|
|
|
|
| 572 |
onnx = onnx_files[0]
|
| 573 |
print(f"Loading local model from MODEL_DIR: {onnx}")
|
| 574 |
predictor = Predictor(onnx)
|
|
|
|
| 575 |
|
| 576 |
def _predict(image: Image.Image) -> list[tuple[str, float]]:
|
| 577 |
tensor = preprocess(image, predictor.image_size)
|
|
|
|
| 593 |
try:
|
| 594 |
onnx_path = download_model_variant(default)
|
| 595 |
predictor = Predictor(onnx_path)
|
|
|
|
| 596 |
|
| 597 |
def _predict(image: Image.Image) -> list[tuple[str, float]]:
|
| 598 |
tensor = preprocess(image, predictor.image_size)
|
requirements.txt
CHANGED
|
@@ -3,5 +3,3 @@ gradio==6.20.0
|
|
| 3 |
numpy==1.26.4
|
| 4 |
pillow==12.3.0
|
| 5 |
huggingface-hub==1.24.0
|
| 6 |
-
datasets==5.0.0
|
| 7 |
-
tqdm
|
|
|
|
| 3 |
numpy==1.26.4
|
| 4 |
pillow==12.3.0
|
| 5 |
huggingface-hub==1.24.0
|
|
|
|
|
|
tag_category.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|