auto-info / test.py
rookiemango's picture
Upload folder using huggingface_hub
da66274 verified
raw
history blame
2.38 kB
from fraction import Fraction
import re
def is_number(s):
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
ANSWER_TRIGGER = 'The answer is'
def handle_frac(pred):
if '/' in pred:
denominator = pred.split('/')[1]
numerator = pred.split('/')[0]
if is_number(denominator) == True and is_number(numerator) == True:
if denominator == '0':
return round(float(numerator.replace(',', '')))
else:
frac = Fraction(pred.replace(',', ''))
num_numerator = frac.numerator
num_denominator = frac.denominator
return round(float(num_numerator / num_denominator))
def delete_extra_zero(n):
'''删除小数点后多余的0'''
try: n=float(n)
except:
# print("None {}".format(n))
try:
rr = str(handle_frac(n))
return rr
except:
return ''
if isinstance(n, int):
return str(n)
if isinstance(n, float):
n = str(n).rstrip('0') # 删除小数点后多余的0
n = int(n.rstrip('.')) if n.endswith('.') else float(n) # 只剩小数点直接转int,否则转回float
n=str(n)
return n
def output_answer_clean(model_pred):
model_pred = model_pred.lower()
preds = model_pred.split(ANSWER_TRIGGER.lower())
answer_flag = True if len(preds) > 1 else False
if answer_flag:
# Pick first answer with flag
pred = preds[1]
else:
# Pick last number without flag
pred = preds[-1]
pred = pred.replace(",", "")
# pred = [s for s in re.findall(r'-?\d+\.?\d*', pred)]
# pred = [s.replace(",", "") for s in re.findall(r'-?\d+/?\.?\d*', pred)]
pred = [delete_extra_zero(s.replace(",", "")) for s in re.findall(r'-?\d+/?\.?\d*', pred)]
if len(pred) == 0:
return None
if answer_flag:
# choose the first element in list
pred = pred[0]
else:
# choose the last element in list
pred = pred
try:
if pred[-1] == ".":
pred = pred[:-1]
except:
pass
if isinstance(pred, list):
return pred[-1]
else:
return pred