Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import onnxruntime as ort
|
| 3 |
+
import numpy as np
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import json
|
| 6 |
+
from huggingface_hub import hf_hub_download
|
| 7 |
+
|
| 8 |
+
# Load the ONNX model and metadata once at startup (optimizes performance)
|
| 9 |
+
MODEL_REPO = "AngelBottomless/camie-tagger-onnxruntime"
|
| 10 |
+
MODEL_FILE = "camie_tagger_initial.onnx" # using the smaller initial model for speed
|
| 11 |
+
META_FILE = "metadata.json"
|
| 12 |
+
|
| 13 |
+
# Download model and metadata from HF Hub (cache_dir="." will cache in the Space)
|
| 14 |
+
model_path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE, cache_dir=".")
|
| 15 |
+
meta_path = hf_hub_download(repo_id=MODEL_REPO, filename=META_FILE, cache_dir=".")
|
| 16 |
+
session = ort.InferenceSession(model_path, providers=["CPUExecutionProvider"])
|
| 17 |
+
metadata = json.load(open(meta_path, "r", encoding="utf-8"))
|
| 18 |
+
|
| 19 |
+
# Preprocessing: resize image to 512x512 and normalize to match training
|
| 20 |
+
def preprocess_image(pil_image: Image.Image) -> np.ndarray:
|
| 21 |
+
img = pil_image.convert("RGB").resize((512, 512))
|
| 22 |
+
arr = np.array(img).astype(np.float32) / 255.0 # scale pixel values to [0,1]
|
| 23 |
+
arr = np.transpose(arr, (2, 0, 1)) # HWC -> CHW
|
| 24 |
+
arr = np.expand_dims(arr, 0) # add batch dimension -> (1,3,512,512)
|
| 25 |
+
return arr
|
| 26 |
+
|
| 27 |
+
# Inference: run the ONNX model and collect tags above threshold
|
| 28 |
+
def predict_tags(pil_image: Image.Image) -> str:
|
| 29 |
+
# 1. Preprocess image to numpy
|
| 30 |
+
input_tensor = preprocess_image(pil_image)
|
| 31 |
+
# 2. Run model (both initial and refined logits are output)
|
| 32 |
+
input_name = session.get_inputs()[0].name
|
| 33 |
+
initial_logits, refined_logits = session.run(None, {input_name: input_tensor})
|
| 34 |
+
# 3. Convert logits to probabilities (using sigmoid since multi-label)
|
| 35 |
+
probs = 1 / (1 + np.exp(-refined_logits)) # shape (1, 70527)
|
| 36 |
+
probs = probs[0] # remove batch dim -> (70527,)
|
| 37 |
+
# 4. Thresholding: get tag names for which probability >= category threshold (or default)
|
| 38 |
+
idx_to_tag = metadata["idx_to_tag"] # map index -> tag string
|
| 39 |
+
tag_to_category = metadata.get("tag_to_category", {}) # map tag -> category
|
| 40 |
+
category_thresholds = metadata.get("category_thresholds", {})# category-specific thresholds
|
| 41 |
+
default_threshold = 0.325
|
| 42 |
+
predicted_tags = []
|
| 43 |
+
for idx, prob in enumerate(probs):
|
| 44 |
+
tag = idx_to_tag[str(idx)]
|
| 45 |
+
cat = tag_to_category.get(tag, "unknown")
|
| 46 |
+
threshold = category_thresholds.get(cat, default_threshold)
|
| 47 |
+
if prob >= threshold:
|
| 48 |
+
# Include this tag; replace underscores with spaces for readability
|
| 49 |
+
predicted_tags.append(tag.replace("_", " "))
|
| 50 |
+
# 5. Return tags as comma-separated string
|
| 51 |
+
if not predicted_tags:
|
| 52 |
+
return "No tags found."
|
| 53 |
+
# Join tags, maybe sorted by name or leave unsorted. Here we sort alphabetically for consistency.
|
| 54 |
+
predicted_tags.sort()
|
| 55 |
+
return ", ".join(predicted_tags)
|
| 56 |
+
|
| 57 |
+
# Create a simple Gradio interface
|
| 58 |
+
demo = gr.Interface(
|
| 59 |
+
fn=predict_tags,
|
| 60 |
+
inputs=gr.Image(type="pil", label="Upload Image"),
|
| 61 |
+
outputs=gr.Textbox(label="Predicted Tags", lines=3),
|
| 62 |
+
title="Camie Tagger (ONNX) – Simple Demo",
|
| 63 |
+
description="Upload an anime/manga illustration to get relevant tags predicted by the Camie Tagger model.",
|
| 64 |
+
# You can optionally add example images if available in the Space directory:
|
| 65 |
+
examples=[["example1.jpg"], ["example2.png"]] # (filenames should exist in the Space)
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
# Launch the app (in HF Spaces, just calling demo.launch() is typically not required; the Space will run app automatically)
|
| 69 |
+
demo.launch()
|