Views
No views yet
1from torchvision import transforms
2import torch
3from PIL import Image
4from huggingface_hub import hf_hub_download
5import importlib.util
6
7device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
8
9# Load the model class definition dynamically
10class_path = hf_hub_download(repo_id="PerceptCLIP/PerceptCLIP_Emotions", filename="modeling.py")
11spec = importlib.util.spec_from_file_location("modeling", class_path)
12modeling = importlib.util.module_from_spec(spec)
13spec.loader.exec_module(modeling)
14
15# initialize a model
16ModelClass = modeling.clip_lora_model
17model = ModelClass().to(device)
18
19# Load pretrained model
20model_path = hf_hub_download(repo_id="PerceptCLIP/PerceptCLIP_Emotions", filename="perceptCLIP_Emotions.pth")
21model.load_state_dict(torch.load(model_path, map_location=device))
22model.eval()
23
24# Emotion label mapping
25idx2label = {
26 0: "amusement",
27 1: "awe",
28 2: "contentment",
29 3: "excitement",
30 4: "anger",
31 5: "disgust",
32 6: "fear",
33 7: "sadness"
34}
35
36# Preprocessing function
37def emo_preprocess():
38 transform = transforms.Compose([
39 transforms.Resize(224),
40 transforms.CenterCrop(size=(224, 224)),
41 transforms.ToTensor(),
42 transforms.Normalize(mean=(0.48145466, 0.4578275, 0.40821073), std=(0.26862954, 0.26130258, 0.27577711)),
43 ])
44 return transform
45
46# Load an image
47image = Image.open("image_path.jpg").convert("RGB")
48image = emo_preprocess()(image).unsqueeze(0).to(device)
49
50# Run inference
51with torch.no_grad():
52 outputs = model(image)
53 _, predicted = outputs.max(1)
54
55# Get emotion label
56predicted_emotion = idx2label[predicted.item()]
57print(f"Predicted Emotion: {predicted_emotion}")1@article{zalcher2025don,
2 title={Don't Judge Before You CLIP: A Unified Approach for Perceptual Tasks},
3 author={Zalcher, Amit and Wasserman, Navve and Beliy, Roman and Heinimann, Oliver and Irani, Michal},
4 journal={arXiv preprint arXiv:2503.13260},
5 year={2025}
6}