File size: 13,337 Bytes
d58c721 12d83cf d58c721 12d83cf d58c721 12d83cf d58c721 12d83cf d58c721 12d83cf d58c721 12d83cf d58c721 12d83cf d58c721 |
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 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 |
# Created by Danyang Zhang @X-Lance.
import lemminflect
from nltk.corpus import stopwords
import nltk
#import random
import re
from typing import Pattern, List, Dict, Tuple
from typing import Optional
import json
import numpy as np
from . import sentence_pattern
import logging
logger = logging.getLogger("rewriting")
def match_target(target: str, phrase: str) -> bool:
"""
Args:
target: str as the target pattern, possible targets:
+ v.
+ v.ing
+ who
+ categ
+ kw
+ article
phrase: str as the candidate
Returns:
bool
"""
if not ( target.startswith("<")\
and target.endswith(">...")\
):
return False
pos = target[1:-4]
if pos=="v." or pos=="v.ing":
return judge_verb(pos, phrase)
return True
def transform_target(target: str, phrase: str, **kargs) -> str:
"""
Args:
target: str as the target pattern, possible targets:
+ v.
+ v.ing
+ who
+ categ
+ kw
+ article
phrase: str as the candidate
kargs: dict like {str: something}
Returns:
str as the transformed phrase
"""
if not ( target.startswith("<")\
and target.endswith(">...")\
):
return phrase
pos = target[1:-4]
if pos=="v.":
return to_infinitive(phrase)
if pos=="v.ing":
return to_vbg(phrase)
if pos=="kw":
return extract_keywords(phrase, **kargs)
if pos=="who":
return drop_titles(phrase, **kargs)
return phrase
def judge_verb(pos: str, phrase: str) -> bool:
# function judge_verb {{{ #
"""
Judges if the first word of `phrase` is a verb infinitive or a present
participle.
Args:
pos: str, "v." or "v.ing"
phrase: str
Returns:
bool
"""
tokens = nltk.word_tokenize(phrase)
pos_tags = nltk.pos_tag(tokens)
return pos=="v." and pos_tags[0][1]=="VB"\
or pos=="v.ing" and pos_tags[0][1]=="VBG"
#head = phrase.split(maxsplit=1)[0]
#lemmas = lemminflect.getLemma(head, upos="VERB", lemmatize_oov=False)
#if len(lemmas)==0:
#return False
#
#if pos=="v.":
#return lemmas[0]==head
#elif pos=="v.ing":
#ing = lemminflect.getInflect(lemmas[0], tag="VBG", inflect_oov=False)
#return ing==head
# }}} function judge_verb #
def to_infinitive(phrase: str) -> str:
head, tail = phrase.split(maxsplit=1)
return lemminflect.getLemma(head, upos="VERB")[0]\
+ " "\
+ tail
def to_vbg(phrase: str) -> str:
head, tail = phrase.split(maxsplit=1)
return lemminflect.getInflection(head, tag="VBG")[0]\
+ " "\
+ tail
def extract_keywords( phrase: str
, rng: np.random.Generator = np.random.default_rng()
) -> str:
# function extract_keywords {{{ #
tokens = nltk.word_tokenize(phrase[1:-1])
pos_tags = nltk.pos_tag(tokens)
keywords = map(lambda kwd: (kwd[0].lower(), kwd[1]), pos_tags)
keywords = list( filter( lambda kwd: ( kwd[1].startswith("NN")\
or kwd[1].startswith("JJ")\
or kwd[1].startswith("VB")
)\
and kwd[0] not in stopwords.words()
, keywords
)
)
noun_keywords = list( filter( lambda kwd: not kwd[1].startswith("VB")
, keywords
)
)
if len(noun_keywords)!=0:
keywords = noun_keywords
keywords = list(map(lambda kwd: "\"{:}\"".format(kwd[0]), keywords))
sampled_keywords = list( filter( lambda _: rng.random()<0.3
, keywords
)
)
if len(sampled_keywords)==0:
sampled_keywords = [keywords[rng.integers(len(keywords))]]
return ", ".join(sampled_keywords)
# }}} function extract_keywords #
def drop_titles( phrase: str
, rng: np.random.Generator = np.random.default_rng()
) -> str:
# function drop_titles {{{ #
titles = phrase.split(", ")
sampled_titles = list( filter( lambda _: rng.random()<0.3
, titles[1:]
)
)
return ", ".join([titles[0]] + sampled_titles)
# }}} function drop_titles #
def parse_file(file_name: str, with_regex: bool = False)\
-> Tuple[ List[sentence_pattern.Item]
, Optional[List[Pattern[str]]]
]:
with open(file_name) as f:
item_list = list( map( sentence_pattern.parse_pattern
, f.read().splitlines()
)
)
regex_list = list( map( lambda itm: re.compile(itm.regex)
, item_list
)
) if with_regex else None
return item_list, regex_list
class TransformerSet:
"""
Sentences requiring transformation:
1. search in command and instruction
2. categ in command and instruction
3. author in command and instruction
4. article in command and instruction (Different)
5. other sentences
"""
def __init__( self
, search_pattern_file: str
, article_pattern_file: str
, article_command_pattern_file: str
, categ_pattern_file: str
, author_pattern_file: str
, question_pattern_file: str
, doccano_file: str
, rng: np.random.Generator
):
# method __init__ {{{ #
"""
Args:
search_pattern_file (str): pattern file for search instructions
article_pattern_file (str): pattern file for article instructions
article_command_pattern_file (str): pattern file for article
instructions in "command" field
categ_pattern_file (str): pattern file for category instructions
author_pattern_file (str): pattern file for author instructions
question_pattern_file (str): pattern file for WikiHowNFQA questions
doccano_file (str): the path to the json file exported by doccano
rng (np.random.Generator): used to generate random indices
"""
self._search_template_lib: List[sentence_pattern.Item]
self._article_template_lib: List[sentence_pattern.Item]
self._article_command_template_lib: List[sentence_pattern.Item]
self._categ_template_lib: List[sentence_pattern.Item]
self._author_template_lib: List[sentence_pattern.Item]
self._question_template_lib: List[sentence_pattern.Item]
self._search_template_regex: List[Pattern[str]]
#self._article_template_regex: List[Pattern[str]]
#self._article_command_template_regex: List[Pattern[str]]
#self._categ_template_regex: List[Pattern[str]]
#self._author_template_regex: List[Pattern[str]]
self._search_template_lib, self._search_template_regex =\
parse_file(search_pattern_file, with_regex=True)
self._article_template_lib, _ = parse_file(article_pattern_file)
self._article_command_template_lib, _ = parse_file(article_command_pattern_file)
self._categ_template_lib, _ = parse_file(categ_pattern_file)
self._author_template_lib, _ = parse_file(author_pattern_file)
self._question_template_lib, _ = parse_file(question_pattern_file)
self._annotation_dict: Dict[str, List[str]] = {}
with open(doccano_file) as f:
doccano_dict = json.load(f)
for anntt in doccano_dict:
self._annotation_dict[anntt["text"]] = [anntt["text"]] + anntt["label"]
self._rng: np.random.Generator = rng
# }}} method __init__ #
def transform(self, sentence: str, environment="instruction") -> str:
# method `transform` {{{ #
"""
Args:
sentence: str
environment: str, "instruction" or "command"
Returns:
str
"""
logger.debug("Starting transform: %s", sentence)
has_leading_then = sentence.startswith("Then, ")
if has_leading_then:
sentence = sentence[6].upper() + sentence[7:]
if sentence.startswith("Search an article"):
transformed = self._transform_search(sentence)
elif sentence.startswith("Access the article"):
transformed = self._transform_article(sentence, environment)
elif sentence.startswith("Access the page"):
transformed = self._transform_categ(sentence)
elif sentence.startswith("Check the author"):
transformed = self._transform_author(sentence)
elif sentence.startswith("My question is"):
transformed: str = self._transform_question(sentence)
elif sentence in self._annotation_dict:
candidates = self._annotation_dict[sentence]
random_index = self._rng.integers(len(candidates))
transformed = candidates[random_index]
else:
transformed = sentence
if has_leading_then:
transformed = "Then, " + transformed[0].lower() + transformed[1:]
logger.debug("Transformation result: %s", transformed)
return transformed
# }}} method `transform` #
def _transform_search(self, sentence: str) -> str:
# method _transform_search {{{ #
if sentence in self._annotation_dict:
nb_candidates = len(self._annotation_dict[sentence])
weights = np.full((nb_candidates,), 2)
weights[0] = 1
weights = weights/np.sum(weights)
random_index = self._rng.choice( nb_candidates
, p=weights
)
sentence = self._annotation_dict[sentence][random_index]
template = None
target_str = None
for tpl, rgx in zip(self._search_template_lib, self._search_template_regex):
match_ = rgx.match(sentence)
if match_ is not None:
template = tpl
target_str = match_.group(1)
break
if template is None:
return sentence
# if the template seems to match the sentence according to the regex,
# but the target isn't consistent, we should ignore it.
target_pattern = template.get_targets()
if not match_target(target_pattern[0], target_str):
return sentence
return self._apply_new_template(target_str, self._search_template_lib)
# }}} method _transform_search #
def _transform_article(self, sentence: str, environment: str) -> str:
# method _transform_article {{{ #
"""
Args:
sentence: str
environment: str, "instruction" or "command", indicates different
target template library
Returns:
str
"""
assert sentence.startswith("Access the article \"")\
and sentence.endswith("\"")
target_str = sentence[19:]
target_template_library = self._article_template_lib\
if environment=="instruction"\
else self._article_command_template_lib
return self._apply_new_template(target_str, target_template_library)
# }}} method _transform_article #
def _transform_categ(self, sentence: str) -> str:
assert sentence.startswith("Access the page of category ")
target_str = sentence[28:]
return self._apply_new_template(target_str, self._categ_template_lib)
def _transform_author(self, sentence: str) -> str:
assert sentence.startswith("Check the author page of ")\
and sentence.endswith(".")
target_str = sentence[25:-1]
return self._apply_new_template(target_str, self._author_template_lib)
def _transform_question(self, sentence: str) -> str:
assert sentence.startswith("My question is: ")\
and sentence.endswith("?")
target_str: str = sentence[16:-1]
return self._apply_new_template(target_str, self._question_template_lib)
def _apply_new_template( self
, target_str: str
, template_library: List[sentence_pattern.Item]
) -> str:
# method _apply_new_template {{{ #
new_template_index = self._rng.integers(len(template_library))
new_template = template_library[new_template_index]
#print(new_template)
#print(repr(new_template))
target_pattern = new_template.get_targets()
target_str = transform_target(target_pattern[0], target_str, rng=self._rng)
new_template.implement(iter([target_str]))
return new_template.instantiate()
# }}} method _apply_new_template #
|