1import warnings, torch
2from huggingface_hub import hf_hub_download
3from transformers import AutoImageProcessor, ViTConfig, ViTForImageClassification
4from transformers.utils import logging as hf_logging
5from PIL import Image
6from IPython.display import display, Markdown
7
8warnings.filterwarnings("ignore")
9hf_logging.set_verbosity_error()
10
11REPO_ID = "jihedjabnoun/faceemo-set"
12
13MODEL_TYPE = "combined" # "faceemo" or "combined"
14
15FILES = {
16 "faceemo": ("FaceEmo-Set_ViT_model_weights.pth", "FaceEmo-Set_ViT_model"),
17 "combined": ("comb_data_ViT_model_weights.pth", "Combined_ViT_model")
18}
19
20MODEL_FILE, MODEL_NAME = FILES[MODEL_TYPE]
21
22EMOTIONS = ["anger","disgust","fear","happiness","neutral","sadness","surprise"]
23IMAGE_PATH = "9.png"
24
25device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
26
27processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k", use_fast=True)
28
29config = ViTConfig.from_pretrained("google/vit-base-patch16-224-in21k", num_labels=len(EMOTIONS))
30model = ViTForImageClassification(config)
31
32weights_path = hf_hub_download(repo_id=REPO_ID, filename=MODEL_FILE)
33
34state = torch.load(weights_path, map_location="cpu")
35if any(k.startswith("module.") for k in state):
36 state = {k.replace("module.", "", 1): v for k, v in state.items()}
37
38model.load_state_dict(state, strict=True)
39model.to(device).eval()
40
41print(f"✅ {MODEL_NAME} loaded successfully")
42
43image = Image.open(IMAGE_PATH).convert("RGB")
44display(image)
45
46inputs = processor(images=image, return_tensors="pt").to(device)
47
48with torch.no_grad():
49 probs = torch.softmax(model(**inputs).logits, dim=1)[0]
50
51top = torch.topk(probs, 3)
52
53lines = []
54for i, (idx, p) in enumerate(zip(top.indices.tolist(), top.values.tolist()), 1):
55 lines.append(f"{i}. **{EMOTIONS[idx]}** — `{p:.2%}`")
56
57display(Markdown("### Prediction (Top-3)\n" + "\n".join(lines)))
1import warnings, torch
2from huggingface_hub import hf_hub_download
3from transformers import AutoImageProcessor, ViTConfig, ViTForImageClassification
4from transformers.utils import logging as hf_logging
5from PIL import Image
6from torch.utils.data import Dataset, DataLoader
7import pandas as pd
8
9warnings.filterwarnings("ignore")
10hf_logging.set_verbosity_error()
11
12REPO_ID = "jihedjabnoun/faceemo-set"
13
14MODEL_TYPE = "faceemo" # "faceemo" or "combined"
15
16FILES = {
17 "faceemo": ("FaceEmo-Set_ViT_model_weights.pth", "FaceEmo-Set_ViT_model"),
18 "combined": ("comb_data_ViT_model_weights.pth", "Combined_ViT_model")
19}
20
21MODEL_FILE, MODEL_NAME = FILES[MODEL_TYPE]
22
23EMOTIONS = ["anger","disgust","fear","happiness","neutral","sadness","surprise"]
24image_paths = ["9.png", "C.png"]
25
26device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
27
28processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k", use_fast=True)
29
30config = ViTConfig.from_pretrained("google/vit-base-patch16-224-in21k", num_labels=len(EMOTIONS))
31model = ViTForImageClassification(config)
32
33weights_path = hf_hub_download(repo_id=REPO_ID, filename=MODEL_FILE)
34
35state = torch.load(weights_path, map_location="cpu")
36if any(k.startswith("module.") for k in state):
37 state = {k.replace("module.", "", 1): v for k, v in state.items()}
38
39model.load_state_dict(state, strict=True)
40model.to(device).eval()
41
42print(f"✅ {MODEL_NAME} loaded successfully")
43
44class ImgListDataset(Dataset):
45 def __init__(self, paths):
46 self.paths = paths
47
48 def __len__(self):
49 return len(self.paths)
50
51 def __getitem__(self, idx):
52 image = Image.open(self.paths[idx]).convert("RGB").resize((224, 224))
53 pixel = processor(images=image, return_tensors="pt")["pixel_values"].squeeze(0)
54 return pixel, self.paths[idx]
55
56loader = DataLoader(ImgListDataset(image_paths), batch_size=32, shuffle=False)
57
58rows = []
59with torch.no_grad():
60 for pixels, paths in loader:
61 pixels = pixels.to(device)
62 probs = torch.softmax(model(pixels).logits, dim=1)
63 top = torch.topk(probs, 3, dim=1)
64
65 for path, idxs, vals in zip(paths, top.indices.cpu().tolist(), top.values.cpu().tolist()):
66 rows.append({
67 "image": path,
68 "top1": f"{EMOTIONS[idxs[0]]} ({vals[0]:.2%})",
69 "top2": f"{EMOTIONS[idxs[1]]} ({vals[1]:.2%})",
70 "top3": f"{EMOTIONS[idxs[2]]} ({vals[2]:.2%})",
71 })
72
73display(pd.DataFrame(rows))
1@inproceedings{jabnoun2026improving,
2 title={Improving Cross-Dataset Generalization in Facial Emotion Recognition Through FaceEmo-Set: A Balanced and Diverse Dataset},
3 author={Jabnoun, Jihed and Maraoui, Mohsen and Zrigui, Mounir},
4 booktitle={Asian Conference on Intelligent Information and Database Systems},
5 pages={355--369},
6 year={2026},
7 organization={Springer}
8}
This work was conducted at the Research Laboratory in Algebra, Numbers Theory and Intelligent Systems, University of Monastir, Tunisia.