thefrigidliquidation commited on
Commit
0db3ac6
1 Parent(s): 3806899

Add code to use the model

Browse files
Files changed (1) hide show
  1. pronoun_fixer.py +219 -0
pronoun_fixer.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from tqdm import tqdm
2
+ from transformers import FillMaskPipeline, RobertaTokenizerFast
3
+
4
+
5
+ MAX_CTX_LEN = 512
6
+
7
+ SPACE_PREFIX = 'Ġ'
8
+
9
+ PRONOUN_TOKENS = {
10
+ 'I', 'ĠI',
11
+ 'you', 'You', 'Ġyou', 'ĠYou',
12
+ 'he', 'He', 'Ġhe', 'ĠHe',
13
+ 'she', 'She', 'Ġshe', 'ĠShe',
14
+ 'it', 'It', 'Ġit', 'ĠIt',
15
+ 'we', 'We', 'Ġwe', 'ĠWe',
16
+ 'they', 'They', 'Ġthey', 'ĠThey',
17
+ 'my', 'My', 'Ġmy', 'ĠMy',
18
+ 'your', 'Your', 'Ġyour', 'ĠYour',
19
+ 'his', 'His', 'Ġhis', 'ĠHis',
20
+ 'her', 'Her', 'Ġher', 'ĠHer',
21
+ 'its', 'Its', 'Ġits', 'ĠIts',
22
+ 'our', 'Our', 'Ġour', 'ĠOur',
23
+ 'their', 'Their', 'Ġtheir', 'ĠTheir',
24
+ 'mine', 'Mine', 'Ġmine', 'ĠMine',
25
+ 'yours', 'Yours', 'Ġyours', 'ĠYours',
26
+ 'hers', 'Hers', 'Ġhers', 'ĠHers',
27
+ 'ours', 'Ours', 'Ġours', 'ĠOurs',
28
+ 'theirs', 'Theirs', 'Ġtheirs', 'ĠTheirs',
29
+ }
30
+
31
+
32
+ def count_tokens(tokenizer, text: str) -> int:
33
+ """ return number of tokens in string """
34
+ return len(tokenizer(text)['input_ids'])
35
+
36
+
37
+ def text_to_token_names(tokenizer, text: str) -> list[str]:
38
+ inputs = tokenizer(text)
39
+ ref_tokens = []
40
+ for id in inputs["input_ids"]:
41
+ token = tokenizer._convert_id_to_token(id)
42
+ ref_tokens.append(token)
43
+ return ref_tokens
44
+
45
+
46
+ def text_to_token_ids(tokenizer, text: str) -> list[str]:
47
+ return tokenizer(text)["input_ids"]
48
+
49
+
50
+ def has_at_least_one_pronoun(tokenizer, text: str) -> bool:
51
+ token_names = text_to_token_names(tokenizer, text)
52
+ for pronoun_token in PRONOUN_TOKENS:
53
+ if pronoun_token in token_names:
54
+ return True
55
+ return False
56
+
57
+
58
+ def chunk_to_contexts(tokenizer, text: str):
59
+ lines = text.splitlines()
60
+
61
+ for i in range(len(lines)):
62
+
63
+ # add lines before and after for context
64
+ ctx = [lines[i]]
65
+ focus_line_idx = 0
66
+ before_line_idx = i
67
+ after_line_idx = i
68
+
69
+ # try adding lines as context until we reach MAX_CTX_LEN
70
+ while True:
71
+
72
+ something_done = False
73
+
74
+ # try adding a line before
75
+ if before_line_idx - 1 >= 0:
76
+ before_candidate = [lines[before_line_idx - 1]] + ctx
77
+ assert len(before_candidate) == len(ctx) + 1
78
+ if count_tokens(tokenizer, "\n".join(before_candidate)) < MAX_CTX_LEN:
79
+ ctx = before_candidate
80
+ focus_line_idx += 1
81
+ before_line_idx -= 1
82
+ something_done = True
83
+
84
+ # try adding a line after
85
+ if after_line_idx + 1 < len(lines):
86
+ # after_candidate = ctx + "\n" + lines[after_line_idx + 1]
87
+ after_candidate = ctx + [lines[after_line_idx + 1]]
88
+ if count_tokens(tokenizer, "\n".join(after_candidate)) < MAX_CTX_LEN:
89
+ ctx = after_candidate
90
+ after_line_idx += 1
91
+ something_done = True
92
+
93
+ # if we can't add any line, we're done
94
+ if not something_done:
95
+ break
96
+
97
+ assert len("".join(f"{x}\n" for x in ctx).splitlines()) == len(ctx)
98
+
99
+ yield "".join(f"{x}\n" for x in ctx), focus_line_idx
100
+
101
+
102
+ def mask_pronouns(tokenizer: RobertaTokenizerFast, text: str) -> tuple[str, list[str]]:
103
+ """ replaces all pronouns in text with <mask> """
104
+ token_names = text_to_token_names(tokenizer, text)
105
+
106
+ masked_token_names = []
107
+ original_pronouns = []
108
+
109
+ for token_name in token_names:
110
+ if token_name in PRONOUN_TOKENS:
111
+ masked_token_names.append(tokenizer.mask_token)
112
+ original_pronouns.append(token_name)
113
+ else:
114
+ masked_token_names.append(token_name)
115
+
116
+ masked_text = tokenizer.decode(tokenizer.convert_tokens_to_ids(masked_token_names), skip_special_tokens=False)
117
+ # remove start and end tokens
118
+ return masked_text[len(tokenizer.bos_token):-len(tokenizer.eos_token)], original_pronouns
119
+
120
+
121
+ def uncase_token(token_name: str) -> str:
122
+ token_name = token_name.replace(' ', '')
123
+ token_name = token_name.replace(SPACE_PREFIX, '')
124
+ return token_name.lower()
125
+
126
+
127
+ def uncase_mask_result(mask_result):
128
+ uncased_token_probs = {uncase_token(k): 0 for k in PRONOUN_TOKENS}
129
+ for guess in mask_result:
130
+ uncased_token_str = uncase_token(guess['token_str'])
131
+ if uncased_token_str not in uncased_token_probs:
132
+ continue
133
+ uncased_token_probs[uncased_token_str] += guess['score']
134
+ return uncased_token_probs
135
+
136
+
137
+ def case_token_like(best_token_uncased: str, original_token: str, best_token_cased_str: str) -> str:
138
+ """
139
+ :param best_token_uncased: the uncased, unspaced token that's the best match
140
+ :param original_token: the original token we are replacing
141
+ :param best_token_cased_str: the token str that's the best match. used for some cap
142
+ :return:
143
+ """
144
+ space = (SPACE_PREFIX == original_token[0]) or (' ' == original_token[0])
145
+ cap = original_token[1 if space else 0].isupper()
146
+ if best_token_uncased == 'i':
147
+ cap = True
148
+ # if the original token was 'I', we can't use it for cap info
149
+ if original_token in ['I', 'ĠI']:
150
+ cap = best_token_cased_str.strip()[0].isupper()
151
+ if cap:
152
+ best_token_uncased = best_token_uncased[0].upper() + best_token_uncased[1:]
153
+ if space:
154
+ best_token_uncased = ' ' + best_token_uncased
155
+ return best_token_uncased
156
+
157
+
158
+ def fix_pronouns_in_text(
159
+ unmasker: FillMaskPipeline,
160
+ tokenizer,
161
+ text: str,
162
+ alpha: float = 0.05,
163
+ use_tqdm: bool = False,
164
+ tqdm_kwargs=None
165
+ ) -> str:
166
+ """
167
+ Fixes pronouns in MTL text
168
+ :param unmasker: unmasker pipeline
169
+ :param tokenizer: model tokenizer
170
+ :param text: text to fix
171
+ :param alpha: only replace the existing pronouns with probability less than alpha
172
+ :param use_tqdm: show tqdm progress bar
173
+ :param tqdm_kwargs: any tqdm args
174
+ :return: the fixed text
175
+ """
176
+ if tqdm_kwargs is None:
177
+ tqdm_kwargs = {}
178
+
179
+ fixed_lines = []
180
+ ctxs = list(chunk_to_contexts(tokenizer, text))
181
+ ctxs_iter = tqdm(ctxs, smoothing=0.0, desc="Fixing pronouns", **tqdm_kwargs) if use_tqdm else ctxs
182
+
183
+ for ctx, focus_line_idx in ctxs_iter:
184
+
185
+ ctx_lines = ctx.splitlines()
186
+ focus_line = ctx_lines[focus_line_idx]
187
+
188
+ # we can skip focusing on lines without a pronoun
189
+ if not has_at_least_one_pronoun(tokenizer, focus_line):
190
+ fixed_lines.append(focus_line)
191
+ continue
192
+
193
+ # mask all pronouns
194
+ masked_ctx, original_pronouns = mask_pronouns(tokenizer, ctx)
195
+
196
+ # unmask pronouns
197
+ mask_results = unmasker(masked_ctx)
198
+ if isinstance(mask_results[0], dict):
199
+ mask_results = [mask_results]
200
+
201
+ unmasked_ctx = masked_ctx
202
+
203
+ for i, mask_result in enumerate(mask_results):
204
+ original_pronoun = original_pronouns[i]
205
+ uncased_original = uncase_token(original_pronoun)
206
+ uncased_result = uncase_mask_result(mask_result)
207
+
208
+ # if what was there doesn't make any sense, replace it
209
+ if uncased_result[uncased_original] < alpha:
210
+ best_uncased_pronoun = max(uncased_result, key=uncased_result.get)
211
+ # TODO: ensure correct type, possessive, adj, subject
212
+ best_cased_pronoun = case_token_like(best_uncased_pronoun, original_pronoun, mask_result[0]['token_str'])
213
+ unmasked_ctx = unmasked_ctx.replace(tokenizer.mask_token, best_cased_pronoun, 1)
214
+ else:
215
+ unmasked_ctx = unmasked_ctx.replace(tokenizer.mask_token, original_pronoun.replace(SPACE_PREFIX, ' '), 1)
216
+
217
+ fixed_lines.append(unmasked_ctx.splitlines()[focus_line_idx])
218
+
219
+ return "\n".join(fixed_lines)