Views
No views yet
1from transformers import AutoModelForSequenceClassification, AutoTokenizer
2import torch
3import re
4
5# Load model and tokenizer
6model_name = "kenzykhaled/arabic-answer-scoring"
7tokenizer = AutoTokenizer.from_pretrained(model_name)
8model = AutoModelForSequenceClassification.from_pretrained(model_name)
9
10# Function to preprocess Arabic text
11def preprocess_arabic_text(text):
12 if not isinstance(text, str):
13 return ""
14
15 # Remove diacritics (تشكيل)
16 text = re.sub(r'[ً-ٰٟ]', '', text)
17
18 # Normalize Arabic letters
19 text = re.sub('[إأآا]', 'ا', text) # Normalize Alif forms
20 text = re.sub('ى', 'ي', text) # Normalize Yaa
21 text = re.sub('ة', 'ه', text) # Normalize Taa Marbouta
22
23 # Remove non-Arabic characters except spaces
24 text = re.sub(r'[^-ۿ\s]', '', text)
25
26 # Remove extra spaces
27 text = re.sub(r'\s+', ' ', text).strip()
28
29 return text
30
31# Define prediction function
32def predict_score(text):
33 # Preprocess and tokenize
34 processed_text = preprocess_arabic_text(text)
35 inputs = tokenizer(processed_text, return_tensors="pt", padding=True, truncation=True, max_length=256)
36
37 # Move to appropriate device (GPU if available)
38 device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
39 model.to(device)
40 inputs = {k: v.to(device) for k, v in inputs.items()}
41
42 # Predict
43 model.eval()
44 with torch.no_grad():
45 outputs = model(**inputs)
46 score = outputs.logits.item()
47
48 return score
49
50# Example usage
51sample_text = "هذه إجابة نموذجية باللغة العربية."
52score = predict_score(sample_text)
53print(f"Predicted score: ")@misc{arabic-scoring-model,
author = {Your Name},
title = {Arabic Text Answer Scoring Model},
year = {2025},
publisher = {Hugging Face}
}