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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
import unittest
import numpy as np
from unittest.mock import patch

# Assume the canonical implementation is in canonical.py
# Assume the generated implementation to be tested is in qa_metrics.generated.py
from qa_metrics.canonical import PEDANT as CanonicalPEDANT
from qa_metrics.pedant import PEDANT as GeneratedPEDANT


# --- Sample Data (original + some additions for edge cases) ---
sample_data = [
    {
        "id": "home_addition_cost",
        "question": "cost per square foot to build a home addition",
        "reference": [
            "Home addition cost estimates of $80 to $130 per square foot for a basic family room addition is common.",
            "$124",
        ],
        "candidate": (
            "The cost per square foot to build a home addition, based on the information provided, "
            "would be approximately $124 for a basic family room addition. However, if the addition "
            "includes a bathroom and/or a kitchen, the cost can escalate to $200-250 per square foot."
        ),
    },
    {
        "id": "textbook_cost",
        "question": "average amount spent on textbooks per semester",
        "reference": ["$500"],
        "candidate": (
            "The average amount spent on textbooks per semester is around $100 - $150 (based on the range "
            "of $80 to $120 per book and assuming one to two books per semester)."
        ),
    },
    {
        "id": "engineer_salary",
        "question": "marine engineer salary per hour",
        "reference": ["$38.10 per hour", "$38.10 per hour."],
        "candidate": "The average salary for marine engineers is $38.10 per hour.",
    },
    {
        "id": "song_singing_incorrect",
        "question": "What song are they singing?",
        "reference": ["Jackson took to the stage in London on Thursday and performed their 1995 song Scream"],
        "candidate": 'They are singing the song "Bohemian Rhapsody" by Queen.',
    },
    {
        "id": "actor_joffrey",
        "question": "who is the actor who plays king joffrey",
        "reference": ["Jack Gleeson"],
        "candidate": "Jack Gleeson",
    },
    {
        "id": "channel_cbb",
        "question": "what channel is celebrity big brother on in the usa",
        "reference": ["on CBS", "CBS"],
        "candidate": "Celebrity Big Brother is aired on the CBS network in the USA.",
    },
    {
        "id": "cubs_ws_2016",
        "question": "who did cubs beat in 2016 world series",
        "reference": ["Cleveland Indians", "the Indians"],
        "candidate": "The Chicago Cubs beat the Cleveland Indians in the 2016 World Series.",
    },
    {
        "id": "caroline_vampire_incorrect",
        "question": "what episode does caroline get turned into a vampire",
        "reference": ["Brave New World", "The Return"],
        "candidate": 'Season 4, Episode 10: "The New Deal"',
    },
]

# Extra cases for specific branches/edges
edge_cases = [
    {
        "id": "empty_everything",
        "question": "",
        "reference": [""],
        "candidate": "",
    },
    {
        "id": "exact_substring_match",
        "question": "name the actor",
        "reference": ["jack gleeson"],
        "candidate": "the actor is JACK GLEESON from Game of Thrones.",
    },
    {
        "id": "multi_candidate_mixed",
        "question": "what channel is celebrity big brother on in the usa",
        "reference": ["CBS"],
        "candidate_list": [
            "It's on ABC.",
            "Celebrity Big Brother airs on CBS in the US.",
            "Paramount+ streams it.",
        ],
    },
    {
        "id": "single_reference_rule",
        "question": "who did cubs beat in 2016 world series",
        "reference": "Cleveland Indians",
        "candidate": "The Chicago Cubs beat the Cleveland Indians in the 2016 World Series.",
    },
]


class TestPedantImplementationsRefactored(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        """
        Initialize both canonical and generated PEDANT evaluators.
        If EITHER initialization fails, the exception will propagate and fail the suite.
        """
        print("\nAttempting to initialize Canonical PEDANT instance...")
        cls.canonical_instance = CanonicalPEDANT()
        print("Canonical PEDANT instance created successfully.")

        print("\nAttempting to initialize Generated PEDANT instance...")
        cls.generated_instance = GeneratedPEDANT()
        print("Generated PEDANT instance created successfully.")

    # --- Comparison Helper ---
    def assertOutputsAlmostEqual(self, canonical_output, generated_output, places=5, msg_prefix=""):
        """Helper to compare outputs, handling different types."""
        self.assertEqual(
            type(canonical_output),
            type(generated_output),
            f"{msg_prefix}: Type mismatch - Canonical={type(canonical_output)}, Generated={type(generated_output)}",
        )

        if isinstance(canonical_output, (float, np.floating)):
            self.assertAlmostEqual(
                canonical_output,
                generated_output,
                places=places,
                msg=f"{msg_prefix}: float outputs differ.",
            )
        elif isinstance(canonical_output, dict):
            self.assertEqual(
                set(canonical_output.keys()),
                set(generated_output.keys()),
                f"{msg_prefix}: dict keys differ.",
            )
            for k in canonical_output:
                if isinstance(canonical_output[k], dict):
                    self.assertEqual(
                        set(canonical_output[k].keys()),
                        set(generated_output[k].keys()),
                        f"{msg_prefix}: nested dict keys differ at '{k}'.",
                    )
                    for inner_k in canonical_output[k]:
                        self.assertOutputsAlmostEqual(
                            canonical_output[k][inner_k],
                            generated_output[k][inner_k],
                            places=places,
                            msg_prefix=f"{msg_prefix} dict entry ('{k}', '{inner_k}')",
                        )
                else:
                    self.assertOutputsAlmostEqual(
                        canonical_output[k],
                        generated_output[k],
                        places=places,
                        msg_prefix=f"{msg_prefix} dict entry '{k}'",
                    )
        elif isinstance(canonical_output, list):
            self.assertCountEqual(
                canonical_output,
                generated_output,
                msg=f"{msg_prefix}: list outputs differ (order ignored).",
            )
        elif isinstance(canonical_output, tuple):
            self.assertEqual(
                len(canonical_output),
                len(generated_output),
                msg=f"{msg_prefix}: tuple lengths differ.",
            )
            for i in range(len(canonical_output)):
                self.assertOutputsAlmostEqual(
                    canonical_output[i],
                    generated_output[i],
                    places=places,
                    msg_prefix=f"{msg_prefix} tuple element {i}",
                )
        else:  # bool, str, int, etc.
            self.assertEqual(
                canonical_output, generated_output, msg=f"{msg_prefix}: outputs differ."
            )

    # --- Original parity tests ---

    def test_get_score(self):
        print("\nComparing get_score...")
        for data in sample_data:
            ref = data["reference"][0]
            cand = data["candidate"]
            q = data["question"]
            with self.subTest(msg=f"Testing case: {data['id']}"):
                canonical_score = self.canonical_instance.get_score(ref, cand, q)
                generated_score = self.generated_instance.get_score(ref, cand, q)
                self.assertOutputsAlmostEqual(
                    canonical_score, generated_score, msg_prefix=f"get_score for {data['id']}"
                )

    def test_get_scores(self):
        print("\nComparing get_scores...")
        for data in sample_data:
            ref_list = data["reference"]
            cand = data["candidate"]
            q = data["question"]
            with self.subTest(msg=f"Testing case: {data['id']}"):
                canonical_scores = self.canonical_instance.get_scores(ref_list, cand, q)
                generated_scores = self.generated_instance.get_scores(ref_list, cand, q)
                self.assertOutputsAlmostEqual(
                    canonical_scores, generated_scores, msg_prefix=f"get_scores for {data['id']}"
                )

    def test_get_highest_score(self):
        print("\nComparing get_highest_score...")
        for data in sample_data:
            ref_list = data["reference"]
            cand = data["candidate"]
            q = data["question"]
            with self.subTest(msg=f"Testing case: {data['id']}"):
                canonical_result = self.canonical_instance.get_highest_score(ref_list, cand, q)
                generated_result = self.generated_instance.get_highest_score(ref_list, cand, q)
                self.assertOutputsAlmostEqual(
                    canonical_result, generated_result, msg_prefix=f"get_highest_score for {data['id']}"
                )

    def test_evaluate(self):
        print("\nComparing evaluate...")
        for data in sample_data:
            ref = data["reference"]
            cand = data["candidate"]
            q = data["question"]
            with self.subTest(msg=f"Testing case: {data['id']}"):
                canonical_eval = self.canonical_instance.evaluate(ref, cand, q)
                generated_eval = self.generated_instance.evaluate(ref, cand, q)
                self.assertOutputsAlmostEqual(
                    canonical_eval, generated_eval, msg_prefix=f"evaluate for {data['id']}"
                )

    def test_get_question_type(self):
        print("\nComparing get_question_type...")
        for data in sample_data:
            ref = data["reference"]
            q = data["question"]
            with self.subTest(msg=f"Testing case: {data['id']}"):
                canonical_type = self.canonical_instance.get_question_type(ref, q)
                generated_type = self.generated_instance.get_question_type(ref, q)
                self.assertOutputsAlmostEqual(
                    canonical_type, generated_type, msg_prefix=f"get_question_type for {data['id']}"
                )

    def test_get_judgement_rule(self):
        print("\nComparing get_judgement_rule...")
        for data in sample_data:
            ref = data["reference"]
            cand = data["candidate"]
            q = data["question"]
            with self.subTest(msg=f"Testing case: {data['id']}"):
                canonical_rule = self.canonical_instance.get_judgement_rule(ref, cand, q)
                generated_rule = self.generated_instance.get_judgement_rule(ref, cand, q)
                self.assertOutputsAlmostEqual(
                    canonical_rule, generated_rule, msg_prefix=f"get_judgement_rule for {data['id']}"
                )

    # --- Additional coverage tests ---

    def test_construct_features_variants(self):
        """Exercise construct_features with and without log probabilities."""
        print("\nComparing construct_features variants...")
        # Minimal single-row input using an existing sample
        seed = sample_data[0]
        row = [{
            "question": seed["question"],
            "reference": seed["reference"][0],
            "candidate": seed["candidate"],
        }]

        # Default (with_log_probas=False)
        cf_default = self.canonical_instance.construct_features(row, with_log_probas=False)
        gf_default = self.generated_instance.construct_features(row, with_log_probas=False)
        self.assertEqual(type(cf_default), type(gf_default), "Sparse matrix type mismatch (default).")
        self.assertEqual(cf_default.shape, gf_default.shape, "Feature shape mismatch (default).")

        # With log probas = True
        cf_log = self.canonical_instance.construct_features(row, with_log_probas=True)
        gf_log = self.generated_instance.construct_features(row, with_log_probas=True)
        self.assertEqual(type(cf_log), type(gf_log), "Sparse matrix type mismatch (log).")
        self.assertEqual(cf_log.shape, gf_log.shape, "Feature shape mismatch (log).")

        # Sanity: column count with_log_probas should not be smaller than default
        self.assertGreaterEqual(cf_log.shape[1], cf_default.shape[1], "Canonical columns unexpected (log vs default).")
        self.assertGreaterEqual(gf_log.shape[1], gf_default.shape[1], "Generated columns unexpected (log vs default).")

    def test_rule_and_type_feature_heads(self):
        """Directly test get_rule_features and get_type_features outputs."""
        print("\nComparing get_rule_features/get_type_features...")
        seed = sample_data[2]  # engineer_salary
        data_rule = [{
            "question": seed["question"],
            "reference": seed["reference"][0],
            "candidate": seed["candidate"],
        }]
        data_type = [{
            "question": seed["question"],
            "reference": seed["reference"][0],
        }]

        # Rule features (proba + log_proba)
        c_rule_p, c_rule_lp = self.canonical_instance.get_rule_features(data_rule)
        g_rule_p, g_rule_lp = self.generated_instance.get_rule_features(data_rule)
        self.assertEqual(c_rule_p.shape, g_rule_p.shape, "Rule proba shape mismatch.")
        self.assertEqual(c_rule_lp.shape, g_rule_lp.shape, "Rule log-proba shape mismatch.")
        # Type features (proba + log_proba)
        c_type_p, c_type_lp = self.canonical_instance.get_type_features(data_type)
        g_type_p, g_type_lp = self.generated_instance.get_type_features(data_type)
        self.assertEqual(c_type_p.shape, g_type_p.shape, "Type proba shape mismatch.")
        self.assertEqual(c_type_lp.shape, g_type_lp.shape, "Type log-proba shape mismatch.")

    def test_exact_match_shortcuts(self):
        """Hit the early-return exact match paths in get_score/evaluate."""
        print("\nTesting exact match shortcuts...")
        case = next(x for x in edge_cases if x["id"] == "exact_substring_match")
        ref = case["reference"][0]
        cand = case["candidate"]
        q = case["question"]

        # get_score should shortcut to 1.0
        c_score = self.canonical_instance.get_score(ref, cand, q)
        g_score = self.generated_instance.get_score(ref, cand, q)
        self.assertOutputsAlmostEqual(c_score, g_score, msg_prefix="exact_match get_score")
        self.assertAlmostEqual(c_score, 1.0, places=7, msg="Canonical get_score did not shortcut to 1.0")

        # evaluate should shortcut to True
        c_eval = self.canonical_instance.evaluate([ref], cand, q)
        g_eval = self.generated_instance.evaluate([ref], cand, q)
        self.assertOutputsAlmostEqual(c_eval, g_eval, msg_prefix="exact_match evaluate")
        self.assertTrue(c_eval, "Canonical evaluate did not shortcut to True")

    def test_empty_inputs(self):
        """Exercise evaluate path where no pairs proceed to the model."""
        print("\nTesting empty inputs...")
        case = next(x for x in edge_cases if x["id"] == "empty_everything")
        ref = case["reference"]
        cand = case["candidate"]
        q = case["question"]

        c_eval = self.canonical_instance.evaluate(ref, cand, q)
        g_eval = self.generated_instance.evaluate(ref, cand, q)
        self.assertOutputsAlmostEqual(c_eval, g_eval, msg_prefix="empty inputs evaluate")
        # Depending on implementation comment, expect False when nothing to evaluate.

    def test_multiple_candidates_path(self):
        """Ensure multi-candidate path is exercised in evaluate/get_scores."""
        print("\nTesting multiple candidates path...")
        case = next(x for x in edge_cases if x["id"] == "multi_candidate_mixed")
        ref = case["reference"]
        cand_list = case["candidate_list"]
        q = case["question"]

        # get_scores with candidate list
        c_scores = self.canonical_instance.get_scores(ref, cand_list, q)
        g_scores = self.generated_instance.get_scores(ref, cand_list, q)
        self.assertOutputsAlmostEqual(c_scores, g_scores, msg_prefix="multi-candidate get_scores")

        # evaluate with candidate list
        c_eval = self.canonical_instance.evaluate(ref, cand_list, q)
        g_eval = self.generated_instance.evaluate(ref, cand_list, q)
        self.assertOutputsAlmostEqual(c_eval, g_eval, msg_prefix="multi-candidate evaluate")

    def test_get_judgement_rule_single_reference(self):
        """Exercise the single-reference branch in get_judgement_rule."""
        print("\nTesting get_judgement_rule single-reference branch...")
        case = next(x for x in edge_cases if x["id"] == "single_reference_rule")
        ref = case["reference"]  # string, not list
        cand = case["candidate"]
        q = case["question"]

        c_rule = self.canonical_instance.get_judgement_rule(ref, cand, q)
        g_rule = self.generated_instance.get_judgement_rule(ref, cand, q)
        self.assertOutputsAlmostEqual(c_rule, g_rule, msg_prefix="single-ref get_judgement_rule")

    def test_get_question_type_single_reference(self):
        """Exercise get_question_type with a single reference string."""
        print("\nTesting get_question_type single-reference branch...")
        seed = sample_data[0]
        ref_single = seed["reference"][0]
        q = seed["question"]

        c_type = self.canonical_instance.get_question_type(ref_single, q)
        g_type = self.generated_instance.get_question_type(ref_single, q)
        self.assertOutputsAlmostEqual(c_type, g_type, msg_prefix="single-ref get_question_type")

    def test_download_latest_model_safe(self):
        """
        Ensure download_latest_model executes without real network usage by patching
        the module-level download_link in both implementations.
        """
        print("\nTesting download_latest_model (patched)...")
        canonical_mod = self.canonical_instance.__class__.__module__
        generated_mod = self.generated_instance.__class__.__module__

        with patch(f"{canonical_mod}.download_link") as c_dl, patch(f"{generated_mod}.download_link") as g_dl:
            c_dl.side_effect = lambda *args, **kwargs: None
            g_dl.side_effect = lambda *args, **kwargs: None
            # Should not raise
            self.canonical_instance.download_latest_model()
            self.generated_instance.download_latest_model()
            # Ensure both tried to call their download helpers at least once
            self.assertTrue(c_dl.called, "Canonical download_link was not called.")
            self.assertTrue(g_dl.called, "Generated download_link was not called.")


if __name__ == "__main__":
    unittest.main(verbosity=2)