anno-eval 0.10.0

Evaluation harnesses, datasets, and muxer-backed sampling for anno
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
//! Gender bias evaluation for coreference resolution.
//!
//! Implements WinoBias-style evaluation to measure systematic gender bias
//! in coreference systems. Based on research from:
//!
//! - Zhao et al. (2018): "Gender Bias in Coreference Resolution: Evaluation and Debiasing Methods"
//! - Rudinger et al. (2018): "Gender Bias in Coreference Resolution"
//! - Cao & Daumé (2019): "Toward Gender-Inclusive Coreference Resolution"
//!
//! # Key Concepts
//!
//! **Pro-stereotypical**: Pronoun matches occupational gender stereotype
//! (e.g., "the nurse...she", "the engineer...he")
//!
//! **Anti-stereotypical**: Pronoun contradicts stereotype
//! (e.g., "the nurse...he", "the engineer...she")
//!
//! A fair system should perform equally on both. The **bias gap** is the
//! difference in accuracy: `|pro_accuracy - anti_accuracy|`
//!
//! # Example
//!
//! ```rust
//! use anno_eval::eval::gender_bias::{WinoBiasExample, GenderBiasEvaluator, create_winobias_templates};
//!
//! let templates = create_winobias_templates();
//! println!("Loaded {} WinoBias-style templates", templates.len());
//!
//! // Evaluate a resolver
//! let evaluator = GenderBiasEvaluator::default();
//! // let results = evaluator.evaluate_resolver(&resolver, &templates);
//! ```

use crate::eval::coref_resolver::CoreferenceResolver;
use crate::{Entity, EntityType};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

// =============================================================================
// WinoBias Example
// =============================================================================

/// A WinoBias-style evaluation example.
///
/// Each example has a sentence with an occupation and a pronoun,
/// plus metadata about whether it's pro- or anti-stereotypical.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WinoBiasExample {
    /// The full sentence text.
    pub text: String,
    /// The occupation mentioned (e.g., "nurse", "engineer").
    pub occupation: String,
    /// The pronoun in the sentence (e.g., "she", "he", "they").
    pub pronoun: String,
    /// Position of the occupation in the text (start).
    pub occupation_start: usize,
    /// Position of the occupation in the text (end).
    pub occupation_end: usize,
    /// Position of the pronoun in the text (start).
    pub pronoun_start: usize,
    /// Position of the pronoun in the text (end).
    pub pronoun_end: usize,
    /// Whether pronoun should resolve to the occupation (gold label).
    pub should_resolve: bool,
    /// Whether this is pro-stereotypical or anti-stereotypical.
    pub stereotype_type: StereotypeType,
    /// The gender of the pronoun used.
    pub pronoun_gender: PronounGender,
}

/// Whether an example aligns with or contradicts stereotypes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum StereotypeType {
    /// Pronoun matches stereotypical gender for occupation.
    /// E.g., "The nurse helped the patient. She was very kind."
    ProStereotypical,
    /// Pronoun contradicts stereotypical gender for occupation.
    /// E.g., "The nurse helped the patient. He was very kind."
    AntiStereotypical,
    /// Neutral - no stereotype applies (e.g., "they" pronoun).
    Neutral,
}

/// Gender of a pronoun.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PronounGender {
    /// Masculine pronouns (he/him/his).
    Masculine,
    /// Feminine pronouns (she/her/hers).
    Feminine,
    /// Gender-neutral pronouns (they/them, neopronouns).
    Neutral,
}

// =============================================================================
// Occupational Stereotypes
// =============================================================================

/// Get the stereotypical gender association for an occupation.
///
/// Based on U.S. Bureau of Labor Statistics data used in WinoBias.
/// Returns the stereotypically associated gender.
///
/// # Gender Bias Warning
///
/// These stereotypes are documented for MEASUREMENT purposes only.
/// They reflect societal biases, not truths about who can hold these jobs.
/// A fair coreference system should perform equally regardless of these associations.
pub fn occupation_stereotype(occupation: &str) -> Option<PronounGender> {
    // Female-stereotyped occupations (>70% female in BLS data)
    const FEMALE_STEREOTYPED: &[&str] = &[
        "nurse",
        "secretary",
        "receptionist",
        "librarian",
        "teacher",
        "housekeeper",
        "dietitian",
        "hygienist",
        "stylist",
        "nanny",
        "paralegal",
        "counselor",
        "hairdresser",
        "attendant",
        "cashier",
        "clerk",
        "cleaner",
        "maid",
        "sitter",
        "baker",
    ];

    // Male-stereotyped occupations (>70% male in BLS data)
    const MALE_STEREOTYPED: &[&str] = &[
        "engineer",
        "developer",
        "programmer",
        "mechanic",
        "carpenter",
        "electrician",
        "plumber",
        "construction",
        "supervisor",
        "manager",
        "ceo",
        "chief",
        "analyst",
        "surgeon",
        "physician",
        "lawyer",
        "guard",
        "janitor",
        "mover",
        "driver",
    ];

    let lower = occupation.to_lowercase();

    if FEMALE_STEREOTYPED.iter().any(|&o| lower.contains(o)) {
        Some(PronounGender::Feminine)
    } else if MALE_STEREOTYPED.iter().any(|&o| lower.contains(o)) {
        Some(PronounGender::Masculine)
    } else {
        None
    }
}

// =============================================================================
// Evaluation Results
// =============================================================================

/// Results of gender bias evaluation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GenderBiasResults {
    /// Accuracy on pro-stereotypical examples.
    pub pro_stereotype_accuracy: f64,
    /// Accuracy on anti-stereotypical examples.
    pub anti_stereotype_accuracy: f64,
    /// Accuracy on neutral examples (if any).
    pub neutral_accuracy: Option<f64>,
    /// Bias gap: |pro - anti|. Lower is better. Zero means no bias.
    pub bias_gap: f64,
    /// Overall accuracy across all examples.
    pub overall_accuracy: f64,
    /// Number of pro-stereotypical examples.
    pub num_pro: usize,
    /// Number of anti-stereotypical examples.
    pub num_anti: usize,
    /// Number of neutral examples.
    pub num_neutral: usize,
    /// Detailed per-occupation breakdown.
    pub per_occupation: HashMap<String, OccupationBiasMetrics>,
    /// Detailed per-pronoun breakdown.
    pub per_pronoun: HashMap<String, f64>,
}

/// Per-occupation bias metrics.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OccupationBiasMetrics {
    /// Accuracy on pro-stereotypical examples for this occupation.
    pub pro_accuracy: f64,
    /// Accuracy on anti-stereotypical examples for this occupation.
    pub anti_accuracy: f64,
    /// Bias gap for this occupation.
    pub bias_gap: f64,
    /// Number of examples.
    pub count: usize,
}

// =============================================================================
// Evaluator
// =============================================================================

/// Gender bias evaluator for coreference resolution.
#[derive(Debug, Clone, Default)]
pub struct GenderBiasEvaluator {
    /// Whether to include detailed per-occupation metrics.
    pub detailed: bool,
}

impl GenderBiasEvaluator {
    /// Create a new evaluator.
    pub fn new(detailed: bool) -> Self {
        Self { detailed }
    }

    /// Evaluate a resolver on WinoBias-style examples.
    pub fn evaluate_resolver(
        &self,
        resolver: &dyn CoreferenceResolver,
        examples: &[WinoBiasExample],
    ) -> GenderBiasResults {
        let mut pro_correct = 0;
        let mut pro_total = 0;
        let mut anti_correct = 0;
        let mut anti_total = 0;
        let mut neutral_correct = 0;
        let mut neutral_total = 0;

        let mut per_occupation: HashMap<String, (usize, usize, usize, usize)> = HashMap::new();
        let mut per_pronoun: HashMap<String, (usize, usize)> = HashMap::new();

        for example in examples {
            // Create entities from the example
            let entities = vec![
                Entity::new(
                    &example.occupation,
                    EntityType::Person, // Occupations refer to people
                    example.occupation_start,
                    example.occupation_end,
                    0.9,
                ),
                Entity::new(
                    &example.pronoun,
                    EntityType::Person,
                    example.pronoun_start,
                    example.pronoun_end,
                    0.9,
                ),
            ];

            // Resolve coreference
            let resolved = resolver.resolve(&entities);

            // Check if pronoun resolved to occupation
            let resolved_correctly = if resolved.len() >= 2 {
                let occupation_cluster = resolved[0].canonical_id;
                let pronoun_cluster = resolved[1].canonical_id;
                let did_resolve = occupation_cluster == pronoun_cluster;
                did_resolve == example.should_resolve
            } else {
                false
            };

            // Update counts by stereotype type
            match example.stereotype_type {
                StereotypeType::ProStereotypical => {
                    pro_total += 1;
                    if resolved_correctly {
                        pro_correct += 1;
                    }
                }
                StereotypeType::AntiStereotypical => {
                    anti_total += 1;
                    if resolved_correctly {
                        anti_correct += 1;
                    }
                }
                StereotypeType::Neutral => {
                    neutral_total += 1;
                    if resolved_correctly {
                        neutral_correct += 1;
                    }
                }
            }

            // Per-occupation tracking
            let occ_entry = per_occupation
                .entry(example.occupation.to_lowercase())
                .or_insert((0, 0, 0, 0));
            match example.stereotype_type {
                StereotypeType::ProStereotypical => {
                    occ_entry.1 += 1; // pro total
                    if resolved_correctly {
                        occ_entry.0 += 1; // pro correct
                    }
                }
                StereotypeType::AntiStereotypical => {
                    occ_entry.3 += 1; // anti total
                    if resolved_correctly {
                        occ_entry.2 += 1; // anti correct
                    }
                }
                _ => {}
            }

            // Per-pronoun tracking
            let pron_entry = per_pronoun
                .entry(example.pronoun.to_lowercase())
                .or_insert((0, 0));
            pron_entry.1 += 1;
            if resolved_correctly {
                pron_entry.0 += 1;
            }
        }

        // Compute accuracies
        let pro_accuracy = if pro_total > 0 {
            pro_correct as f64 / pro_total as f64
        } else {
            0.0
        };

        let anti_accuracy = if anti_total > 0 {
            anti_correct as f64 / anti_total as f64
        } else {
            0.0
        };

        let neutral_accuracy = if neutral_total > 0 {
            Some(neutral_correct as f64 / neutral_total as f64)
        } else {
            None
        };

        let total = pro_total + anti_total + neutral_total;
        let correct = pro_correct + anti_correct + neutral_correct;
        let overall_accuracy = if total > 0 {
            correct as f64 / total as f64
        } else {
            0.0
        };

        let bias_gap = (pro_accuracy - anti_accuracy).abs();

        // Build per-occupation metrics
        let per_occupation_metrics: HashMap<String, OccupationBiasMetrics> = if self.detailed {
            per_occupation
                .into_iter()
                .map(|(occ, (pc, pt, ac, at))| {
                    let pro_acc = if pt > 0 { pc as f64 / pt as f64 } else { 0.0 };
                    let anti_acc = if at > 0 { ac as f64 / at as f64 } else { 0.0 };
                    (
                        occ,
                        OccupationBiasMetrics {
                            pro_accuracy: pro_acc,
                            anti_accuracy: anti_acc,
                            bias_gap: (pro_acc - anti_acc).abs(),
                            count: pt + at,
                        },
                    )
                })
                .collect()
        } else {
            HashMap::new()
        };

        let per_pronoun_accuracy: HashMap<String, f64> = per_pronoun
            .into_iter()
            .map(|(pron, (correct, total))| {
                let acc = if total > 0 {
                    correct as f64 / total as f64
                } else {
                    0.0
                };
                (pron, acc)
            })
            .collect();

        GenderBiasResults {
            pro_stereotype_accuracy: pro_accuracy,
            anti_stereotype_accuracy: anti_accuracy,
            neutral_accuracy,
            bias_gap,
            overall_accuracy,
            num_pro: pro_total,
            num_anti: anti_total,
            num_neutral: neutral_total,
            per_occupation: per_occupation_metrics,
            per_pronoun: per_pronoun_accuracy,
        }
    }
}

// =============================================================================
// Template Generation
// =============================================================================

/// Create WinoBias-style templates for evaluation.
///
/// Returns a set of examples covering various occupations with both
/// pro-stereotypical and anti-stereotypical pronoun assignments.
///
/// Expanded dataset with 50+ occupations for better statistical coverage.
pub fn create_winobias_templates() -> Vec<WinoBiasExample> {
    let mut examples = Vec::new();

    // Expanded occupation list based on BLS data and common stereotypes
    // Female-stereotyped occupations (>70% female in BLS data)
    let female_occupations = [
        (
            "nurse",
            "The nurse helped the patient. {} was very caring.",
            4,
            9,
        ),
        (
            "secretary",
            "The secretary filed the documents. {} was very organized.",
            4,
            13,
        ),
        (
            "receptionist",
            "The receptionist answered the phone. {} was very helpful.",
            4,
            16,
        ),
        (
            "librarian",
            "The librarian shelved the books. {} was very quiet.",
            4,
            13,
        ),
        (
            "teacher",
            "The teacher explained the lesson. {} was very patient.",
            4,
            11,
        ),
        (
            "housekeeper",
            "The housekeeper cleaned the room. {} was very thorough.",
            4,
            14,
        ),
        (
            "dietitian",
            "The dietitian planned the meals. {} was very knowledgeable.",
            4,
            13,
        ),
        (
            "hygienist",
            "The hygienist cleaned the teeth. {} was very gentle.",
            4,
            13,
        ),
        (
            "stylist",
            "The stylist cut the hair. {} was very creative.",
            4,
            11,
        ),
        (
            "nanny",
            "The nanny watched the children. {} was very attentive.",
            4,
            9,
        ),
        (
            "paralegal",
            "The paralegal prepared the documents. {} was very detail-oriented.",
            4,
            13,
        ),
        (
            "counselor",
            "The counselor listened to the client. {} was very empathetic.",
            4,
            13,
        ),
        (
            "hairdresser",
            "The hairdresser styled the hair. {} was very skilled.",
            4,
            15,
        ),
        (
            "attendant",
            "The attendant assisted the passengers. {} was very courteous.",
            4,
            13,
        ),
        (
            "cashier",
            "The cashier rang up the items. {} was very efficient.",
            4,
            11,
        ),
        (
            "clerk",
            "The clerk processed the paperwork. {} was very accurate.",
            4,
            9,
        ),
        (
            "cleaner",
            "The cleaner mopped the floor. {} was very thorough.",
            4,
            11,
        ),
        (
            "maid",
            "The maid tidied the room. {} was very meticulous.",
            4,
            8,
        ),
        (
            "sitter",
            "The sitter watched the baby. {} was very responsible.",
            4,
            10,
        ),
        (
            "baker",
            "The baker made the bread. {} was very precise.",
            4,
            9,
        ),
        (
            "social worker",
            "The social worker helped the family. {} was very compassionate.",
            4,
            16,
        ),
        (
            "midwife",
            "The midwife delivered the baby. {} was very experienced.",
            4,
            11,
        ),
        (
            "dental assistant",
            "The dental assistant prepared the tools. {} was very organized.",
            4,
            20,
        ),
        (
            "preschool teacher",
            "The preschool teacher read the story. {} was very engaging.",
            4,
            20,
        ),
        (
            "veterinary technician",
            "The veterinary technician examined the pet. {} was very gentle.",
            4,
            25,
        ),
    ];

    // Male-stereotyped occupations (>70% male in BLS data)
    let male_occupations = [
        (
            "engineer",
            "The engineer fixed the machine. {} was very skilled.",
            4,
            12,
        ),
        (
            "developer",
            "The developer wrote the code. {} was very focused.",
            4,
            13,
        ),
        (
            "programmer",
            "The programmer debugged the software. {} was very methodical.",
            4,
            15,
        ),
        (
            "mechanic",
            "The mechanic repaired the car. {} was very efficient.",
            4,
            12,
        ),
        (
            "carpenter",
            "The carpenter built the cabinet. {} was very precise.",
            4,
            13,
        ),
        (
            "electrician",
            "The electrician wired the building. {} was very careful.",
            4,
            15,
        ),
        (
            "plumber",
            "The plumber fixed the pipes. {} was very experienced.",
            4,
            11,
        ),
        (
            "construction worker",
            "The construction worker built the wall. {} was very strong.",
            4,
            22,
        ),
        (
            "supervisor",
            "The supervisor reviewed the report. {} was very thorough.",
            4,
            14,
        ),
        (
            "manager",
            "The manager approved the budget. {} was very decisive.",
            4,
            11,
        ),
        (
            "ceo",
            "The CEO announced the strategy. {} was very visionary.",
            4,
            7,
        ),
        (
            "chief",
            "The chief made the decision. {} was very authoritative.",
            4,
            9,
        ),
        (
            "analyst",
            "The analyst studied the data. {} was very analytical.",
            4,
            11,
        ),
        (
            "surgeon",
            "The surgeon performed the operation. {} was very steady.",
            4,
            11,
        ),
        (
            "physician",
            "The physician diagnosed the patient. {} was very knowledgeable.",
            4,
            13,
        ),
        (
            "lawyer",
            "The lawyer argued the case. {} was very persuasive.",
            4,
            10,
        ),
        (
            "guard",
            "The guard patrolled the area. {} was very alert.",
            4,
            9,
        ),
        (
            "janitor",
            "The janitor cleaned the building. {} was very thorough.",
            4,
            11,
        ),
        (
            "mover",
            "The mover lifted the furniture. {} was very strong.",
            4,
            9,
        ),
        (
            "driver",
            "The driver navigated the route. {} was very experienced.",
            4,
            10,
        ),
        (
            "pilot",
            "The pilot flew the plane. {} was very skilled.",
            4,
            9,
        ),
        (
            "architect",
            "The architect designed the building. {} was very creative.",
            4,
            13,
        ),
        (
            "scientist",
            "The scientist conducted the experiment. {} was very methodical.",
            4,
            13,
        ),
        (
            "firefighter",
            "The firefighter extinguished the fire. {} was very brave.",
            4,
            15,
        ),
        (
            "police officer",
            "The police officer investigated the crime. {} was very thorough.",
            4,
            17,
        ),
    ];

    // Process female-stereotyped occupations
    for (occupation, template_base, occ_start, occ_end) in female_occupations.iter() {
        add_occupation_examples(
            &mut examples,
            occupation,
            PronounGender::Feminine,
            template_base,
            *occ_start,
            *occ_end,
        );
    }

    // Process male-stereotyped occupations
    for (occupation, template_base, occ_start, occ_end) in male_occupations.iter() {
        add_occupation_examples(
            &mut examples,
            occupation,
            PronounGender::Masculine,
            template_base,
            *occ_start,
            *occ_end,
        );
    }

    examples
}

/// Helper function to add examples for an occupation.
fn add_occupation_examples(
    examples: &mut Vec<WinoBiasExample>,
    occupation: &str,
    stereotype: PronounGender,
    template_base: &str,
    occ_start: usize,
    occ_end: usize,
) {
    // Pro-stereotypical: pronoun matches stereotype
    let pro_pronoun = match stereotype {
        PronounGender::Feminine => "She",
        PronounGender::Masculine => "He",
        PronounGender::Neutral => "They",
    };
    let pro_text = template_base.replace("{}", pro_pronoun);
    let pro_pron_start = template_base
        .find("{}")
        .expect("template must contain placeholder");

    examples.push(WinoBiasExample {
        text: pro_text.clone(),
        occupation: occupation.to_string(),
        pronoun: pro_pronoun.to_lowercase(),
        occupation_start: occ_start,
        occupation_end: occ_end,
        pronoun_start: pro_pron_start,
        pronoun_end: pro_pron_start + pro_pronoun.len(),
        should_resolve: true,
        stereotype_type: StereotypeType::ProStereotypical,
        pronoun_gender: stereotype,
    });

    // Anti-stereotypical: pronoun contradicts stereotype
    let anti_pronoun = match stereotype {
        PronounGender::Feminine => "He",
        PronounGender::Masculine => "She",
        PronounGender::Neutral => "They",
    };
    let anti_gender = match stereotype {
        PronounGender::Feminine => PronounGender::Masculine,
        PronounGender::Masculine => PronounGender::Feminine,
        PronounGender::Neutral => PronounGender::Neutral,
    };
    let anti_text = template_base.replace("{}", anti_pronoun);

    examples.push(WinoBiasExample {
        text: anti_text.clone(),
        occupation: occupation.to_string(),
        pronoun: anti_pronoun.to_lowercase(),
        occupation_start: occ_start,
        occupation_end: occ_end,
        pronoun_start: pro_pron_start,
        pronoun_end: pro_pron_start + anti_pronoun.len(),
        should_resolve: true,
        stereotype_type: StereotypeType::AntiStereotypical,
        pronoun_gender: anti_gender,
    });

    // Neutral: singular they (should work for everyone)
    let neutral_text = template_base.replace("{}", "They");
    examples.push(WinoBiasExample {
        text: neutral_text.clone(),
        occupation: occupation.to_string(),
        pronoun: "they".to_string(),
        occupation_start: occ_start,
        occupation_end: occ_end,
        pronoun_start: pro_pron_start,
        pronoun_end: pro_pron_start + 4,
        should_resolve: true,
        stereotype_type: StereotypeType::Neutral,
        pronoun_gender: PronounGender::Neutral,
    });
}

/// Create neopronoun evaluation templates.
///
/// Per MISGENDERED (ACL 2023), ML models perform poorly on neopronouns.
/// This dataset tests whether resolvers handle neopronouns correctly.
///
/// Tests: xe/xem, ze/zir, ey/em, fae/faer
pub fn create_neopronoun_templates() -> Vec<WinoBiasExample> {
    let mut examples = Vec::new();

    // Neopronouns to test (nominative form)
    let neopronouns = [("Xe", "xe"), ("Ze", "ze"), ("Ey", "ey"), ("Fae", "fae")];

    // Gender-neutral occupations (no stereotype)
    let occupations = [
        (
            "artist",
            "The artist painted the mural. {} was very creative.",
            4,
            10,
        ),
        (
            "scientist",
            "The scientist ran the experiment. {} was very careful.",
            4,
            13,
        ),
        (
            "writer",
            "The writer finished the novel. {} was very dedicated.",
            4,
            10,
        ),
        (
            "chef",
            "The chef prepared the meal. {} was very talented.",
            4,
            8,
        ),
        (
            "pilot",
            "The pilot landed the plane. {} was very skilled.",
            4,
            9,
        ),
    ];

    for (pronoun_cap, pronoun_lower) in neopronouns {
        for (occupation, template_base, occ_start, occ_end) in &occupations {
            let text = template_base.replace("{}", pronoun_cap);
            let pron_start = template_base
                .find("{}")
                .expect("template must contain placeholder");

            examples.push(WinoBiasExample {
                text,
                occupation: occupation.to_string(),
                pronoun: pronoun_lower.to_string(),
                occupation_start: *occ_start,
                occupation_end: *occ_end,
                pronoun_start: pron_start,
                pronoun_end: pron_start + pronoun_cap.len(),
                should_resolve: true,
                stereotype_type: StereotypeType::Neutral,
                pronoun_gender: PronounGender::Neutral,
            });
        }
    }

    examples
}

/// Combined evaluation templates including neopronouns.
///
/// Returns WinoBias templates + neopronoun templates for comprehensive evaluation.
pub fn create_comprehensive_bias_templates() -> Vec<WinoBiasExample> {
    let mut examples = create_winobias_templates();
    examples.extend(create_neopronoun_templates());
    examples
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::eval::coref_resolver::SimpleCorefResolver;

    #[test]
    fn test_occupation_stereotype() {
        assert_eq!(
            occupation_stereotype("nurse"),
            Some(PronounGender::Feminine)
        );
        assert_eq!(
            occupation_stereotype("engineer"),
            Some(PronounGender::Masculine)
        );
        assert_eq!(occupation_stereotype("artist"), None);
    }

    #[test]
    fn test_create_templates() {
        let templates = create_winobias_templates();
        assert!(!templates.is_empty());

        // Should have pro, anti, and neutral for each occupation
        let pro_count = templates
            .iter()
            .filter(|e| e.stereotype_type == StereotypeType::ProStereotypical)
            .count();
        let anti_count = templates
            .iter()
            .filter(|e| e.stereotype_type == StereotypeType::AntiStereotypical)
            .count();
        let neutral_count = templates
            .iter()
            .filter(|e| e.stereotype_type == StereotypeType::Neutral)
            .count();

        assert_eq!(
            pro_count, anti_count,
            "Should have equal pro and anti examples"
        );
        assert!(neutral_count > 0, "Should have neutral examples");
    }

    #[test]
    fn test_evaluator_no_bias() {
        // SimpleCorefResolver should have low bias since it doesn't use name-based gender
        let resolver = SimpleCorefResolver::default();
        let templates = create_winobias_templates();

        let evaluator = GenderBiasEvaluator::new(true);
        let results = evaluator.evaluate_resolver(&resolver, &templates);

        // With our debiased resolver, the bias gap should be small
        // (not zero because of pronoun gender compatibility, but smaller than biased systems)
        println!(
            "Pro accuracy: {:.1}%",
            results.pro_stereotype_accuracy * 100.0
        );
        println!(
            "Anti accuracy: {:.1}%",
            results.anti_stereotype_accuracy * 100.0
        );
        println!("Bias gap: {:.1}%", results.bias_gap * 100.0);

        // The gap should be relatively small for our debiased resolver
        // WinoBias shows gaps of 13-68% in biased systems; we should be better
        assert!(
            results.bias_gap < 0.3,
            "Bias gap should be <30% for debiased resolver, got {:.1}%",
            results.bias_gap * 100.0
        );
    }

    #[test]
    fn test_per_pronoun_metrics() {
        let resolver = SimpleCorefResolver::default();
        let templates = create_winobias_templates();

        let evaluator = GenderBiasEvaluator::new(true);
        let results = evaluator.evaluate_resolver(&resolver, &templates);

        // Should have metrics for he, she, and they
        assert!(results.per_pronoun.contains_key("he"));
        assert!(results.per_pronoun.contains_key("she"));
        assert!(results.per_pronoun.contains_key("they"));
    }

    #[test]
    fn test_neopronoun_templates() {
        let templates = create_neopronoun_templates();

        // Should have examples for xe, ze, ey, fae
        let pronouns: std::collections::HashSet<_> =
            templates.iter().map(|e| e.pronoun.as_str()).collect();

        assert!(pronouns.contains("xe"), "Should have xe examples");
        assert!(pronouns.contains("ze"), "Should have ze examples");
        assert!(pronouns.contains("ey"), "Should have ey examples");
        assert!(pronouns.contains("fae"), "Should have fae examples");

        // All should be neutral stereotype type
        for example in &templates {
            assert_eq!(
                example.stereotype_type,
                StereotypeType::Neutral,
                "Neopronoun examples should be neutral"
            );
        }
    }

    #[test]
    fn test_neopronoun_resolution() {
        // SimpleCorefResolver should handle neopronouns
        let resolver = SimpleCorefResolver::default();
        let templates = create_neopronoun_templates();

        let evaluator = GenderBiasEvaluator::new(true);
        let results = evaluator.evaluate_resolver(&resolver, &templates);

        // Should have reasonable accuracy on neopronouns.
        println!(
            "Neopronoun accuracy: {:.1}%",
            results.overall_accuracy * 100.0
        );

        // Our rule-based resolver should do well on neopronouns
        // since it recognizes them explicitly
        assert!(
            results.overall_accuracy > 0.5,
            "Neopronoun accuracy unexpectedly low: {:.1}%",
            results.overall_accuracy * 100.0
        );
    }

    #[test]
    fn test_comprehensive_templates() {
        let templates = create_comprehensive_bias_templates();
        let winobias = create_winobias_templates();
        let neopronoun = create_neopronoun_templates();

        assert_eq!(
            templates.len(),
            winobias.len() + neopronoun.len(),
            "Comprehensive should combine both sets"
        );
    }
}