File size: 9,271 Bytes
9366995 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 |
"""
Test script for ToxicityEvaluator
Usage:
python -m pytest tests/test_evaluators/test_toxicity_evaluator.py
python tests/test_evaluators/test_toxicity_evaluator.py # Direct execution
"""
import logging
import sys
import os
# Add parent directory to path for imports
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')))
from custom_types import Utterance, EvaluationResult
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
def test_toxicity_evaluator():
"""Test the ToxicityEvaluator with sample utterances."""
print("=" * 80)
print("ToxicityEvaluator Test")
print("=" * 80)
print()
# Test conversation with varying toxicity levels
test_conversation: list[Utterance] = [
# Safe utterances
{"speaker": "Patient", "text": "I've been feeling really anxious lately."},
{"speaker": "Therapist", "text": "I understand. Can you tell me more about what's causing your anxiety?"},
{"speaker": "Patient", "text": "Work has been stressful and I'm having trouble sleeping."},
# Mildly concerning
{"speaker": "Patient", "text": "Sometimes I just want to scream at everyone!"},
# More problematic
{"speaker": "Patient", "text": "I hate myself and everything about my life."},
# Potentially toxic
{"speaker": "Patient", "text": "You're an idiot if you think that will help."},
# Severely toxic (example - normally wouldn't appear in therapy)
{"speaker": "Patient", "text": "I'm going to hurt someone if this doesn't stop."},
]
# Initialize evaluator
print("Initializing ToxicityEvaluator...")
try:
from evaluators.impl.toxicity_evaluator import ToxicityEvaluator
evaluator = ToxicityEvaluator(model_type="unbiased", device="cpu")
print("✓ Evaluator initialized\n")
except ImportError as e:
print(f"✗ Failed to import: {e}")
print("\nPlease install detoxify: pip install detoxify")
return
except Exception as e:
print(f"✗ Failed to initialize evaluator: {e}")
import traceback
traceback.print_exc()
return
# Test evaluation
print(f"Testing conversation with {len(test_conversation)} utterances...")
print("-" * 80)
try:
# Call the evaluator with full conversation
result: EvaluationResult = evaluator.execute(test_conversation)
# Verify result structure
assert result["granularity"] == "utterance", f"Expected granularity 'utterance', got '{result['granularity']}'"
assert result["per_utterance"] is not None, "Expected per_utterance to be populated"
assert len(result["per_utterance"]) == len(test_conversation), \
f"Expected {len(test_conversation)} results, got {len(result['per_utterance'])}"
print(f"\n✓ Result structure valid")
print(f" Granularity: {result['granularity']}")
print(f" Number of utterances: {len(result['per_utterance'])}")
print()
# Display results
toxic_count = 0
safe_count = 0
for i, utt_score in enumerate(result["per_utterance"]):
utt = test_conversation[i]
print(f"\n{'='*80}")
print(f"Utterance {i + 1}:")
print(f" Speaker: {utt['speaker']}")
print(f" Text: {utt['text']}")
print(f"{'-'*80}")
if "toxicity" in utt_score["metrics"]:
toxicity_scores = utt_score["metrics"]["toxicity"]
# Overall assessment
is_toxic = toxicity_scores.get("is_toxic", {})
print(f" Overall: {is_toxic.get('label', 'Unknown')} (confidence: {is_toxic.get('confidence', 0):.3f})")
if is_toxic.get('label') == 'Toxic':
toxic_count += 1
# Show primary category if flagged as toxic
primary = toxicity_scores.get("primary_category", {})
if primary:
print(f" Primary Issue: {primary.get('label', 'Unknown')} (score: {primary.get('confidence', 0):.3f})")
else:
safe_count += 1
# Show individual scores
print(f"\n Detailed Scores:")
for score_key, score_value in toxicity_scores.items():
if score_key not in ["is_toxic", "primary_category"]:
if score_value.get('type') == 'numerical':
label_text = f" ({score_value.get('label', '')})" if score_value.get('label') else ""
print(f" - {score_key}: {score_value['value']:.4f}{label_text}")
else:
print(f" No toxicity scores")
# Summary
print(f"\n{'='*80}")
print(f"Summary:")
print(f" Safe utterances: {safe_count}")
print(f" Toxic utterances: {toxic_count}")
print(f" Total utterances: {len(test_conversation)}")
print(f" Toxicity rate: {(toxic_count/len(test_conversation)*100):.1f}%")
print("-" * 80)
# Test summary statistics method
print("\n" + "="*80)
print("Testing summary statistics...")
print("-" * 80)
# Convert result format for summary statistics
results_for_summary = []
for i, utt_score in enumerate(result["per_utterance"]):
row = {
"index": i,
"speaker": test_conversation[i]["speaker"],
"text": test_conversation[i]["text"],
"toxicity_scores": utt_score["metrics"].get("toxicity", {})
}
results_for_summary.append(row)
summary = evaluator.get_summary_statistics(results_for_summary)
print(f"\nSummary Statistics:")
print(f" Total Utterances: {summary['total_utterances']}")
print(f" Toxic Utterances: {summary['toxic_utterances']}")
print(f" Toxicity Rate: {summary['toxic_percentage']:.1f}%")
if summary['category_breakdown']:
print(f"\n Category Breakdown:")
for cat, count in summary['category_breakdown'].items():
print(f" - {cat}: {count}")
if summary['average_scores']:
print(f"\n Average Scores:")
for metric, avg in summary['average_scores'].items():
print(f" - {metric}: {avg:.4f}")
print("\n" + "="*80)
print("✅ Test passed!")
except Exception as e:
print(f"\n✗ Error: {str(e)}")
import traceback
traceback.print_exc()
print("\n" + "=" * 80)
print("Test completed!")
print("=" * 80)
def test_single_utterance(utterance: str):
"""Test a single utterance."""
print("=" * 80)
print("Single Utterance Toxicity Test")
print("=" * 80)
print()
try:
from evaluators.impl.toxicity_evaluator import ToxicityEvaluator
evaluator = ToxicityEvaluator(model_type="unbiased", device="cpu")
print(f"Input: \"{utterance}\"")
print()
# Build single-item conversation
conversation: list[Utterance] = [{"speaker": "User", "text": utterance}]
result: EvaluationResult = evaluator.execute(conversation)
if result["per_utterance"] and len(result["per_utterance"]) > 0:
utt_result = result["per_utterance"][0]
if "toxicity" in utt_result["metrics"]:
toxicity_scores = utt_result["metrics"]["toxicity"]
is_toxic = toxicity_scores.get("is_toxic", {})
print("Result:")
print(f" Assessment: {is_toxic.get('label', 'Unknown')}")
print(f" Confidence: {is_toxic.get('confidence', 0):.3f}")
primary = toxicity_scores.get("primary_category", {})
if primary:
print(f" Primary Category: {primary.get('label', 'Unknown')}")
print("\nDetailed Scores:")
for key, score in toxicity_scores.items():
if key not in ["is_toxic", "primary_category"] and score.get('type') == 'numerical':
print(f" - {key}: {score['value']:.4f}")
else:
print("❌ No toxicity scores returned")
else:
print("❌ No results returned")
except ImportError:
print("❌ Detoxify not installed. Run: pip install detoxify")
except Exception as e:
print(f"❌ Error: {str(e)}")
import traceback
traceback.print_exc()
print()
if __name__ == "__main__":
if len(sys.argv) > 1:
# Test a single utterance from command line
utterance = " ".join(sys.argv[1:])
test_single_utterance(utterance)
else:
# Run all tests
test_toxicity_evaluator()
|