|
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: |
|
|
|
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') |
|
n = int(n.rstrip('.')) if n.endswith('.') else float(n) |
|
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: |
|
|
|
pred = preds[1] |
|
else: |
|
|
|
pred = preds[-1] |
|
|
|
pred = pred.replace(",", "") |
|
|
|
|
|
pred = [delete_extra_zero(s.replace(",", "")) for s in re.findall(r'-?\d+/?\.?\d*', pred)] |
|
|
|
if len(pred) == 0: |
|
return None |
|
|
|
if answer_flag: |
|
|
|
pred = pred[0] |
|
else: |
|
|
|
pred = pred |
|
|
|
try: |
|
if pred[-1] == ".": |
|
pred = pred[:-1] |
|
except: |
|
pass |
|
if isinstance(pred, list): |
|
return pred[-1] |
|
else: |
|
return pred |