Spaces:
Running
Running
Upload hf_clap_embedder.py with huggingface_hub
Browse files- hf_clap_embedder.py +34 -0
hf_clap_embedder.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch, librosa, laion_clap, functools, warnings
|
| 2 |
+
from huggingface_hub import hf_hub_download # Added for robust HF downloading
|
| 3 |
+
warnings.filterwarnings('ignore')
|
| 4 |
+
|
| 5 |
+
original_load = torch.load
|
| 6 |
+
torch.load = functools.partial(original_load, weights_only=False)
|
| 7 |
+
original_load_state_dict = torch.nn.Module.load_state_dict
|
| 8 |
+
|
| 9 |
+
def tolerant_load_state_dict(self, state_dict, strict=True, assign=False):
|
| 10 |
+
return original_load_state_dict(self, state_dict, strict=False, assign=assign)
|
| 11 |
+
torch.nn.Module.load_state_dict = tolerant_load_state_dict
|
| 12 |
+
|
| 13 |
+
# Initialize the CLAP module with fusion disabled as requested
|
| 14 |
+
model = laion_clap.CLAP_Module(enable_fusion=False)
|
| 15 |
+
|
| 16 |
+
# Securely download the weights through the official Hugging Face Hub API
|
| 17 |
+
# This bypasses the broken wget/urllib external download logic entirely
|
| 18 |
+
local_checkpoint = hf_hub_download(
|
| 19 |
+
repo_id="lukewys/laion_clap",
|
| 20 |
+
filename="630k-audioset-best.pt"
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
# Load the locally cached file path directly into the model
|
| 24 |
+
model.load_ckpt(local_checkpoint)
|
| 25 |
+
|
| 26 |
+
torch.load = original_load
|
| 27 |
+
torch.nn.Module.load_state_dict = original_load_state_dict
|
| 28 |
+
|
| 29 |
+
def get_clap_embedding(path):
|
| 30 |
+
audio_data, _ = librosa.load(path, sr=48000)
|
| 31 |
+
audio_data = audio_data.reshape(1, -1)
|
| 32 |
+
with torch.no_grad():
|
| 33 |
+
audio_embed = model.get_audio_embedding_from_data(x=audio_data)
|
| 34 |
+
return audio_embed.flatten()
|