Spaces:
Runtime error
Runtime error
Update image_embedder.py
Browse files- image_embedder.py +51 -21
image_embedder.py
CHANGED
|
@@ -21,13 +21,17 @@ from __future__ import annotations
|
|
| 21 |
import os
|
| 22 |
import sys
|
| 23 |
from typing import Optional
|
| 24 |
-
|
| 25 |
import numpy as np
|
| 26 |
import torch
|
| 27 |
import torch.nn.functional as F
|
| 28 |
from PIL import Image
|
| 29 |
from huggingface_hub import hf_hub_download
|
| 30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
# ---------------------------------------------------------------------------
|
| 32 |
# Make the local 'detree' package importable
|
| 33 |
# ---------------------------------------------------------------------------
|
|
@@ -37,20 +41,29 @@ if _current_dir not in sys.path:
|
|
| 37 |
|
| 38 |
try:
|
| 39 |
import clip as _clip_lib
|
|
|
|
| 40 |
except ImportError:
|
| 41 |
-
|
| 42 |
_clip_lib = None
|
| 43 |
|
|
|
|
| 44 |
try:
|
| 45 |
from detree.model.clip_projector import CLIPProjector
|
|
|
|
| 46 |
except ImportError as _e:
|
| 47 |
-
|
| 48 |
CLIPProjector = None
|
| 49 |
|
| 50 |
# Hugging face
|
| 51 |
_BASE_DIR = "MAS-AI-0000/Authentica"
|
| 52 |
_PROJECTOR_DIR = os.path.join(_BASE_DIR, "Lib/Models/Image")
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
# ---------------------------------------------------------------------------
|
| 55 |
# Configuration
|
| 56 |
# ---------------------------------------------------------------------------
|
|
@@ -63,6 +76,8 @@ CLIP_PROJECTOR_FILENAME = "Lib/Models/Image/clip_projector.pt"
|
|
| 63 |
# ==== Load assets ====
|
| 64 |
clip_projector_path = hf_hub_download(repo_id=REPO_ID, filename=CLIP_PROJECTOR_FILENAME)
|
| 65 |
|
|
|
|
|
|
|
| 66 |
# ---------------------------------------------------------------------------
|
| 67 |
# Module-level initialisation
|
| 68 |
# ---------------------------------------------------------------------------
|
|
@@ -75,35 +90,39 @@ _projector: Optional[object] = None
|
|
| 75 |
def _init() -> None:
|
| 76 |
global _clip_model, _clip_prep, _projector
|
| 77 |
|
|
|
|
|
|
|
| 78 |
if _clip_lib is None or CLIPProjector is None:
|
| 79 |
-
|
| 80 |
return
|
| 81 |
|
| 82 |
# Load CLIP
|
|
|
|
| 83 |
try:
|
| 84 |
_clip_model, _clip_prep = _clip_lib.load(CLIP_MODEL, jit=False, device=DEVICE)
|
| 85 |
_clip_model.eval()
|
| 86 |
for param in _clip_model.parameters():
|
| 87 |
param.requires_grad = False
|
| 88 |
-
|
| 89 |
except Exception as exc:
|
| 90 |
-
|
| 91 |
return
|
| 92 |
|
| 93 |
# Load CLIPProjector
|
| 94 |
if not os.path.exists(_PROJECTOR_DIR):
|
| 95 |
-
|
| 96 |
return
|
| 97 |
|
|
|
|
| 98 |
try:
|
| 99 |
_projector = CLIPProjector.from_pretrained(
|
| 100 |
-
|
| 101 |
-
clip_projector_path, device=DEVICE
|
| 102 |
).to(DEVICE)
|
| 103 |
_projector.eval()
|
| 104 |
-
|
|
|
|
| 105 |
except Exception as exc:
|
| 106 |
-
|
| 107 |
|
| 108 |
|
| 109 |
_init()
|
|
@@ -128,18 +147,29 @@ def get_image_embedding(image: Image.Image) -> np.ndarray:
|
|
| 128 |
``np.ndarray`` of shape ``(1, embedding_dim)`` and dtype float32.
|
| 129 |
"""
|
| 130 |
if _clip_model is None or _projector is None:
|
|
|
|
| 131 |
return np.zeros((1, 1), dtype=np.float32)
|
| 132 |
|
| 133 |
-
image =
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
|
| 144 |
return projected.cpu().numpy().astype(np.float32)
|
| 145 |
|
|
|
|
| 21 |
import os
|
| 22 |
import sys
|
| 23 |
from typing import Optional
|
| 24 |
+
import logging
|
| 25 |
import numpy as np
|
| 26 |
import torch
|
| 27 |
import torch.nn.functional as F
|
| 28 |
from PIL import Image
|
| 29 |
from huggingface_hub import hf_hub_download
|
| 30 |
|
| 31 |
+
|
| 32 |
+
log = logging.getLogger("image_embedder")
|
| 33 |
+
logging.basicConfig(level=logging.INFO, format="%(levelname)s [%(name)s] %(message)s")
|
| 34 |
+
|
| 35 |
# ---------------------------------------------------------------------------
|
| 36 |
# Make the local 'detree' package importable
|
| 37 |
# ---------------------------------------------------------------------------
|
|
|
|
| 41 |
|
| 42 |
try:
|
| 43 |
import clip as _clip_lib
|
| 44 |
+
log.info("clip package imported successfully.")
|
| 45 |
except ImportError:
|
| 46 |
+
log.error("'clip' package not found β image embedding will return zeros.")
|
| 47 |
_clip_lib = None
|
| 48 |
|
| 49 |
+
|
| 50 |
try:
|
| 51 |
from detree.model.clip_projector import CLIPProjector
|
| 52 |
+
log.info("CLIPProjector imported successfully.")
|
| 53 |
except ImportError as _e:
|
| 54 |
+
log.error(f"Could not import CLIPProjector: {_e} β image embedding will return zeros.")
|
| 55 |
CLIPProjector = None
|
| 56 |
|
| 57 |
# Hugging face
|
| 58 |
_BASE_DIR = "MAS-AI-0000/Authentica"
|
| 59 |
_PROJECTOR_DIR = os.path.join(_BASE_DIR, "Lib/Models/Image")
|
| 60 |
|
| 61 |
+
log.info(f"[paths] _BASE_DIR = {_BASE_DIR!r}")
|
| 62 |
+
log.info(f"[paths] _PROJECTOR_DIR = {_PROJECTOR_DIR!r} exists={os.path.exists(_PROJECTOR_DIR)}")
|
| 63 |
+
if os.path.exists(_PROJECTOR_DIR):
|
| 64 |
+
log.info(f"[paths] _PROJECTOR_DIR contents: {os.listdir(_PROJECTOR_DIR)}")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
# ---------------------------------------------------------------------------
|
| 68 |
# Configuration
|
| 69 |
# ---------------------------------------------------------------------------
|
|
|
|
| 76 |
# ==== Load assets ====
|
| 77 |
clip_projector_path = hf_hub_download(repo_id=REPO_ID, filename=CLIP_PROJECTOR_FILENAME)
|
| 78 |
|
| 79 |
+
log.info(f"[config] device={DEVICE!r} clip_model={CLIP_MODEL!r}")
|
| 80 |
+
|
| 81 |
# ---------------------------------------------------------------------------
|
| 82 |
# Module-level initialisation
|
| 83 |
# ---------------------------------------------------------------------------
|
|
|
|
| 90 |
def _init() -> None:
|
| 91 |
global _clip_model, _clip_prep, _projector
|
| 92 |
|
| 93 |
+
log.info("_init: starting ImageEmbedder initialisation.")
|
| 94 |
+
|
| 95 |
if _clip_lib is None or CLIPProjector is None:
|
| 96 |
+
log.error("_init: required packages unavailable β embedding disabled.")
|
| 97 |
return
|
| 98 |
|
| 99 |
# Load CLIP
|
| 100 |
+
log.info(f"_init: loading CLIP model {CLIP_MODEL!r} on device={DEVICE!r} ...")
|
| 101 |
try:
|
| 102 |
_clip_model, _clip_prep = _clip_lib.load(CLIP_MODEL, jit=False, device=DEVICE)
|
| 103 |
_clip_model.eval()
|
| 104 |
for param in _clip_model.parameters():
|
| 105 |
param.requires_grad = False
|
| 106 |
+
log.info(f"_init: CLIP ({CLIP_MODEL}) loaded OK on {DEVICE!r}")
|
| 107 |
except Exception as exc:
|
| 108 |
+
log.exception(f"_init: error loading CLIP: {exc}")
|
| 109 |
return
|
| 110 |
|
| 111 |
# Load CLIPProjector
|
| 112 |
if not os.path.exists(_PROJECTOR_DIR):
|
| 113 |
+
log.error(f"_init: projector directory not found at {_PROJECTOR_DIR!r} β embedding disabled.")
|
| 114 |
return
|
| 115 |
|
| 116 |
+
log.info(f"_init: loading CLIPProjector from {_PROJECTOR_DIR!r} ...")
|
| 117 |
try:
|
| 118 |
_projector = CLIPProjector.from_pretrained(
|
| 119 |
+
_PROJECTOR_DIR, device=DEVICE
|
|
|
|
| 120 |
).to(DEVICE)
|
| 121 |
_projector.eval()
|
| 122 |
+
log.info(f"_init: CLIPProjector loaded OK. "
|
| 123 |
+
f"clip_dim={_projector.clip_dim} target_dim={_projector.target_dim}")
|
| 124 |
except Exception as exc:
|
| 125 |
+
log.exception(f"_init: error loading CLIPProjector: {exc}")
|
| 126 |
|
| 127 |
|
| 128 |
_init()
|
|
|
|
| 147 |
``np.ndarray`` of shape ``(1, embedding_dim)`` and dtype float32.
|
| 148 |
"""
|
| 149 |
if _clip_model is None or _projector is None:
|
| 150 |
+
log.error("get_image_embedding: clip_model or projector is None β returning zeros. Check _init logs.")
|
| 151 |
return np.zeros((1, 1), dtype=np.float32)
|
| 152 |
|
| 153 |
+
log.info(f"get_image_embedding: input image size={image.size} mode={image.mode!r}")
|
| 154 |
+
try:
|
| 155 |
+
image = image.convert("RGB")
|
| 156 |
+
image_tensor = _clip_prep(image).unsqueeze(0).to(DEVICE)
|
| 157 |
+
log.info(f"get_image_embedding: preprocessed tensor shape={tuple(image_tensor.shape)}")
|
| 158 |
+
|
| 159 |
+
# CLIP encode β L2-normalise
|
| 160 |
+
clip_emb = _clip_model.encode_image(image_tensor).float()
|
| 161 |
+
log.info(f"get_image_embedding: raw CLIP embedding shape={tuple(clip_emb.shape)} "
|
| 162 |
+
f"norm={clip_emb.norm(dim=-1).item():.4f}")
|
| 163 |
+
clip_emb = F.normalize(clip_emb, dim=-1)
|
| 164 |
+
clip_emb = clip_emb.float()
|
| 165 |
+
|
| 166 |
+
# Project into the DETree embedding space (projector normalises output)
|
| 167 |
+
projected = _projector(clip_emb, normalize=True)
|
| 168 |
+
log.info(f"get_image_embedding: projected shape={tuple(projected.shape)} "
|
| 169 |
+
f"norm={projected.norm(dim=-1).item():.4f}")
|
| 170 |
+
except Exception as exc:
|
| 171 |
+
log.exception(f"get_image_embedding: failed during inference: {exc}")
|
| 172 |
+
return np.zeros((1, 1), dtype=np.float32)
|
| 173 |
|
| 174 |
return projected.cpu().numpy().astype(np.float32)
|
| 175 |
|