Views
No views yet
maf_model_full.pth - Complete model state dict (includes all weights)clip_config.pth - CLIP model configuration (required for loading)model_config.pth - Model hyperparameters (required for initialization)model_architecture.py - Model architecture code with lexicon supportREADME.md - This documentation filepip install torch torchvision transformers open_clip_torch pillow huggingface_hub1from huggingface_hub import hf_hub_download
2import torch
3import open_clip
4from transformers import AutoTokenizer
5import importlib.util
6
7# Setup device
8device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
9
10# ===== STEP 1: Download all required files =====
11repo_id = "lucius-40/bengali-political-maf-v8"
12
13clip_config_path = hf_hub_download(repo_id=repo_id, filename="clip_config.pth")
14model_config_path = hf_hub_download(repo_id=repo_id, filename="model_config.pth")
15model_weights_path = hf_hub_download(repo_id=repo_id, filename="maf_model_full.pth")
16arch_path = hf_hub_download(repo_id=repo_id, filename="model_architecture.py")
17
18# ===== STEP 2: Load configurations =====
19clip_config = torch.load(clip_config_path, map_location=device)
20model_config = torch.load(model_config_path, map_location=device)
21
22print(f"Loading CLIP: {clip_config['model_name']} ({clip_config['pretrained']})")
23
24# ===== STEP 3: Initialize CLIP visual encoder =====
25clip_model, _, preprocess = open_clip.create_model_and_transforms(
26 clip_config['model_name'], # 'ViT-B-16'
27 pretrained=clip_config['pretrained'], # 'laion2b_s34b_b88k'
28 device=device
29)
30
31# Extract visual encoder only
32clip_visual = clip_model.visual.float().to(device)
33
34# ===== STEP 4: Load model architecture =====
35spec = importlib.util.spec_from_file_location("model_architecture", arch_path)
36model_arch = importlib.util.module_from_spec(spec)
37spec.loader.exec_module(model_arch)
38MAF = model_arch.MAF
39
40# ===== STEP 5: Initialize MAF model =====
41model = MAF(
42 clip_model=clip_visual,
43 num_classes=model_config['num_classes'],
44 num_heads=model_config['num_heads'],
45 use_lexicon_boost=model_config['use_lexicon_boost']
46)
47
48# ===== STEP 6: Load fine-tuned weights =====
49model.load_state_dict(torch.load(model_weights_path, map_location=device))
50model = model.to(device)
51model.eval()
52
53print("✓ Model loaded successfully with fine-tuned CLIP and XLM-RoBERTa weights!")
54
55# ===== STEP 7: Prepare tokenizer =====
56tokenizer = AutoTokenizer.from_pretrained(model_config['xlm_model_name'])1from PIL import Image
2from torchvision import transforms
3
4# Define image preprocessing (IMPORTANT: Must match training)
5transform = transforms.Compose([
6 transforms.Resize((224, 224)),
7 transforms.ToTensor(),
8 transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
9])
10
11# Load and preprocess image
12image_path = "path/to/your/meme.jpg"
13image = Image.open(image_path).convert('RGB')
14image_tensor = transform(image).unsqueeze(0).to(device)
15
16# Prepare text (OCR text from the meme)
17text = "আপনার বাংলা টেক্সট এখানে" # Your Bengali text here
18
19# Tokenize text
20encoded = tokenizer(
21 text,
22 max_length=model_config['max_length'],
23 padding='max_length',
24 truncation=True,
25 return_tensors='pt'
26)
27input_ids = encoded['input_ids'].to(device)
28attention_mask = encoded['attention_mask'].to(device)
29
30# Calculate lexicon matches (for boosting)
31from model_architecture import contains_political_keywords
32lexicon_matches = contains_political_keywords(text)
33lexicon_tensor = torch.tensor([lexicon_matches]).to(device)
34
35# Run inference
36with torch.no_grad():
37 outputs = model(image_tensor, input_ids, attention_mask, lexicon_tensor)
38 probs = torch.softmax(outputs, dim=1)
39 pred_class = torch.argmax(probs, dim=1).item()
40 confidence = probs[0][pred_class].item()
41
42# Print results
43class_names = ['NonPolitical', 'Political']
44print(f"Prediction: {class_names[pred_class]}")
45print(f"Confidence: {confidence:.4f}")
46print(f"Probabilities: NonPolitical={probs[0][0]:.4f}, Political={probs[0][1]:.4f}")torch>=1.9.0
torchvision>=0.10.0
transformers>=4.41.2
open_clip_torch>=2.0.0
pillow>=9.5.0
huggingface_hub>=0.16.01@inproceedings{ahsan2024multimodal,
2 title={A Multimodal Framework to Detect Target Aware Aggression in Memes},
3 author={Ahsan, Shawly and Hossain, Eftekhar and Sharif, Omar and Das, Avishek and Hoque, Mohammed Moshiul and Dewan, M},
4 booktitle={Proceedings of the 18th Conference of the European Chapter of the Association for Computational Linguistics (Volume 1: Long Papers)},
5 pages={2487--2500},
6 year={2024}
7}contains_political_keywords function is included in model_architecture.py and should be used during inference for optimal performance.