Spaces:
Sleeping
Sleeping
Upload ear/semantic.py with huggingface_hub
Browse files- ear/semantic.py +18 -2
ear/semantic.py
CHANGED
|
@@ -71,6 +71,21 @@ BANK: dict[str, list[str]] = {
|
|
| 71 |
_FLAT: list[tuple[str, str]] = [(g, t) for g, items in BANK.items() for t in items]
|
| 72 |
|
| 73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
class _Semantic:
|
| 75 |
def __init__(self) -> None:
|
| 76 |
self.ready = False
|
|
@@ -96,7 +111,7 @@ class _Semantic:
|
|
| 96 |
texts = [t for _, t in _FLAT]
|
| 97 |
with torch.no_grad():
|
| 98 |
inputs = processor(text=texts, return_tensors="pt", padding=True)
|
| 99 |
-
emb = model.get_text_features(**inputs)
|
| 100 |
emb = emb / emb.norm(dim=-1, keepdim=True)
|
| 101 |
|
| 102 |
self._model, self._processor, self._text_emb = model, processor, emb
|
|
@@ -138,7 +153,8 @@ class _Semantic:
|
|
| 138 |
except TypeError:
|
| 139 |
inputs = self._processor(audios=clip, sampling_rate=CLAP_SR,
|
| 140 |
return_tensors="pt")
|
| 141 |
-
audio_emb = self._model.get_audio_features(**inputs)
|
|
|
|
| 142 |
audio_emb = audio_emb / audio_emb.norm(dim=-1, keepdim=True)
|
| 143 |
sims = (audio_emb @ self._text_emb.T).squeeze(0).cpu().numpy()
|
| 144 |
|
|
|
|
| 71 |
_FLAT: list[tuple[str, str]] = [(g, t) for g, items in BANK.items() for t in items]
|
| 72 |
|
| 73 |
|
| 74 |
+
def _features(raw, projection):
|
| 75 |
+
"""Normalise CLAP's feature output across transformers versions.
|
| 76 |
+
|
| 77 |
+
4.x returns the projected tensor directly. 5.x returns a
|
| 78 |
+
BaseModelOutputWithPooling, so the projection has to be applied here —
|
| 79 |
+
which is exactly what 4.x did internally.
|
| 80 |
+
"""
|
| 81 |
+
if hasattr(raw, "shape"):
|
| 82 |
+
return raw
|
| 83 |
+
pooled = getattr(raw, "pooler_output", None)
|
| 84 |
+
if pooled is None:
|
| 85 |
+
pooled = raw.last_hidden_state[:, 0]
|
| 86 |
+
return projection(pooled)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
class _Semantic:
|
| 90 |
def __init__(self) -> None:
|
| 91 |
self.ready = False
|
|
|
|
| 111 |
texts = [t for _, t in _FLAT]
|
| 112 |
with torch.no_grad():
|
| 113 |
inputs = processor(text=texts, return_tensors="pt", padding=True)
|
| 114 |
+
emb = _features(model.get_text_features(**inputs), model.text_projection)
|
| 115 |
emb = emb / emb.norm(dim=-1, keepdim=True)
|
| 116 |
|
| 117 |
self._model, self._processor, self._text_emb = model, processor, emb
|
|
|
|
| 153 |
except TypeError:
|
| 154 |
inputs = self._processor(audios=clip, sampling_rate=CLAP_SR,
|
| 155 |
return_tensors="pt")
|
| 156 |
+
audio_emb = _features(self._model.get_audio_features(**inputs),
|
| 157 |
+
self._model.audio_projection)
|
| 158 |
audio_emb = audio_emb / audio_emb.norm(dim=-1, keepdim=True)
|
| 159 |
sims = (audio_emb @ self._text_emb.T).squeeze(0).cpu().numpy()
|
| 160 |
|