dag_tools.py 33.6 KB
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
# -*- coding: utf-8 -*-
import os, io, argparse, re
from lxml import etree

# Lista frekwencyjna w trzech kolumnach rozdzielonych tabulacją: liczba wystąpień, lemat, pos
FREQLIST = '/home/dorotak/korba/korba-ameba/freq-nkjp1m.txt'

# Lista typów (elementów tekstu TEI), które zostaną pominięte w eksporcie do dag -
# wszystkie, które nie są interpretowane w anotacji bez 'foreign'.
OMITLIST = ['quote']

namespaces = {
  'tei': 'http://www.tei-c.org/ns/1.0',
  'xi': 'http://www.w3.org/2001/XInclude',
  'nkjp': 'http://www.nkjp.pl/ns/1.0',
  'xml': 'http://www.w3.org/XML/1998/namespace'
}

def new_segment(line_list):
  seg = {'start': int(line_list[0]), 'end': int(line_list[1]), 'orth': line_list[2], 'disamb': True if line_list[-1] == 'disamb' else False}
  if seg['disamb']:
    seg['interpretation'] = line_list[3] + ':' + line_list[4]
  return seg

def check_freq(last_lex, last_pos, new_lex, new_pos):
  found = 0
  last_f = 0
  new_f = 0
  for line in io.open(FREQLIST, 'r', encoding='utf-8'):
    f, lex, pos = line.strip().split('\t')
    if (last_lex == lex) and (last_pos == pos):
      last_f = int(f)
      found += 1
    if (new_lex == lex) and (new_pos == pos):
      new_f = int(f)
      found += 1
    if found == 2:
      break
  return last_f, new_f

# Przetwarza tekst po tagerze filtrując tylko interpretacje oznaczone disamb
# Uwaga na sytuacje, gdy jest kilka takich interpretacji dla segmentu - zdarza się
# to jeśli interpretacje różnią się tylko lematem a znaczniki są takie same.
def read_text(filename):
  file_in = io.open(filename, 'r', encoding='utf-8')
  seg_list = []
  newpara = False
  
  for line in file_in:
    line_list = line.split()
    if len(line_list) > 0:
      if line_list[-1] == 'disamb':
        if len(seg_list) and not newpara:
          last_seg = seg_list[-1]
          # Jeśli aktualnie czytany segment ma takie same 'start' i 'end', to sprawdź, który wybrać
          # Na razie - zignoruj
          if last_seg['start'] == int(line_list[0]) and last_seg['end'] == int(line_list[1]):
#            pass
#            print u"Kilka wybranych interpretacji: {}".format(line.strip()).encode('utf-8')
            last_f, new_f = check_freq(last_seg['interpretation'].split(':',2)[0], last_seg['interpretation'].split(':',2)[1], line_list[3], line_list[4].split(':',1)[0])
            if new_f > last_f:
              print u"zmiana dla segmentu {}: {} {}:{} -> {} {}:{}".format(line_list[2], last_f, last_seg['interpretation'].split(':',2)[0], last_seg['interpretation'].split(':',2)[1], new_f, line_list[3], line_list[4].split(':',1)[0]).encode('utf-8')
              seg_list.pop()
              seg_list.append(new_segment(line_list))
          else:
            seg_list.append(new_segment(line_list))
        # Jeszcze pusta lista segmentów lub był nowy akapit
        else:
          seg_list.append(new_segment(line_list))
          newpara = False
    # pusta linia w pliku - przestaw newpara
    else:
      newpara = True
      
  file_in.close()
  return seg_list

def print_dag_simple(seg_list):

  for seg in seg_list:
    print u"{}\t{}\t{}".format(seg['start'], seg['end'], seg['orth']).encode('utf-8')


# Przetwarza tekst po tagerze zbierając również choice'y
def process_text_choice(filename):
  file_in = io.open(filename, 'r', encoding='utf-8')
  seg_list = []
  newpara = False
  
  for line in file_in:
    line_list = line.split()
    if len(line_list) > 0:
      if len(seg_list) and not newpara:
        found = False
        for seg_var in seg_list[-1]:
          # Jeśli w którymś z wariantów na ostatnim miejscu jest segment o takim samym start i end - zaktualizuj go i zakończ
          if seg_var[-1]['start'] == int(line_list[0]) and seg_var[-1]['end'] == int(line_list[1]):
            if line_list[-1] == 'disamb':
              seg_var[-1]['disamb'] = True
              seg_var[-1]['interpretation'] = line_list[3] + ':' + line_list[4]
            found = True
            break
        if not found:
          # Jeśli segment zaczyna się jak inne warianty - dodaj nowy
          if seg_list[-1][0][0]['start'] == int(line_list[0]):
            seg_list[-1].append([new_segment(line_list)])
          # Segment zaczyna się inaczej - jeśli wszystkie warianty mają ten sam end - dołóż nowy segment do listy,
          # jeśli nie - znajdź wariant, do którego należy go dołożyć.
          else:
            endings = [seg_var[-1]['end'] for seg_var in seg_list[-1]]
            if len(set(endings)) == 1:
              if int(line_list[1]) > endings[0]:
                seg_list.append([[new_segment(line_list)]])
              else:
                print u'Kolejny segment kończy się wcześniej niż poprzednie: {}'.format(line.strip())
            else:
#              print 'endings: {}'.format(endings)
              seg_list[-1][endings.index(int(line_list[0]))].append(new_segment(line_list))
            
      # Jeszcze pusta lista segmentów lub był nowy akapit
      else:
        seg_list.append([[new_segment(line_list)]])
        newpara = False
    # pusta linia w pliku - przestaw newpara
    else:
      newpara = True

      
  file_in.close()
  return seg_list


def print_dag_segs(seg_list):
  seg_len = 0  

  for choice in seg_list:
    for paren in choice:
      seg_len += len(paren)

  print u"Liczba segmentów: {}".format(seg_len).encode('utf-8')

  for var in seg_list:
    print var
  
def test_dag(seg_list, filename):
  namespaces = {
    'tei': 'http://www.tei-c.org/ns/1.0',
    'xi': 'http://www.w3.org/2001/XInclude',
    'nkjp': 'http://www.nkjp.pl/ns/1.0',
    'xml': 'http://www.w3.org/XML/1998/namespace'
  }

  directory = os.path.dirname(filename)
  seg_tree = etree.parse(os.path.join(directory, 'ann_segmentation.xml'))
  sents = seg_tree.xpath("//tei:s", namespaces=namespaces)
  tree_segs = []
  for s in sents:
    tree_segs.extend(s.getchildren())
  if len(tree_segs) == len(seg_list):
    print u">>>Folder {} - ta sama liczba elementów zdania".format(directory).encode("utf-8")
  else:
    print u"<<<Folder {} - różna liczba elementów zdania".format(directory).encode("utf-8")

  for ind, tree_s in enumerate(tree_segs, start=0):
    if ind >= len(seg_list):
      print u"Plik DAG ma za mało segmentów - brak odpowiednika dla id={}".format(tree_s.get('{http://www.w3.org/XML/1998/namespace}id')).encode("utf-8")
    else:
      if tree_s.tag == '{http://www.tei-c.org/ns/1.0}seg':
        if len(seg_list[ind]) != 1:
#          print u"Podział na choice w DAG dla pojedynczego segmentu o id={}".format(tree_s.get('{http://www.w3.org/XML/1998/namespace}id')).encode("utf-8")
          print u"{} - {}".format(etree.tostring(tree_s, method='text', encoding='unicode'), seg_list[ind]).encode("utf-8")
        else:
#          print u"{}".format(tree_s.xpath('.//tei:w/text()', namespaces = namespaces)).encode("utf-8")
          if len(seg_list[ind][0]) != 1:
            print u"Dla segmentu o id={} jest kilka segmentów w DAG".format(tree_s.get('{http://www.w3.org/XML/1998/namespace}id')).encode("utf-8")
#          else: # w ann_segmentation jest wersja transliterowana - nie można tego sprawdzić
#            if tree_s.xpath('.//tei:w/text()', namespaces = namespaces)[0] != seg_list[ind][0][0]['orth']:
#              print u"Dla segmentu o id={} jest inny napis w DAG".format(tree_s.get('{http://www.w3.org/XML/1998/namespace}id')).encode("utf-8")
      elif tree_s.tag == '{http://www.tei-c.org/ns/1.0}choice':
        tree_choice = [len(elem.xpath('descendant-or-self::tei:seg', namespaces=namespaces)) for elem in tree_s]
        tree_choice.sort()
        seg_list_choice = [len(choice) for choice in seg_list[ind]]
        seg_list_choice.sort()
#        print "ind: {}, {} - {}".format(ind, tree_choice, seg_list_choice)
        if tree_choice != seg_list_choice:
#          print u"Niezgodność w DAG dla segmentu z choice od id={}".format(tree_s.xpath('descendant-or-self::tei:seg', namespaces=namespaces)[0].get('{http://www.w3.org/XML/1998/namespace}id')).encode("utf-8")
          print u"{} - {}".format(etree.tostring(tree_s, method='text', encoding='unicode'), seg_list[ind]).encode("utf-8")
      else:
        print u"Nietypowy element w zdaniu: {}".format(tree_s).encode("utf-8")

def find_morph(seg_id, morph_index, morph_list):
  m_index = morph_index
  while (m_index < len(morph_list)) and (morph_list[m_index].get('corresp','') != "ann_segmentation.xml#{}".format(seg_id)):
    m_index += 1
  if m_index == len(morph_list):
    return (morph_index, []) 
  else:
    return (m_index, [morph_list[m_index]])

def tag_wo_ns(elem):
  return elem.tag.rsplit("}", 1)[-1]

# Przystosowanie do nowego formatu Concrafta - dodatkowe cztery kolumny (dwie przed prawdopodobieństwem i dwie po)
def print_interps(dag_out, start, end, morph_seg, seg_type, rejected, disamb, last_in_sent):
  orth = morph_seg.xpath('./tei:fs/tei:f[@name="orth"]/tei:string', namespaces = namespaces)[0].text
  if last_in_sent:
    eos = 'eos'
  else:
    eos = ''
  if seg_type == 'foreign':
    if disamb:
      if rejected == '':
        dag_out.write(u"{}\t{}\t{}\t{}\t{}\t\t\t1.000\t\t{}\tdisamb\n".format(start, end, orth, orth, 'xxx', eos))
      else:
        dag_out.write(u"{}\t{}\t{}\t{}\t{}\t\t\t0.000\t\t{}\t\n".format(start, end, orth, orth, 'xxx', eos))
    else:
      dag_out.write(u"{}\t{}\t{}\t{}\t{}\t\t\t0.000\t\t\n".format(start, end, orth, orth, 'xxx'))
  else:
    if disamb:
      disamb_elems = morph_seg.xpath('./tei:fs/tei:f[@name="disamb"]/tei:fs[@type="tool_report"]/tei:f[@name="choice"]', namespaces = namespaces)
#      if len(disamb_elems) == 0:
#        print u"Brak ujednoznacznienia dla segmentu: {}".format(orth).encode("utf-8")
#        return
      if len(disamb_elems):
        disamb_ids = [elem.get('fVal')[1:] for elem in disamb_elems] # trzeba powinąć początkowy # w fVal
      else:
        disamb_ids = []
    for lex in morph_seg.xpath('./tei:fs/tei:f[@name="interps"]/tei:fs[@type="lex"]', namespaces = namespaces):
      base = lex.xpath('./tei:f[@name="base"]/tei:string', namespaces = namespaces)[0].text
      ctag = lex.xpath('./tei:f[@name="ctag"]/tei:symbol/@value', namespaces = namespaces)[0]
      msds = lex.xpath('./tei:f[@name="msd"]//tei:symbol', namespaces = namespaces)
      for m in msds:
        msd =  m.get('value')
        msd_id = m.get('{http://www.w3.org/XML/1998/namespace}id')
        msd = ctag + ':' + msd if msd else ctag
        dag_out.write(u"{}\t{}\t{}\t{}\t{}".format(start, end, orth, base, msd))
        if disamb:
          if msd_id in disamb_ids:
            dag_out.write(u"\t\t\t{0:.3f}\t\t{1}\tdisamb\n".format(1.0/len(disamb_elems), eos))
          else:
            dag_out.write(u"\t\t\t0.000\t\t{}\t\n".format(eos))
        else:
          dag_out.write(u"\t\t\t0.000\t\t\n")

def make_segdict(seglist):
  pts = []
  res = []
  for s in seglist:
    seg_corresp = s.get('corresp', '')
    seg_type = s.get('type', '')
    if seg_corresp:
      corresp_elem, corresp_pos, corresp_len = seg_corresp.split('(',1)[1].split(')',1)[0].split(',')
      res.append({'seg': s, 'corresp_elem': corresp_elem, 'corresp_pos': int(corresp_pos), 'corresp_len': corresp_len, 'seg_type': seg_type})
      pts.append(int(corresp_pos))
    else:
      res.append({'seg': s, 'corresp_elem': '', 'corresp_pos': 0, 'corresp_len': '', 'seg_type': seg_type})
      print u"Segment w choice bez correspa!!! corresp: {}".format(seg_corresp).encode("utf-8")
  return (res, pts)

# directory - folder z tekstem
# full_corp - True, jeśli eksportuję z pełnego korpusu (text_structure.xml) a nie próbki (text.xml)
# disamb - True, jeśli ma być do DAGa eksportowana informacja o wybranej interpretacji
def make_dag(directory, full_corp, disamb):
  dag_out = io.open(os.path.join(directory, 'text_transcr.txt.morph'), 'w', encoding='utf-8')
  seg_tree = etree.parse(os.path.join(directory, 'ann_segmentation.xml'))
  morph_tree = etree.parse(os.path.join(directory, 'ann_morphosyntax.xml'))
  morph_seg_list = morph_tree.xpath('/tei:teiCorpus/tei:TEI/tei:text/tei:body/tei:p/tei:s/tei:seg', namespaces = namespaces)
  ab_pattern = re.compile("txt_\d+.\d+")

  morph_index = 0
  start = 0
  
  last_ab = '0'
  ab_id = 0
  for para in seg_tree.xpath("//tei:p", namespaces=namespaces): # <p>: dla pełnego korpusu - akapit, dla próbki - próbka i trzeba znaleźć podział
    for sentence in para.xpath("./tei:s", namespaces=namespaces):
      last_in_sentence = False
      sentence_list = sentence.xpath("./*", namespaces=namespaces)
      sentence_len = len(sentence_list)
      for sent_id, seg_entry in enumerate(sentence_list, start = 1):
        if sent_id == sentence_len:
          last_in_sentence = True
          
        tag = tag_wo_ns(seg_entry)

        if tag == 'seg':
          i, morph_seg = find_morph(seg_entry.get('{http://www.w3.org/XML/1998/namespace}id'), morph_index, morph_seg_list)
          ab_corresp = seg_entry.get('corresp')
          seg_type = seg_entry.get('type', '')
          if not full_corp:
            if ab_corresp is not None: # Sprawdź, czy nie trzeba zacząć nowego akapitu
              ab_id = ab_pattern.search(ab_corresp).group(0)
              if ab_id != last_ab:
                if last_ab != '0':
                  dag_out.write(u"\n")
                  start = 0
          if len(morph_seg) and seg_type not in OMITLIST:
            print_interps(dag_out, start, start + 1, morph_seg[0], seg_type, '', disamb, last_in_sentence)
            start += 1
            if not full_corp and ab_corresp is not None:
              last_ab = ab_id
          morph_index = i
        elif tag == 'choice':
          # Stwórz listę wariantów
          variant_list = []
          points = []
          first_seg = seg_entry.xpath('.//tei:seg', namespaces=namespaces)[0]
          if first_seg.get('type', '') not in OMITLIST: # jeśli segment na OMITLIST, to w ogóle odrzucamy taki choice
            for var in seg_entry.iterchildren():
              if tag_wo_ns(var) == 'seg':
                if "-orig," in var.get('corresp', ''): # jeśli to pochodzi z korbowego choice i będzie odrzucone
                  continue
                else:
                  varlst, pts = make_segdict([var]) 
                  variant_list.append(varlst)
                  points.extend(pts)
              elif tag_wo_ns(var) == 'paren':
                if "-orig," in list(var)[0].get('corresp', ''): # jeśli to pochodzi z korbowego choice i będzie odrzucone
                  continue
                else:
                  varlst, pts = make_segdict(list(var)) 
                  variant_list.append(varlst)
                  points.extend(pts)
              elif tag_wo_ns(var) == 'choice':
                if "-orig," in var.xpath(".//tei:seg", namespaces=namespaces)[0].get('corresp', ''): # jeśli to pochodzi z korbowego choice i będzie odrzucone
                  continue
                else:
                  for elem_choice in var.iterchildren():
                    if tag_wo_ns(elem_choice) == 'seg':
                      varlst, pts = make_segdict([elem_choice]) 
                      variant_list.append(varlst)
                      points.extend(pts)
                    elif tag_wo_ns(elem_choice) == 'paren':
                      varlst, pts = make_segdict(list(elem_choice)) 
                      variant_list.append(varlst)
                      points.extend(pts)

          if variant_list:
            # Zbierz wszystkie różne początki z correspów i posortuj -
            # to będą kolejne węzły w DAG
            points = list(set(points))  # wyeliminuj powtórzenia
            points.sort()
            
            last_end = len(points)
            for v in variant_list:
              for seg_ind, seg_dict in enumerate(v):
                i, morph_seg = find_morph(seg_dict['seg'].get('{http://www.w3.org/XML/1998/namespace}id'), morph_index, morph_seg_list)
                if "-orig," in seg_dict['corresp_elem']: # poprawiona wersja z oryginalnego <choice> w tekście XML - nie będzie brana pod uwagę przez tager
                  continue
                if not full_corp:
                  if seg_dict['corresp_elem']: # Sprawdź, czy nie trzeba zacząć nowego akapitu
                    ab_id = ab_pattern.search(seg_dict['corresp_elem']).group(0)
                    if ab_id != last_ab:
                      if last_ab != '0':
                        dag_out.write(u"\n")
                      start = 0
                      v_start = 0
                      last_ab = ab_id
                if len(morph_seg) and seg_dict['seg_type'] not in OMITLIST: 
                  rejected = seg_dict['seg'].get('{http://www.nkjp.pl/ns/1.0}rejected', '')
                  if len(v) == seg_ind + 1: # ostatni element wariantu
                    print_interps(dag_out, start + points.index(seg_dict['corresp_pos']), start + last_end, morph_seg[0], seg_dict['seg_type'], rejected, disamb, last_in_sentence)
                  else:
                    print_interps(dag_out, start + points.index(seg_dict['corresp_pos']), start + points.index(v[seg_ind + 1]['corresp_pos']), morph_seg[0], seg_dict['seg_type'], rejected, disamb, False)
                morph_index = i
            start += last_end

    if full_corp and (start != 0):
      dag_out.write(u"\n")
      start = 0

  if not full_corp:
    dag_out.write(u"\n")
  dag_out.close()
  
'''
Stare warianty przed wprowadzeniem oznaczenia końca zdania
'''
# Przystosowanie do nowego formatu Concrafta - dodatkowe cztery kolumny (dwie przed prawdopodobieństwem i dwie po)
def old_print_interps(dag_out, start, end, morph_seg, seg_type, disamb):
  orth = morph_seg.xpath('./tei:fs/tei:f[@name="orth"]/tei:string', namespaces = namespaces)[0].text
  if seg_type == 'foreign':
    if disamb:
      dag_out.write(u"{}\t{}\t{}\t{}\t{}\t\t\t1.000\t\t\tdisamb\n".format(start, end, orth, orth, 'xxx'))
    else:
      dag_out.write(u"{}\t{}\t{}\t{}\t{}\t\t\t0.000\t\t\n".format(start, end, orth, orth, 'xxx'))
  else:
    if disamb:
      disamb_elems = morph_seg.xpath('./tei:fs/tei:f[@name="disamb"]/tei:fs[@type="tool_report"]/tei:f[@name="choice"]', namespaces = namespaces)
      if len(disamb_elems) == 0:
        print u"Brak ujednoznacznienia dla segmentu: {}".format(orth).encode("utf-8")
        return
      disamb_ids = [elem.get('fVal')[1:] for elem in disamb_elems] # trzeba powinąć początkowy # w fVal
    for lex in morph_seg.xpath('./tei:fs/tei:f[@name="interps"]/tei:fs[@type="lex"]', namespaces = namespaces):
      base = lex.xpath('./tei:f[@name="base"]/tei:string', namespaces = namespaces)[0].text
      ctag = lex.xpath('./tei:f[@name="ctag"]/tei:symbol/@value', namespaces = namespaces)[0]
      msds = lex.xpath('./tei:f[@name="msd"]//tei:symbol', namespaces = namespaces)
      for m in msds:
        msd =  m.get('value')
        msd_id = m.get('{http://www.w3.org/XML/1998/namespace}id')
        msd = ctag + ':' + msd if msd else ctag
        dag_out.write(u"{}\t{}\t{}\t{}\t{}".format(start, end, orth, base, msd))
        if disamb:
          if msd_id in disamb_ids:
            dag_out.write(u"\t\t\t{0:.3f}\t\t\tdisamb\n".format(1.0/len(disamb_elems)))
          else:
            dag_out.write(u"\t\t\t0.000\t\t\t\n")
        else:
          dag_out.write(u"\t\t\t0.000\t\t\n")

# directory - folder z tekstem
# full_corp - True, jeśli eksportuję z pełnego korpusu (text_structure.xml) a nie próbki (text.xml)
# disamb - True, jeśli ma być do DAGa eksportowana informacja o wybranej interpretacji
def old_make_dag(directory, full_corp, disamb):
  dag_out = io.open(os.path.join(directory, 'text_transcr.txt.old.morph'), 'w', encoding='utf-8')
  seg_tree = etree.parse(os.path.join(directory, 'ann_segmentation.xml'))
  morph_tree = etree.parse(os.path.join(directory, 'ann_morphosyntax.xml'))
  morph_seg_list = morph_tree.xpath('/tei:teiCorpus/tei:TEI/tei:text/tei:body/tei:p/tei:s/tei:seg', namespaces = namespaces)

  morph_index = 0
  start = 0
  
  last_ab = 0
  ab_id = 0
  for para in seg_tree.xpath("//tei:p", namespaces=namespaces): # <p>: dla pełnego korpusu - akapit, dla próbki - próbka i trzeba znaleźć podział
    for seg_entry in para.xpath("./tei:s/*", namespaces=namespaces):
      tag = tag_wo_ns(seg_entry)

      if tag == 'seg':
        i, morph_seg = find_morph(seg_entry.get('{http://www.w3.org/XML/1998/namespace}id'), morph_index, morph_seg_list)
        ab_corresp = seg_entry.get('corresp')
        seg_type = seg_entry.get('type', '')
        if not full_corp:
          if ab_corresp is not None: # Sprawdź, czy nie trzeba zacząć nowego akapitu
            ab_id = ab_corresp[26:].split('.', 1)[1].split('-', 1)[0]
            if ab_id != last_ab:
              if last_ab != 0:
                dag_out.write(u"\n")
                start = 0
        if len(morph_seg) and seg_type not in OMITLIST:
          old_print_interps(dag_out, start, start + 1, morph_seg[0], seg_type, disamb)
          start += 1
          if ab_id:
            last_ab = ab_id
        morph_index = i
      elif tag == 'choice':
        # Stwórz listę wariantów
        variant_list = []
        first_seg = seg_entry.xpath('.//tei:seg', namespaces=namespaces)[0]
        if first_seg.get('type', '') not in OMITLIST: # jeśli segment na OMITLIST, to w ogóle odrzucamy taki choice
          for var in seg_entry.iterchildren():
            if tag_wo_ns(var) == 'seg':
              if "-orig," in var.get('corresp', ''): # jeśli to pochodzi z korbowego choice i będzie odrzucone
                continue
              else:
                variant_list.append([var])
            elif tag_wo_ns(var) == 'paren':
              if "-orig," in list(var)[0].get('corresp', ''): # jeśli to pochodzi z korbowego choice i będzie odrzucone
                continue
              else:
                variant_list.append(list(var))
            elif tag_wo_ns(var) == 'choice':
              if "-orig," in var.xpath(".//tei:seg", namespaces=namespaces)[0].get('corresp', ''): # jeśli to pochodzi z korbowego choice i będzie odrzucone
                continue
              else:
                for elem_choice in var.iterchildren():
                  if tag_wo_ns(elem_choice) == 'seg':
                    variant_list.append([elem_choice])
                  elif tag_wo_ns(elem_choice) == 'paren':
                    variant_list.append(list(elem_choice))
        if variant_list:
          # Wylicz przesuniecie end ostatniego segmentu
          last_end = sum([len(v) - 1 for v in variant_list]) + 1
          v_end = start + 1
          for v in variant_list:
            v_start = start
            for seg_ind, seg in enumerate(v):
              i, morph_seg = find_morph(seg.get('{http://www.w3.org/XML/1998/namespace}id'), morph_index, morph_seg_list)
              ab_corresp = seg.get('corresp', '')
              if "-orig," in ab_corresp: # poprawiona wersja z oryginalnego <choice> w tekście XML - nie będzie brana pod uwagę przez tager
                continue
              seg_type = seg.get('type', '')
              if not full_corp:
                if ab_corresp: # Sprawdź, czy nie trzeba zacząć nowego akapitu
                  ab_id = ab_corresp[26:].split('.', 1)[1].split('-', 1)[0]
                  if ab_id != last_ab:
                    if last_ab != 0:
                      dag_out.write(u"\n")
                    start = 0
                    v_start = 0
                    v_end = 1
                    last_ab = ab_id
              if len(morph_seg) and seg_type not in OMITLIST: 
                if len(v) == seg_ind + 1:
                  old_print_interps(dag_out, v_start, start + last_end, morph_seg[0], seg_type, disamb)
                else:
                  old_print_interps(dag_out, v_start, v_end, morph_seg[0], seg_type, disamb)
                  v_start = v_end
                  v_end += 1
    #          else:
    #            print u"Segment w choice bez interpretacji!!! ab_corresp: {}, seg_type: {}".format(ab_corresp, seg_type).encode("utf-8")
              morph_index = i
          start += last_end

    if full_corp and (start != 0):
      dag_out.write(u"\n")
      start = 0

  if not full_corp:
    dag_out.write(u"\n")
  dag_out.close()


def insert_disamb(morph_seg, fVal, interp):
  fs_elem = morph_seg[0]
  new_f = etree.SubElement(fs_elem, '{http://www.tei-c.org/ns/1.0}f')
  new_f.set("name", "disamb")
  new_fs = etree.SubElement(new_f, '{http://www.tei-c.org/ns/1.0}fs')
  new_fs.set("type", "tool_report")
  new_f2 = etree.SubElement(new_fs, '{http://www.tei-c.org/ns/1.0}f')
  new_f2.set("name", "choice")
  new_f2.set("fVal", fVal)
  new_f3 = etree.SubElement(new_fs, '{http://www.tei-c.org/ns/1.0}f')
  new_f3.set("name", "interpretation")
  new_string = etree.SubElement(new_f3, '{http://www.tei-c.org/ns/1.0}string')
  new_string.text = interp
  
def process_seg(morph_seg, interp):
#  interp = seg_list[seg_list_id]['interpretation']
  if interp[0:2] == '::':  # uwaga na base = ':'
    interp_list = interp[2:].split(':', 1)
    interp_list.insert(0, ':')
  else:
    interp_list = interp.split(':', 2)  
  base = "&quot;" if interp_list[0] == '"' else interp_list[0]
  ctag = interp_list[1]
  msd = interp_list[2] if len(interp_list) > 2 else ''
  lex_list = morph_seg.xpath('./tei:fs/tei:f[@name="interps"]/tei:fs[@type="lex"][tei:f[@name="base"]/tei:string = "'+ base + '" and tei:f[@name="ctag"]/tei:symbol/@value="' + ctag + '"]', namespaces = namespaces)
  if len(lex_list):
    msd_list = lex_list[0].xpath('./tei:f[@name="msd"]//tei:symbol[@value="' + msd + '"]', namespaces=namespaces)
    fVal = "#" + msd_list[0].get('{http://www.w3.org/XML/1998/namespace}id') if len(msd_list) > 0 else ""
    insert_disamb(morph_seg, fVal, interp)
  else:
#    print u"Nie znalazłem base: {}, ctag: {} dla segmentu o id: {}".format(base, ctag, seg_entry.get('{http://www.w3.org/XML/1998/namespace}id')).encode('utf-8')
    insert_disamb(morph_seg, "", interp)

def insert_rejected(seg):
#  print u"rejected dla id: {}".format(seg.get('{http://www.w3.org/XML/1998/namespace}id')).encode('utf-8')
  seg.set('{http://www.nkjp.pl/ns/1.0}rejected', "true")
  
def tag_tei(directory):
  seg_list = read_text(os.path.join(directory, 'text_transcr.txt.morph.tagged'))
  parser = etree.XMLParser(remove_blank_text=True)
  seg_tree = etree.parse(os.path.join(directory, 'ann_segmentation.xml'), parser)
  morph_tree = etree.parse(os.path.join(directory, 'ann_morphosyntax.xml'), parser)
  morph_seg_list = morph_tree.xpath('/tei:teiCorpus/tei:TEI/tei:text/tei:body/tei:p/tei:s/tei:seg', namespaces = namespaces)

  morph_index = 0
  seg_list_id = 0

  for seg_entry in seg_tree.xpath("//tei:s/*", namespaces=namespaces):
    tag = tag_wo_ns(seg_entry)

    if tag == 'seg':
      if seg_entry.get('corresp'): # Jeśli segment nie ma "corresp", to nie będzie znakowany, więc go pomiń
        i, morph_seg = find_morph(seg_entry.get('{http://www.w3.org/XML/1998/namespace}id'), morph_index, morph_seg_list)
        
        if len(morph_seg):
          if morph_seg[0].xpath('./tei:fs/tei:f[@name="orth"]/tei:string', namespaces = namespaces)[0].text == seg_list[seg_list_id]['orth']:
            process_seg(morph_seg[0], seg_list[seg_list_id]['interpretation'])
            seg_list_id += 1
            morph_index = i
          else:
            print u"Niezgodność na segmencie o id: {}".format(seg_entry.get('{http://www.w3.org/XML/1998/namespace}id')).encode('utf-8')
            return
        else:
          print u"Brak opisu w morphosyntax dla segmentu o id: {}".format(seg_entry.get('{http://www.w3.org/XML/1998/namespace}id')).encode('utf-8')
      
    elif tag == 'choice':
      variant_found = False
      choice_list = [] # trzeba rozwinąć ewentualne choice'y powstałe z elementów <choice> w tekście
      for elem in list(seg_entry):
        if tag_wo_ns(elem) == 'choice':
          choice_list.extend(list(elem))
        else:
          choice_list.append(elem)
      for variant in choice_list:
        if tag_wo_ns(variant) == 'seg':
          if variant_found:
            insert_rejected(variant)
          elif "-orig," in variant.get('corresp'):
            insert_rejected(variant)
          else:
            i, morph_seg = find_morph(variant.get('{http://www.w3.org/XML/1998/namespace}id'), morph_index, morph_seg_list)
            if len(morph_seg):
              if morph_seg[0].xpath('./tei:fs/tei:f[@name="orth"]/tei:string', namespaces = namespaces)[0].text == seg_list[seg_list_id]['orth']:
                process_seg(morph_seg[0], seg_list[seg_list_id]['interpretation'])
                seg_list_id += 1
                morph_index = i
                variant_found = True
              else:
                insert_rejected(variant)
            else:
              print u"Brak opisu w morphosyntax dla segmentu z choice o id: {}".format(variant.get('{http://www.w3.org/XML/1998/namespace}id')).encode('utf-8')
              return
        elif tag_wo_ns(variant) == 'paren':
          if variant_found:
            for s in variant:
              insert_rejected(s)
          elif "-orig," in variant[0].get('corresp'):
            for s in variant:
              insert_rejected(s)
          else:
            i, morph_seg = find_morph(variant[0].get('{http://www.w3.org/XML/1998/namespace}id'), morph_index, morph_seg_list)
            if len(morph_seg):
              if morph_seg[0].xpath('./tei:fs/tei:f[@name="orth"]/tei:string', namespaces = namespaces)[0].text == seg_list[seg_list_id]['orth']:
                process_seg(morph_seg[0], seg_list[seg_list_id]['interpretation'])
                seg_list_id += 1
                morph_index = i
                variant_found = True
                for s in variant[1:]:
                  j, morph_seg = find_morph(s.get('{http://www.w3.org/XML/1998/namespace}id'), morph_index, morph_seg_list)
                  if len(morph_seg):
                    if morph_seg[0].xpath('./tei:fs/tei:f[@name="orth"]/tei:string', namespaces = namespaces)[0].text == seg_list[seg_list_id]['orth']:
                      process_seg(morph_seg[0], seg_list[seg_list_id]['interpretation'])
                      seg_list_id += 1
                      morph_index = j
                    else:
                      print u"Brak zgodności zapisu orth dla segmentu z choice o id: {}".format(s.get('{http://www.w3.org/XML/1998/namespace}id')).encode('utf-8')
                      return
                  else:
                    print u"Brak opisu w morphosyntax dla segmentu z choice o id: {}".format(s.get('{http://www.w3.org/XML/1998/namespace}id')).encode('utf-8')
                    return
              else:
                for s in variant:
                  insert_rejected(s)
            else:
              print u"Brak opisu w morphosyntax dla segmentu z choice o id: {}".format(variant.get('{http://www.w3.org/XML/1998/namespace}id')).encode('utf-8')
              return
        else:
          print u"Niewłaściwy tag: {} zamiast seg lub paren w choice".format(tag_wo_ns(variant)).encode('utf-8')
          return

    else:
      print u"Niewłaściwy tag: {} zamiast seg lub choice".format(tag).encode('utf-8')
      return

  seg_tree.write(os.path.join(directory, 'ann_segmentation.concraft.xml'), pretty_print=True, encoding='UTF-8', xml_declaration=True)
  morph_tree.write(os.path.join(directory, 'ann_morphosyntax.concraft.xml'), pretty_print=True, encoding='UTF-8', xml_declaration=True)

def check_duplicates(fname):
  seg_tree = etree.parse(fname)
  last_pos = -1
  last_elem = ''
  
  for seg_entry in seg_tree.xpath("//tei:p/tei:s/*", namespaces=namespaces):
    tag = tag_wo_ns(seg_entry)
    if tag == 'seg':
      corresp = seg_entry.get('corresp')
      if corresp:
        elem_name, elem_pos, elem_len = corresp.strip().split(',')
        if elem_name == last_elem and elem_pos == last_pos:
          print u'Powtórzony początek w pliku {}, corresp: {}'.format(fname, corresp)
        last_pos = elem_pos
        last_elem = elem_name
    else:
      elem_name = last_elem
      elem_pos = last_pos
      loc_elem = last_elem
      loc_pos = last_pos
      for var_entry in list(seg_entry):
        tag = tag_wo_ns(var_entry)
        if tag == 'seg':
          corresp = var_entry.get('corresp')
          if corresp:
            elem_name, elem_pos, elem_len = corresp.strip().split(',')
            if elem_name == loc_elem and elem_pos == loc_pos:
              print u'Powtórzony początek w pliku {}, corresp: {}'.format(fname, corresp)
            loc_pos = last_pos
            loc_elem = last_elem
        elif tag == 'paren':
          for par_entry in list(var_entry):
            corresp = par_entry.get('corresp')
            if corresp:
              elem_name, elem_pos, elem_len = corresp.strip().split(',')
              if elem_name == loc_elem and elem_pos == loc_pos:
                print u'Powtórzony początek w pliku {}, corresp: {}'.format(fname, corresp)
              loc_pos = elem_pos
              loc_elem = elem_name
          loc_pos = last_pos
          loc_elem = last_elem
        elif tag == 'choice':
          for entry in list(var_entry):
            tag = tag_wo_ns(entry)
            if tag == 'seg':
              corresp = entry.get('corresp')
              if corresp:
                elem_name, elem_pos, elem_len = corresp.strip().split(',')
                if elem_name == loc_elem and elem_pos == loc_pos:
                  print u'Powtórzony początek w pliku {}, corresp: {}'.format(fname, corresp)
                loc_pos = last_pos
                loc_elem = last_elem
            elif tag == 'paren':
              for par_entry in list(entry):
                corresp = par_entry.get('corresp')
                if corresp:
                  elem_name, elem_pos, elem_len = corresp.strip().split(',')
                  if elem_name == loc_elem and elem_pos == loc_pos:
                    print u'Powtórzony początek w pliku {}, corresp: {}'.format(fname, corresp)
                  loc_pos = elem_pos
                  loc_elem = elem_name
              loc_pos = last_pos
              loc_elem = last_elem
      last_pos = elem_pos
      last_elem = elem_name