File size: 3,867 Bytes
01e655b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
import re
import torch
import torch.nn.functional as F


class CustomRepetitionPenaltyLogitsProcessorRepeat:

    def __init__(self, penalty: float, max_input_ids, past_window):
        if not isinstance(penalty, float) or not (penalty > 0):
            raise ValueError(
                f"`penalty` has to be a strictly positive float, but is {penalty}"
            )

        self.penalty = penalty
        self.max_input_ids = max_input_ids
        self.past_window = past_window

    def __call__(
        self, input_ids: torch.LongTensor, scores: torch.FloatTensor
    ) -> torch.FloatTensor:

        input_ids = input_ids[:, -self.past_window :]
        freq = F.one_hot(input_ids, scores.size(1)).sum(1)
        freq[self.max_input_ids :] = 0
        alpha = self.penalty**freq
        scores = torch.where(scores < 0, scores * alpha, scores / alpha)

        return scores


class CustomRepetitionPenaltyLogitsProcessor:

    def __init__(self, penalty: float, max_input_ids, past_window):
        if not isinstance(penalty, float) or not (penalty > 0):
            raise ValueError(
                f"`penalty` has to be a strictly positive float, but is {penalty}"
            )

        self.penalty = penalty
        self.max_input_ids = max_input_ids
        self.past_window = past_window

    def __call__(
        self, input_ids: torch.LongTensor, scores: torch.FloatTensor
    ) -> torch.FloatTensor:

        input_ids = input_ids[:, -self.past_window :]
        score = torch.gather(scores, 1, input_ids)
        _score = score.detach().clone()
        score = torch.where(score < 0, score * self.penalty, score / self.penalty)
        score[input_ids >= self.max_input_ids] = _score[input_ids >= self.max_input_ids]
        scores.scatter_(1, input_ids, score)

        return scores


def count_invalid_characters(s, reserved_tokens: list = []):
    escaped_tokens = [re.escape(token) for token in reserved_tokens]
    reserved_pattern = "|".join(escaped_tokens)
    s = re.sub(rf"{reserved_pattern}", "", s)
    pattern = re.compile(r"[^\u4e00-\u9fffA-Za-z,。、,\. ]")
    non_alphabetic_chinese_chars = pattern.findall(s)
    return set(non_alphabetic_chinese_chars)


def detect_language(sentence):

    chinese_char_pattern = re.compile(r"[\u4e00-\u9fff]")
    english_word_pattern = re.compile(r"\b[A-Za-z]+\b")

    chinese_chars = chinese_char_pattern.findall(sentence)
    english_words = english_word_pattern.findall(sentence)

    if len(chinese_chars) > len(english_words):
        return "zh"
    else:
        return "en"


character_map = {
    ":": ",",
    ";": ",",
    "!": "。",
    "(": ",",
    ")": ",",
    "【": ",",
    "】": ",",
    "『": ",",
    "』": ",",
    "「": ",",
    "」": ",",
    "《": ",",
    "》": ",",
    "-": ",",
    "‘": "",
    "“": "",
    "’": "",
    "”": "",
    ":": ",",
    ";": ",",
    "!": ".",
    "(": ",",
    ")": ",",
    # '[': ',',
    # ']': ',',
    ">": ",",
    "<": ",",
    "-": ",",
}

halfwidth_2_fullwidth_map = {
    "!": "!",
    '"': "“",
    "'": "‘",
    "#": "#",
    "$": "$",
    "%": "%",
    "&": "&",
    "(": "(",
    ")": ")",
    ",": ",",
    "-": "-",
    "*": "*",
    "+": "+",
    ".": "。",
    "/": "/",
    ":": ":",
    ";": ";",
    "<": "<",
    "=": "=",
    ">": ">",
    "?": "?",
    "@": "@",
    # '[': '[',
    "\\": "\",
    # ']': ']',
    "^": "^",
    # '_': '_',
    "`": "`",
    "{": "{",
    "|": "|",
    "}": "}",
    "~": "~",
}


def apply_half2full_map(text):
    translation_table = str.maketrans(halfwidth_2_fullwidth_map)
    return text.translate(translation_table)


def apply_character_map(text):
    translation_table = str.maketrans(character_map)
    return text.translate(translation_table)