Download annotations/annotation_1/test.py from mcy98/RECODE-H: direct link, hf CLI and curl.
- Browser
- Download file 19 kB
-
https://huggingface.co/datasets/mcy98/RECODE-H/resolve/main/annotations/annotation_1/test.py
- Command line
-
hf download hf://datasets/mcy98/RECODE-H/annotations/annotation_1/test.py
-
curl -L -o test.py https://huggingface.co/datasets/mcy98/RECODE-H/resolve/main/annotations/annotation_1/test.py
19 kB
| 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): | |
| 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) | |