File size: 22,201 Bytes
c93b07a |
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 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 |
import json
import os.path
import pickle
import yaml
import re
try:
import nltk
def tokenize(
text,
):
tokens = ' '.join(nltk.word_tokenize(text)).replace('``', '"').replace("''", '"').split()
return tokens
from nltk.tokenize.treebank import TreebankWordDetokenizer
def detokenize(text: str):
tokens = text.split()
text = TreebankWordDetokenizer().detokenize(tokens)
text = text.replace(' . ', '. ')
return text
except Exception:
print('-> Cannot import nltk')
def is_disjoint(
span1,
span2,
):
"""
check joint span for exclude spans
:param span1:
:param span2:
:return:
"""
return (span1[0] - span2[1] + 1) * (span2[0] - span1[1] + 1) < 0
def remove_accent(text):
text = re.sub(r'[àáạảãâầấậẩẫăằắặẳẵ]', 'a', text)
text = re.sub(r'[ÀÁẠẢÃĂẰẮẶẲẴÂẦẤẬẨẪ]', 'A', text)
text = re.sub(r'[èéẹẻẽêềếệểễ]', 'e', text)
text = re.sub(r'[ÈÉẸẺẼÊỀẾỆỂỄ]', 'E', text)
text = re.sub(r'[ìíịỉĩ]', 'i', text)
text = re.sub(r'[ÌÍỊỈĨ]', 'I', text)
text = re.sub(r'[òóọỏõôồốộổỗơờớợởỡ]', 'o', text)
text = re.sub(r'[ÒÓỌỎÕÔỒỐỘỔỖƠỜỚỢỞỠ]', 'O', text)
text = re.sub(r'[ùúụủũưừứựửữ]', 'u', text)
text = re.sub(r'[ƯỪỨỰỬỮÙÚỤỦŨ]', 'U', text)
text = re.sub(r'[ỳýỵỷỹ]', 'y', text)
text = re.sub(r'[ỲÝỴỶỸ]', 'Y', text)
text = re.sub(r'đ', 'd', text)
text = re.sub(r'Đ', 'D', text)
return text
def remove_timbre(text):
text = re.sub(r'[àáạảã]', 'a', text)
text = re.sub(r'[ÀÁẠẢÃ]', 'A', text)
text = re.sub(r'[âầấậẩẫ]', 'â', text)
text = re.sub(r'[ÂẦẤẬẨẪ]', 'Â', text)
text = re.sub(r'[ăằắặẳẵ]', 'ă', text)
text = re.sub(r'[ĂẰẮẶẲẴ]', 'Ă', text)
text = re.sub(r'[èéẹẻẽ]', 'e', text)
text = re.sub(r'[ÈÉẸẺẼ]', 'E', text)
text = re.sub(r'[êềếệểễ]', 'ê', text)
text = re.sub(r'[ÊỀẾỆỂỄ]', 'Ê', text)
text = re.sub(r'[ìíịỉĩ]', 'i', text)
text = re.sub(r'[ÌÍỊỈĨ]', 'I', text)
text = re.sub(r'[òóọỏõ]', 'o', text)
text = re.sub(r'[ÒÓỌỎÕ]', 'O', text)
text = re.sub(r'[ôồốộổỗ]', 'ô', text)
text = re.sub(r'[ÔỒỐỘỔỖ]', 'Ô', text)
text = re.sub(r'[ơờớợởỡ]', 'ơ', text)
text = re.sub(r'[ƠỜỚỢỞỠ]', 'Ơ', text)
text = re.sub(r'[ùúụủũ]', 'u', text)
text = re.sub(r'[ÙÚỤỦŨ]', 'U', text)
text = re.sub(r'[ưừứựửữ]', 'ư', text)
text = re.sub(r'[ƯỪỨỰỬỮ]', 'Ư', text)
text = re.sub(r'[ỳýỵỷỹ]', 'y', text)
text = re.sub(r'[ỲÝỴỶỸ]', 'Y', text)
text = re.sub(r'đ', 'd', text)
text = re.sub(r'Đ', 'D', text)
return text
def get_mentions(ner_tags, tokens, ):
spans = []
prev_tag = None
s_pos = None
for i, tag in enumerate(ner_tags):
if tag == 'O':
if prev_tag is not None and s_pos is not None:
# spans.append(([s_pos, i], prev_tag))
spans.append({
'span': [s_pos, i],
'tag': prev_tag,
'text': ' '.join(tokens[s_pos:i]),
})
prev_tag = None
s_pos = None
elif tag.startswith('B'):
if prev_tag is not None and s_pos is not None:
# spans.append(([s_pos, i], prev_tag))
spans.append({
'span': [s_pos, i],
'tag': prev_tag,
'text': ' '.join(tokens[s_pos:i]),
})
s_pos = i
prev_tag = tag[2:]
else:
cur_tag = tag[2:]
if prev_tag is not None and prev_tag != cur_tag and s_pos is not None:
# if prev_tag is not None and s_pos is not None:
# spans.append(([s_pos, i], prev_tag))
spans.append({
'span': [s_pos, i],
'tag': prev_tag,
'text': ' '.join(tokens[s_pos:i]),
})
prev_tag = None
s_pos = None
if i == len(ner_tags) - 1 and prev_tag is not None and s_pos is not None:
# spans.append(([s_pos, i + 1], prev_tag))
spans.append({
'span': [s_pos, i + 1],
'tag': prev_tag,
'text': ' '.join(tokens[s_pos: i + 1])
})
return spans
def mentions2tags(
tokens,
mentions,
):
tags = ['O'] * len(tokens)
for mention in mentions:
mention_tag = mention['tag']
span = mention['span']
if mention_tag != 'O':
mention_tags = [f'B-{mention_tag}'] + [f'I-{mention_tag}'] * (span[1] - span[0] - 1)
else:
mention_tags = ['O'] * (span[1] - span[0])
tags[span[0]: span[1]] = mention_tags
return tags
def load_yaml(fn):
with open(fn, mode='r', encoding='utf8') as f:
config = yaml.safe_load(f)
return config
def load_json(fn):
with open(fn, mode='r', encoding='utf8') as f:
data = json.load(f)
return data
def load_jsonl(fn, num_max_lines=None,):
data = []
i = 0
with open(fn, mode='r', encoding='utf8') as f:
for line in f:
data.append(json.loads(line))
i += 1
if num_max_lines is not None and i == num_max_lines:
break
return data
def load_jsonl_generator(fn, num_max_lines=None,):
i = 0
with open(fn, mode='r', encoding='utf8') as f:
for line in f:
try:
item = json.loads(line)
yield item
i += 1
if num_max_lines is not None and i == num_max_lines:
break
except Exception as e:
print(f'-> error {e} in line content:`\n{line}\n`')
def load_jsonl_by_batch(
fn,
bs,
):
batch = []
with open(fn, mode='r', encoding='utf8', errors='surrogateescape') as f:
for line in f:
try:
item = json.loads(line)
batch.append(item)
except Exception as e:
print(e)
# print(line)
print('#' * 10)
if len(batch) == bs:
yield batch
batch = []
if len(batch) > 0:
yield batch
def load_text_by_batch(
fn,
bs,
):
batch = []
with open(fn, mode='r', encoding='utf8', errors='surrogateescape') as f:
for line in f:
batch.append(line.strip())
if len(batch) == bs:
yield batch
batch = []
if len(batch) > 0:
yield batch
def dump_json(data, fn, indent=None,):
with open(fn, mode='w', encoding='utf8') as f:
json.dump(data, f, ensure_ascii=False, indent=indent,)
def dump_jsonl(data: list, fn,):
with open(fn, mode='w', encoding='utf8') as f:
for item in data:
f.write(json.dumps(item, ensure_ascii=False))
f.write('\n')
def convert_jsonl2jsonl_gz(
input_path,
output_path,
):
import gzip
with gzip.open(output_path, mode='wb',) as f:
for batch in load_jsonl_by_batch(
fn=input_path,
bs=1000,
):
for item in batch:
f.write((json.dumps(item, ensure_ascii=False,) + '\n').encode('utf8'))
# f.write('\n')
def convert_jsonl2jsonl_gz_in_dir(
input_dir,
output_dir=None,
):
if output_dir is None:
output_dir = input_dir
fns = [
fn for fn in os.listdir(input_dir)
if fn.endswith('.jsonl')
]
for fn in fns:
print(f'-> compressing {fn}')
convert_jsonl2jsonl_gz(
input_path=os.path.join(input_dir, fn),
output_path=os.path.join(output_dir, fn + '.gz'),
)
def dump_jsonl_gz(
data,
output_path,
):
import gzip
with gzip.open(output_path, mode='wb') as f:
for item in data:
f.write((json.dumps(item, ensure_ascii=False,) + '\n').encode('utf8'))
def load_jsonl_gz(
fn,
num_max_lines=None,
num_workers=1,
):
if num_workers == 1:
import gzip
else:
import mgzip as gzip
data = []
i = 0
with (gzip.open(fn, mode='rb') if num_workers == 1 else gzip.open(fn, mode='rb', thread=num_workers)) as f:
for line in f:
try:
item = json.loads(line)
data.append(item)
i += 1
if num_max_lines is not None and i == num_max_lines:
break
except Exception as e:
print(e)
return data
def load_jsonl_gz_generator(
fn,
num_max_lines=None,
num_workers=1,
):
if num_workers == 1:
import gzip
else:
import mgzip as gzip
i = 0
with (gzip.open(fn, mode='rb') if num_workers == 1 else gzip.open(fn, mode='rb', thread=num_workers)) as f:
try:
for line in f:
try:
item = json.loads(line)
yield item
i += 1
if num_max_lines is not None and i == num_max_lines:
break
except Exception as e:
print(e)
except Exception as e_file:
print(f'-> error: {e_file}')
def load_jsonl_or_jsonl_gz(
fn,
num_max_lines=None,
num_workers=1,
):
from functools import partial
if fn.endswith('.jsonl'):
load_func = load_jsonl
elif fn.endswith('.jsonl.gz'):
load_func = partial(load_jsonl_gz, num_workers=num_workers,)
else:
raise NotImplementedError()
return load_func(fn, num_max_lines=num_max_lines,)
def load_jsonl_or_jsonl_gz_generator(
fn,
num_max_lines=None,
num_workers=1,
):
from functools import partial
if fn.endswith('.jsonl'):
load_func = load_jsonl_generator
elif fn.endswith('.gz'):
load_func = partial(load_jsonl_gz_generator, num_workers=num_workers,)
else:
raise NotImplementedError()
for item in load_func(fn, num_max_lines=num_max_lines):
yield item
def load_jsonl_gz_by_batch(
fn,
bs,
num_workers=1,
):
if num_workers == 1:
import gzip
else:
import mgzip as gzip
batch = []
with (gzip.open(fn, mode='rb') if num_workers == 1 else gzip.open(fn, mode='rb', thread=num_workers)) as f:
try:
for line in f:
try:
item = json.loads(line)
batch.append(item)
if len(batch) == bs:
yield batch
batch = []
except Exception as e:
print(e)
print(line)
print('#' * 10)
except Exception as e:
print(e)
if len(batch) > 0:
yield batch
def load_jsonl_or_jsonl_gz_by_batch(fn, bs, num_workers=1,):
from functools import partial
if fn.endswith('.jsonl'):
load_func = load_jsonl_by_batch
elif fn.endswith('.jsonl.gz'):
load_func = partial(load_jsonl_gz_by_batch, num_workers=num_workers,)
else:
raise NotImplementedError()
for batch in load_func(fn, bs):
yield batch
def get_load_func(
fn,
):
if fn.endswith('.jsonl'):
load_func = load_jsonl_by_batch
elif fn.endswith('.jsonl.gz'):
load_func = load_jsonl_gz_by_batch
else:
raise NotImplementedError()
return load_func
def load_text_gz(
fn,
max_lines=None,
num_workers=1,
):
if num_workers == 1:
import gzip
else:
import mgzip as gzip
data = []
n = 0
with (gzip.open(fn, mode='rb') if num_workers == 1 else gzip.open(fn, mode='rb', thread=num_workers)) as f:
for line in f:
n += 1
data.append(line.decode('utf8'))
if max_lines is not None and n >= max_lines:
break
return data
def load_text_gz_generator(fn, num_max_lines=None, num_workers=1,):
if num_workers == 1:
import gzip
else:
import mgzip as gzip
n = 0
with (gzip.open(fn, mode='rb') if num_workers == 1 else gzip.open(fn, mode='rb', thread=num_workers)) as f:
for line in f:
n += 1
yield line.decode('utf8')
if num_max_lines is not None and n >= num_max_lines:
break
def dump_pickle(data, fn):
with open(fn, mode='wb') as f:
pickle.dump(data, f)
def load_pickle(fn):
with open(fn, mode='rb',) as f:
data = pickle.load(f)
return data
def load_text(fn):
data = []
with open(fn, mode='r', encoding='utf8') as f:
for line in f:
line = line.strip()
if line:
data.append(line)
return data
def load_text_generator(fn, num_max_lines=None,):
n = 0
with open(fn, mode='r', encoding='utf8') as f:
for line in f:
n += 1
line = line.strip()
yield line
if num_max_lines is not None and n == num_max_lines:
break
def load_text_or_text_gz_generator(fn, num_max_lines=None, num_workers=1,):
from functools import partial
if fn.endswith('.gz'):
load_func = partial(load_text_gz_generator, num_workers=num_workers,)
else:
load_func = load_text_generator
for item in load_func(fn, num_max_lines=num_max_lines):
yield item
def load_zst_generator(fn, num_max_lines=None):
import zstandard as zstd
import io
n = 0
DCTX = zstd.ZstdDecompressor(max_window_size=2 ** 31)
with zstd.open(fn, mode='rb', dctx=DCTX) as zfh, \
io.TextIOWrapper(zfh) as iofh:
for line in iofh:
line = line.strip()
n += 1
yield line
if num_max_lines is not None and n == num_max_lines:
break
def load_zst_jsonl_generator(fn, num_max_lines=None):
import zstandard as zstd
import io
import json
n = 0
DCTX = zstd.ZstdDecompressor(max_window_size=2 ** 31)
with zstd.open(fn, mode='rb', dctx=DCTX) as zfh, \
io.TextIOWrapper(zfh) as iofh:
for line in iofh:
line = line.strip()
line = json.loads(line)
n += 1
yield line
if num_max_lines is not None and n == num_max_lines:
break
def write_text(data, fn):
with open(fn, mode='w', encoding='utf8') as f:
for item in data:
f.write(item)
f.write('\n')
def split_jsonl(fn, n_parts=10,):
data = load_jsonl(fn)
n = len(data)
bs = (n - 1) // n_parts + 1
for i in range(n_parts):
dump_jsonl(data[i * bs: (i + 1) * bs], f'{fn}.part{i}')
def count_file_lines(file_path: str) -> int:
import subprocess
if file_path.endswith('.gz'):
ps = subprocess.Popen(('zcat', file_path), stdout=subprocess.PIPE,)
output = subprocess.check_output(["wc", "-l"], stdin=ps.stdout)
else:
output = subprocess.check_output(["wc", "-l", file_path])
num_lines = int(output.split()[0])
return num_lines
def mask_number(
text,
tag,
):
if tag == 'num.phone' and text.isdigit():
return '<num.phone>'
text = re.sub(r'\d+([\.,]?\d+)*', '<number>', text)
return text
### process ner data ####
def load_conll(fn, sep='\t'):
with open(fn, mode='r', encoding='utf8') as f:
text = f.read()
text = text.strip()
if text == '':
return []
data = []
for sent_text in re.split(r'\n{2,}', text.strip()):
sent_lines = re.split(r'\n', sent_text)
sent = []
for line in sent_lines:
line = line.strip('\n')
if line == '':
continue
parts = line.split(sep)
if len(parts) > 0:
sent.append(parts)
if len(sent) > 0:
data.append(sent)
sent = []
return data
def unique_data(
data,
):
results = []
unique_info = set()
for item in data:
info = (
' '.join(item['tokens']),
' '.join(item['tags'])
)
if info not in unique_info:
unique_info.add(info)
results.append(item)
print(f'-> Deduplicate: from {len(data)} -> {len(results)}')
return results
def identify(
data,
prefix,
):
for i, item in enumerate(data):
item['id'] = f'{prefix}_{i:06d}'
def split_ner_data(
data,
test_size=0.1,
seed=42,
test=False,
):
import random
data = unique_data(data)
random.seed(seed)
from collections import defaultdict
negative_samples = []
samples = []
entity_tag2idxs = defaultdict(set)
entity_values = set()
entity_tag_values = set()
for item in data:
entities = get_mentions(
ner_tags=item['tags'],
tokens=item['tokens'],
)
for entity in entities:
entity_values.add(entity['text'])
entity_tag_values.add((entity['text'], entity['tag']))
if len(entities) == 0:
negative_samples.append(item)
item['negative'] = True
else:
item['negative'] = False
idx = len(samples)
samples.append(item)
for entity in entities:
entity_tag2idxs[entity['tag']].add(idx)
entity_tag2idxs = {tag: list(idxs) for tag, idxs in entity_tag2idxs.items()}
train_samples = []
dev_samples = []
test_samples = []
n_negative_samples = len(negative_samples)
train_pos_idxs = set()
dev_pos_idxs = set()
test_pos_idxs = set()
selected_idxs = set()
for entity_tag, idxs in entity_tag2idxs.items():
idxs = [i for i in idxs if i not in selected_idxs]
if len(idxs) == 0:
continue
random.shuffle(idxs)
n_test = int(test_size * len(idxs))
if n_test == 0:
train_pos_idxs.update(idxs)
else:
dev_pos_idxs.update(idxs[:n_test])
test_pos_idxs.update(idxs[n_test: 2 * n_test])
train_pos_idxs.update(idxs[2 * n_test:])
selected_idxs.update(idxs)
assert len(train_pos_idxs.intersection(dev_pos_idxs)) == 0
assert len(train_pos_idxs.intersection(test_pos_idxs)) == 0
assert len(dev_pos_idxs.intersection(test_pos_idxs)) == 0
train_samples.extend([
samples[i] for i in train_pos_idxs
])
if len(dev_pos_idxs) > 0:
dev_samples.extend([
samples[i] for i in dev_pos_idxs
])
else:
dev_samples.extend([
samples[i] for i in train_pos_idxs
])
test_samples.extend([
samples[i] for i in test_pos_idxs
])
if test:
print('#train samples:', len(train_samples))
print('#dev samples:', len(dev_samples))
print('#test samples:', len(test_samples))
identify(train_samples, prefix='train')
identify(dev_samples, prefix='dev')
identify(test_samples, prefix='test')
return train_samples, dev_samples, test_samples
else:
train_samples = [
*train_samples,
*test_samples,
]
print('#train samples:', len(train_samples))
print('#dev samples:', len(dev_samples))
identify(train_samples, prefix='train')
identify(dev_samples, prefix='dev')
identify(test_samples, prefix='test')
return train_samples, dev_samples
def load_ner_src_tgt(
src_path,
tgt_path,
):
texts = load_text(src_path)
labels = load_text(tgt_path)
assert len(texts) == len(labels)
data = []
for text, label in zip(texts, labels):
tokens = text.split()
tags = label.split()
assert len(tokens) == len(tags)
data.append({
'tokens': tokens,
'tags': tags,
})
return data
def load_ner_src_tgt_inline(fn):
data = []
with open(fn, mode='r', encoding='utf8') as f:
for line in f:
text, tag = line.split('\t')
text = text.strip()
tag = tag.strip()
tokens = text.split()
tags = tag.split()
assert len(tokens) == len(tags)
data.append({
'tokens': tokens,
'tags': tags,
})
return data
def load_syllable(path):
syllables = []
with open(path, mode='r', encoding='utf8') as f:
for line in f:
line = line.strip()
if line == '':
continue
parts = line.split('\t', maxsplit=1)
syllables.append(parts[0])
return syllables
def get_coordinates(
text: str,
):
text = text.strip()
lines = re.split(r'\n+', text)
coordinates = []
for line in lines:
line = line.strip()
if line == '':
continue
long, lat, _ = line.split(',')
lat = float(lat)
long = float(long)
coordinates.append([lat, long])
return coordinates
def load_polygon(
kml_path,
):
from lxml import etree
with open(kml_path, mode='r',) as f:
xml_data = etree.XML(f.read())
# xml_data = etree.parse(kml_path)
place_marks = xml_data.xpath('//Placemark')
results = {}
for place_mark in place_marks:
name = place_mark.xpath('.//name/text()')[0]
coordinates = get_coordinates(place_mark.xpath('.//coordinates/text()')[0])
results[name] = coordinates
return results
|