File size: 2,381 Bytes
167df7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da66274
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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