|
import gradio as gr |
|
import onnxruntime as ort |
|
import numpy as np |
|
from PIL import Image |
|
import json |
|
from huggingface_hub import hf_hub_download |
|
|
|
|
|
MODEL_REPO = "AngelBottomless/camie-tagger-onnxruntime" |
|
MODEL_FILE = "camie_tagger_initial.onnx" |
|
META_FILE = "metadata.json" |
|
model_path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE, cache_dir=".") |
|
meta_path = hf_hub_download(repo_id=MODEL_REPO, filename=META_FILE, cache_dir=".") |
|
session = ort.InferenceSession(model_path, providers=["CPUExecutionProvider"]) |
|
metadata = json.load(open(meta_path, "r", encoding="utf-8")) |
|
|
|
def preprocess_image(pil_image: Image.Image) -> np.ndarray: |
|
img = pil_image.convert("RGB").resize((512, 512)) |
|
arr = np.array(img).astype(np.float32) / 255.0 |
|
arr = np.transpose(arr, (2, 0, 1)) |
|
arr = np.expand_dims(arr, 0) |
|
return arr |
|
|
|
|
|
def tag_image(pil_image: Image.Image, output_format: str) -> str: |
|
|
|
input_tensor = preprocess_image(pil_image) |
|
input_name = session.get_inputs()[0].name |
|
initial_logits, refined_logits = session.run(None, {input_name: input_tensor}) |
|
probs = 1 / (1 + np.exp(-refined_logits)) |
|
probs = probs[0] |
|
idx_to_tag = metadata["idx_to_tag"] |
|
tag_to_category = metadata.get("tag_to_category", {}) |
|
category_thresholds = metadata.get("category_thresholds", {}) |
|
default_threshold = 0.325 |
|
results_by_cat = {} |
|
prompt_tags = [] |
|
|
|
for idx, prob in enumerate(probs): |
|
tag = idx_to_tag[str(idx)] |
|
cat = tag_to_category.get(tag, "unknown") |
|
thresh = category_thresholds.get(cat, default_threshold) |
|
if float(prob) >= thresh: |
|
|
|
results_by_cat.setdefault(cat, []).append((tag, float(prob))) |
|
|
|
prompt_tags.append(tag.replace("_", " ")) |
|
if output_format == "Prompt-style Tags": |
|
if not prompt_tags: |
|
return "No tags predicted." |
|
|
|
|
|
prompt_tags.sort(key=lambda t: max([p for (tg, p) in results_by_cat[tag_to_category.get(t.replace(' ', '_'), 'unknown')] if tg == t.replace(' ', '_')]), reverse=True) |
|
return ", ".join(prompt_tags) |
|
else: |
|
if not results_by_cat: |
|
return "No tags predicted for this image." |
|
lines = [] |
|
lines.append("**Predicted Tags by Category:** \n") |
|
for cat, tag_list in results_by_cat.items(): |
|
|
|
tag_list.sort(key=lambda x: x[1], reverse=True) |
|
lines.append(f"**Category: {cat}** β {len(tag_list)} tags") |
|
for tag, prob in tag_list: |
|
tag_pretty = tag.replace("_", " ") |
|
lines.append(f"- {tag_pretty} (Prob: {prob:.3f})") |
|
lines.append("") |
|
return "\n".join(lines) |
|
|
|
|
|
demo = gr.Blocks(theme=gr.themes.Soft()) |
|
|
|
with demo: |
|
|
|
gr.Markdown("# π·οΈ Camie Tagger β Anime Image Tagging\nThis demo uses an ONNX model of Camie Tagger to label anime illustrations with tags. Upload an image and click **Tag Image** to see predictions.") |
|
gr.Markdown("*(Note: The model will predict a large number of tags across categories like character, general, artist, etc. You can choose a concise prompt-style output or a detailed category-wise breakdown.)*") |
|
|
|
with gr.Row(): |
|
|
|
with gr.Column(): |
|
image_in = gr.Image(type="pil", label="Input Image") |
|
format_choice = gr.Radio(choices=["Prompt-style Tags", "Detailed Output"], value="Prompt-style Tags", label="Output Format") |
|
tag_button = gr.Button("π Tag Image") |
|
|
|
with gr.Column(): |
|
output_box = gr.Markdown("") |
|
|
|
gr.Examples( |
|
examples=[["example1.jpg"], ["example2.png"]], |
|
inputs=image_in, |
|
outputs=output_box, |
|
fn=tag_image, |
|
cache_examples=True |
|
) |
|
|
|
tag_button.click(fn=tag_image, inputs=[image_in, format_choice], outputs=output_box) |
|
|
|
gr.Markdown("----\n**Model:** [Camie Tagger ONNX](https://huggingface.co/AngelBottomless/camie-tagger-onnxruntime) β’ **Base Model:** Camais03/camie-tagger (61% F1 on 70k tags) β’ **ONNX Runtime:** for efficient CPU inference​:contentReference[oaicite:6]{index=6} β’ *Demo built with Gradio Blocks.*") |
|
|
|
|
|
demo.launch() |
|
|