You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

custom_tabulate.py 5.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. import os
  2. import sys
  3. import re
  4. from agbench.tabulate_cmd import default_tabulate
  5. import json
  6. import pandas as pd
  7. import sqlite3
  8. import glob
  9. import string
  10. import warnings
  11. import numpy as np
  12. EXCLUDE_DIR_NAMES = ["__pycache__"]
  13. def in_house_normalize_answer(a):
  14. # Lower case
  15. # Trim (left and right)
  16. # standardize comma separated values
  17. # Replace multiple spaces with one space
  18. # Remove trailing punctuation
  19. norm_answer = ", ".join(a.strip().lower().split(","))
  20. norm_answer = re.sub(r"[\.\!\?]+$", "", re.sub(r"\s+", " ", norm_answer))
  21. return norm_answer
  22. def in_house_question_scorer(
  23. model_answer: str,
  24. ground_truth: str,
  25. ) -> bool:
  26. n_ma = in_house_normalize_answer(model_answer)
  27. n_gt = in_house_normalize_answer(ground_truth)
  28. return (n_gt != "" and n_gt == n_ma)
  29. def gaia_question_scorer(
  30. model_answer: str,
  31. ground_truth: str,
  32. ) -> bool:
  33. #FROM: https://huggingface.co/spaces/gaia-benchmark/leaderboard/blob/main/scorer.py
  34. def normalize_number_str(number_str: str) -> float:
  35. # we replace these common units and commas to allow
  36. # conversion to float
  37. for char in ["$", "%", ","]:
  38. number_str = number_str.replace(char, "")
  39. try:
  40. return float(number_str)
  41. except ValueError:
  42. print(f"String {number_str} cannot be normalized to number str.")
  43. return float("inf")
  44. def split_string(s: str, char_list: list[str] = [",", ";"],) -> list[str]:
  45. pattern = f"[{''.join(char_list)}]"
  46. return re.split(pattern, s)
  47. def normalize_str(input_str, remove_punct=True) -> str:
  48. """
  49. Normalize a string by:
  50. - Removing all white spaces
  51. - Optionally removing punctuation (if remove_punct is True)
  52. - Converting to lowercase
  53. Parameters:
  54. - input_str: str, the string to normalize
  55. - remove_punct: bool, whether to remove punctuation (default: True)
  56. Returns:
  57. - str, the normalized string
  58. """
  59. # Remove all white spaces. Required e.g for seagull vs. sea gull
  60. no_spaces = re.sub(r"\s", "", input_str)
  61. # Remove punctuation, if specified.
  62. if remove_punct:
  63. translator = str.maketrans("", "", string.punctuation)
  64. return no_spaces.lower().translate(translator)
  65. else:
  66. return no_spaces.lower()
  67. def is_float(element: any) -> bool:
  68. try:
  69. float(element)
  70. return True
  71. except ValueError:
  72. return False
  73. # if gt is a number
  74. if is_float(ground_truth):
  75. normalized_answer = normalize_number_str(model_answer)
  76. return normalized_answer == float(ground_truth)
  77. # if gt is a list
  78. elif any(char in ground_truth for char in [",", ";"]):
  79. # question with the fish: normalization removes punct
  80. gt_elems = split_string(ground_truth)
  81. ma_elems = split_string(model_answer)
  82. # check length is the same
  83. if len(gt_elems) != len(ma_elems):
  84. #warnings.warn(
  85. # "Answer lists have different lengths, returning False.", UserWarning
  86. #)
  87. return False
  88. # compare each element as float or str
  89. comparisons = []
  90. for ma_elem, gt_elem in zip(ma_elems, gt_elems):
  91. if is_float(gt_elem):
  92. normalized_ma_elem = normalize_number_str(ma_elem)
  93. comparisons.append(normalized_ma_elem == float(gt_elem))
  94. else:
  95. # we do not remove punct since comparisons can include punct
  96. comparisons.append(
  97. normalize_str(ma_elem, remove_punct=False)
  98. == normalize_str(gt_elem, remove_punct=False)
  99. )
  100. return all(comparisons)
  101. # if gt is a str
  102. else:
  103. return normalize_str(model_answer) == normalize_str(ground_truth)
  104. ##############
  105. def scorer(instance_dir):
  106. # Read the expected answer
  107. expected_answer_file = os.path.join(instance_dir, "expected_answer.txt")
  108. if not os.path.isfile(expected_answer_file):
  109. return None
  110. expected_answer = None
  111. with open(expected_answer_file, "rt") as fh:
  112. expected_answer = fh.read().strip()
  113. # Read the console
  114. console_log_file = os.path.join(instance_dir, "console_log.txt")
  115. if not os.path.isfile(console_log_file):
  116. return None
  117. console_log = ""
  118. with open(console_log_file, "rt") as fh:
  119. console_log = fh.read()
  120. final_answer = None
  121. m = re.search(r"FINAL ANSWER:(.*?)\n", console_log, re.DOTALL)
  122. if m:
  123. final_answer = m.group(1).strip()
  124. # Missing the final answer line
  125. if final_answer is None:
  126. return None
  127. # Return true if they are equal after normalization
  128. # return in_house_question_scorer(final_answer, expected_answer)
  129. return gaia_question_scorer(final_answer, expected_answer)
  130. def main(args):
  131. default_tabulate(args, scorer=scorer)
  132. if __name__ == "__main__" and __package__ is None:
  133. main(sys.argv)