Spaces:
Sleeping
Sleeping
Update classifier.py
Browse files- classifier.py +63 -92
classifier.py
CHANGED
@@ -1,98 +1,69 @@
|
|
1 |
-
#
|
2 |
-
import
|
3 |
-
import
|
4 |
-
from
|
5 |
-
from
|
6 |
-
from metrics import compute_semantic_similarity, compute_empathy_score, compute_bleu_score, compute_rouge_score
|
7 |
|
8 |
-
|
|
|
|
|
|
|
9 |
"""
|
10 |
-
|
11 |
-
|
12 |
-
Returns the prediction label, confidence, color, toxicity score, bias score, paraphrased comment (if applicable), and its metrics.
|
13 |
"""
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
return
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
tokenizer = classifier_model.tokenizer
|
23 |
-
|
24 |
-
# Tokenize the input comment
|
25 |
-
start_classification = time.time()
|
26 |
-
inputs = tokenizer(comment, return_tensors="pt", truncation=True, padding=True, max_length=512)
|
27 |
-
|
28 |
-
# Run inference
|
29 |
-
with torch.no_grad():
|
30 |
-
outputs = model(**inputs)
|
31 |
-
logits = outputs.logits
|
32 |
-
|
33 |
-
# Get the predicted class (0 = non-toxic, 1 = toxic)
|
34 |
-
predicted_class = torch.argmax(logits, dim=1).item()
|
35 |
-
label = "Toxic" if predicted_class == 1 else "Non-Toxic"
|
36 |
-
confidence = torch.softmax(logits, dim=1)[0][predicted_class].item()
|
37 |
-
label_color = "red" if label == "Toxic" else "green"
|
38 |
-
|
39 |
-
# Compute Toxicity Score (approximated as the probability of the toxic class)
|
40 |
-
toxicity_score = torch.softmax(logits, dim=1)[0][1].item()
|
41 |
-
toxicity_score = round(toxicity_score, 2)
|
42 |
-
|
43 |
-
# Simulate Bias Score (placeholder)
|
44 |
-
bias_score = 0.01 if label == "Non-Toxic" else 0.15
|
45 |
-
bias_score = round(bias_score, 2)
|
46 |
-
print(f"Classification took {time.time() - start_classification:.2f} seconds")
|
47 |
-
|
48 |
-
# If the comment is toxic, paraphrase it and compute essential metrics
|
49 |
-
paraphrased_comment = None
|
50 |
-
paraphrased_prediction = None
|
51 |
-
paraphrased_confidence = None
|
52 |
-
paraphrased_color = None
|
53 |
-
paraphrased_toxicity_score = None
|
54 |
-
paraphrased_bias_score = None
|
55 |
-
semantic_similarity = None
|
56 |
-
empathy_score = None
|
57 |
-
bleu_score = None
|
58 |
-
rouge_scores = None
|
59 |
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
#
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
paraphrased_confidence = torch.softmax(paraphrased_logits, dim=1)[0][paraphrased_predicted_class].item()
|
76 |
-
paraphrased_color = "red" if paraphrased_label == "Toxic" else "green"
|
77 |
-
paraphrased_toxicity_score = torch.softmax(paraphrased_logits, dim=1)[0][1].item()
|
78 |
-
paraphrased_toxicity_score = round(paraphrased_toxicity_score, 2)
|
79 |
-
paraphrased_bias_score = 0.01 if paraphrased_label == "Non-Toxic" else 0.15 # Placeholder
|
80 |
-
paraphrased_bias_score = round(paraphrased_bias_score, 2)
|
81 |
-
print(f"Reclassification of paraphrased comment took {time.time() - start_reclassification:.2f} seconds")
|
82 |
-
|
83 |
-
# Compute essential metrics
|
84 |
-
start_metrics = time.time()
|
85 |
-
semantic_similarity = compute_semantic_similarity(comment, paraphrased_comment)
|
86 |
-
empathy_score = compute_empathy_score(paraphrased_comment)
|
87 |
-
bleu_score = compute_bleu_score(comment, paraphrased_comment)
|
88 |
-
rouge_scores = compute_rouge_score(comment, paraphrased_comment)
|
89 |
-
print(f"Metrics computation took {time.time() - start_metrics:.2f} seconds")
|
90 |
|
91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
92 |
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# metrics.py
|
2 |
+
import nltk
|
3 |
+
from nltk.translate.bleu_score import sentence_bleu
|
4 |
+
from rouge_score import rouge_scorer
|
5 |
+
from model_loader import metrics_models
|
|
|
6 |
|
7 |
+
# Download required NLTK data
|
8 |
+
nltk.download('punkt')
|
9 |
+
|
10 |
+
def compute_semantic_similarity(original, paraphrased):
|
11 |
"""
|
12 |
+
Compute semantic similarity between the original and paraphrased comment using Sentence-BERT.
|
13 |
+
Returns a similarity score between 0 and 1.
|
|
|
14 |
"""
|
15 |
+
try:
|
16 |
+
sentence_bert = metrics_models.load_sentence_bert()
|
17 |
+
embeddings = sentence_bert.encode([original, paraphrased])
|
18 |
+
similarity = float(embeddings[0] @ embeddings[1].T)
|
19 |
+
return round(similarity, 2)
|
20 |
+
except Exception as e:
|
21 |
+
print(f"Error computing semantic similarity: {str(e)}")
|
22 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
|
24 |
+
def compute_empathy_score(paraphrased):
|
25 |
+
"""
|
26 |
+
Compute an empathy score for the paraphrased comment (placeholder).
|
27 |
+
Returns a score between 0 and 1.
|
28 |
+
"""
|
29 |
+
try:
|
30 |
+
# Placeholder: Compute empathy based on word presence (e.g., "sorry", "understand")
|
31 |
+
empathy_words = ["sorry", "understand", "care", "help", "support"]
|
32 |
+
words = paraphrased.lower().split()
|
33 |
+
empathy_count = sum(1 for word in words if word in empathy_words)
|
34 |
+
score = empathy_count / len(words) if words else 0
|
35 |
+
return round(score, 2)
|
36 |
+
except Exception as e:
|
37 |
+
print(f"Error computing empathy score: {str(e)}")
|
38 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
|
40 |
+
def compute_bleu_score(original, paraphrased):
|
41 |
+
"""
|
42 |
+
Compute the BLEU score between the original and paraphrased comment.
|
43 |
+
Returns a score between 0 and 1.
|
44 |
+
"""
|
45 |
+
try:
|
46 |
+
reference = [nltk.word_tokenize(original.lower())]
|
47 |
+
candidate = nltk.word_tokenize(paraphrased.lower())
|
48 |
+
score = sentence_bleu(reference, candidate, weights=(0.25, 0.25, 0.25, 0.25))
|
49 |
+
return round(score, 2)
|
50 |
+
except Exception as e:
|
51 |
+
print(f"Error computing BLEU score: {str(e)}")
|
52 |
+
return None
|
53 |
|
54 |
+
def compute_rouge_score(original, paraphrased):
|
55 |
+
"""
|
56 |
+
Compute ROUGE scores (ROUGE-1, ROUGE-2, ROUGE-L) between the original and paraphrased comment.
|
57 |
+
Returns a dictionary with ROUGE scores.
|
58 |
+
"""
|
59 |
+
try:
|
60 |
+
scorer = rouge_scorer.RougeScorer(['rouge1', 'rouge2', 'rougeL'], use_stemmer=True)
|
61 |
+
scores = scorer.score(original, paraphrased)
|
62 |
+
return {
|
63 |
+
'rouge1': round(scores['rouge1'].fmeasure, 2),
|
64 |
+
'rouge2': round(scores['rouge2'].fmeasure, 2),
|
65 |
+
'rougeL': round(scores['rougeL'].fmeasure, 2)
|
66 |
+
}
|
67 |
+
except Exception as e:
|
68 |
+
print(f"Error computing ROUGE scores: {str(e)}")
|
69 |
+
return None
|