import_data.py 29.1 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 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
#-*- coding:utf-8 -*-

import sqlite3
import datetime
from django.db import connection, transaction
from django.core.management.base import BaseCommand

from common.util import no_history
from dictionary.management.commands.create_classifications import \
    create_classifications
from dictionary.models import CrossReference, Ending, LexemeInflectionPattern, \
    Lexeme, PatternType, BaseFormLabel, CrossReferenceType, LexemeAssociation, \
    LexicalClass, PartOfSpeech, Pattern, Qualifier, Vocabulary, \
    LexemeAttribute, Gender, LexemeAttributeValue, ClassificationValue, \
    LexemeCV, LexemeAV, Variant, Classification, History

MINI_MODE = True # do debugowania
MINI_LEXEME_COUNT = 1000
MINI_LEXEME_QUERY = "SELECT %s FROM leksemy ORDER BY haslo COLLATE NOCASE LIMIT ?"

BATCH_SIZE = 5000

OTHER = u'skr'
DEFAULT_VOCAB = u'SGJP'

POS_TRANSLATION = {
    u'burk': u'fraz',
    u'qub': u'part',
}

COMMONNESS_TRANSLATION = {
    u'geogr.': u'geograficzna',
    u'ogranizacja': u'organizacja',
    u'instutycja': u'instytucja',
    u'tytuł.': u'tytuł',
}

ATTRS = {
    u'zwrotność': (
        (('v', 'ger', 'pact'), None),
        (
            (u'—', u''),
            (u'się', u'się'),
            (u'(się)', u'(się)'),
            (u'sobie', u'sobie'),
            (u'(sobie)', u'(sobie)'),
            (u'się/sobie', u'się/sobie'),
        ),
        ('haslosuf', lambda suf: suf.strip(' ?') or u'—'),
        'single',
    ),
    u'przechodniość': (
        (('v', 'pred'), None),
        (
            ('iT', u'nieprzechodni'),
            ('qT', u'quasi-przechodni'),
            ('T', u'przechodni'),
        ),
        ('przechodniosc', lambda x: x),
        'single',
    ),
    u'aspekt': (
        (('v', 'pred', 'ger', 'pact', 'ppas', 'appas'), None),
        (
            ('dk', u'dk'),
            ('ndk', u'ndk'),
            ('ndk/dk', u'ndk/dk'),
            ('dk/ndk', u'dk/ndk'),
            ('ndk/(dk)', u'ndk/(dk)'),
            ('dk/(ndk)', u'dk/(ndk)'),
        ),
        ('aspekt', lambda x: x),
        'single',
    ),
    u'właściwy': (
        (('v', 'pred'), None),
        (
            ('Q', u'niewłaściwy'),
            ('(Q)', u'właściwy/niewłaściwy'),
            ('', u'właściwy'),
        ),
        ('właściwy', lambda x: x),
        'single',
    ),
    u'depr': (
        (('subst', 'skrs'), 'm1'),
        (
            ('n', u'n'),
            ('d', u'd'),
            ('nd', u'nd'),
        ),
        ('depr', lambda x: x),
        'single',
    ),
    u'osoba': (
        (('ppron',), None),
        (
            ('', u''),
            ('pri', u''),
            ('sec', u''),
        ),
        ('charfl', lambda x: x),
        'single',
    ),
    u'forma złoż.': (
        (('adj', 'adjcom', 'pact', 'ppas', 'appas'), None),
        (
            ('obecna', u''),
            ('nieobecna', u''),
        ),
        ('charfl', lambda x: 'obecna' if x != '0-' else 'nieobecna'),
        'single',
    ),
    u'forma poprz.': (
        (('adj', 'adjcom', 'pact', 'ppas', 'appas'), None),
        (
            ('obecna', u''),
            ('nieobecna', u''),
        ),
        ('charfl', lambda x: 'obecna' if x == '3+' else 'nieobecna'),
        'single',
    ),
    u'przypadek': (
        (('prep',), None),
        (
            ('nom', u'M'),
            ('gen', u'D'),
            ('dat', u'C'),
            ('acc', u'B'),
            ('inst', u'N'),
            ('loc', u'Msc'),
        ),
        ('charfl', lambda x: x),
        'multi',
    ),
    u'dokładniej': (
        (('advndm', 'interj', 'fraz', 'comp', 'part', 'conj'), None),
        (
            (u'przysłówek', u''),
            (u'relator/przysłówek', u''),
            (u'zaimek przysłowny', u''),
            (u'przysłówek liczebnikowy', u''),
            (u'relator', u''),
            (u'człon frazeologizmu', u''),
            (u'człon nazwiska', u''),
            (u'człon nazwy', u''),
            (u'spójnik podrzędny związany', u''),
            (u'spójnik podrzędny', u''),
            (u'spójnik', u''),
            (u'spójnik równorzędny', u''),
            (u'spójnik (odpowiednik)', u''),
            (u'spójnik (odpowiednik \pim{póki})', u''),
            (u'spójnik lewy', u''),
            (u'wykrzyknik onomatopeiczny', u''),
            (u'wykrzyknik', u''),
            (u'wykrzyknik apelatywny', u''),
            (u'wykrzyknik parentetyczny', u''),
            (u'wykrzyknik parentetyczny (przerywnik)', u''),
            (u'prefiks', u''),
            (u'przyimek', u''),
            (u'modyfikator deklaratywności', u''),
            (u'partykuła', u''),
            (u'operator trybu', u''),
            (u'dopowiedzenie', u''),
            (u'operator adnumeratywny', u''),
            (u'operator adsubstantywny', u''),
        ),
        ('dokładniej', lambda x: x),
        'single',
    ),
}

TEXT_ATTRS = {
    u'rzeczownik': (
        ('adj', 'adv'),
        'rzeczownik',
    ),
}

BASIC_FORM_LABELS = {
    'f': 'sg:nom',
    'm1': 'sg:nom',
    'm2': 'sg:nom',
    'm3': 'sg:nom',
    'n1': 'sg:nom',
    'n2': 'sg:nom',
    'p1': 'pl:nom:mo',
    'p2': 'pl:nom',
    'p3': 'pl:nom',
}

CSS_CLASS_TRANSLATION = {
    'h': 'header',
    'c': 'header-c',
    'b': 'blank',
    'd': 'data',
}


class Command(BaseCommand):
    args = '<input db filename>'
    help = 'Imports initial data'

    def handle(self, db_name, **options):
        ImportData(db_name).delete_and_import()


def get_cursor(db):
    conn = sqlite3.connect(db)
    conn.row_factory = sqlite3.Row
    return conn.cursor()


def bulk_create(model, objects):
    model.objects.bulk_create(objects, batch_size=BATCH_SIZE)


METHOD_NAMES = {
    CrossReference: 'import_cross_references',
    Ending: 'import_endings',
    LexemeInflectionPattern: 'import_lexeme_inflection_patterns',
    Lexeme: 'import_lexemes',
    PatternType: 'import_pattern_types',
    BaseFormLabel: 'new_base_form_labels',
    CrossReferenceType: 'new_cross_reference_types',
    Gender: 'new_genders',
    LexemeAssociation: 'new_lexeme_associations',
    LexicalClass: 'new_lexical_classes',
    PartOfSpeech: 'new_parts_of_speech',
    Pattern: 'new_patterns',
    Qualifier: 'new_qualifiers',
    Vocabulary: 'new_vocabularies',
}


class ImportData(object):
    def __init__(self, db):
        transaction.commit_unless_managed()
        transaction.enter_transaction_management()
        transaction.managed()
        self.cursor = connection.cursor()
        self.sqlite_cursor = get_cursor(db)
        no_history()

    def close(self):
        self.cursor.close()
        self.sqlite_cursor.close()
        transaction.commit()
        transaction.leave_transaction_management()


    def new_lexical_classes(self):
        for row in self.sqlite_cursor.execute('select distinct pos from wzory'):
            if not LexicalClass.objects.filter(symbol=row['pos']).exists():
                yield LexicalClass(symbol=row['pos'])

    def cache_lc(self):
        if 'lc' not in self.__dict__:
            self.lc = dict((lc.symbol, lc) for lc in LexicalClass.objects.all())

    def translate_pos(self, pos):
        return POS_TRANSLATION.get(pos, pos)

    def new_parts_of_speech(self):
        lcs = {}
        for row in self.sqlite_cursor.execute(
                'select distinct wzory.pos, leksemy.pos from wzory '
                'natural join odmieniasie '
                'join leksemy on leksemy.nr = odmieniasie.nr'):
            lcs[row[1]] = row[0]

        for row in self.sqlite_cursor.execute('SELECT * FROM klasygramatyczne'):
            pos = self.translate_pos(row['pos'])
            if not PartOfSpeech.objects.filter(symbol=pos).exists():
                lc = lcs.get(pos, OTHER)
                yield PartOfSpeech(
                    symbol=pos,
                    full_name=row['nazwakl'],
                    index=row['klporz'],
                    color_scheme=row['posind'],
                    lexical_class_id=lc)

    def cache_pos(self):
        if 'pos' not in self.__dict__:
            self.pos = dict(
                (pos.symbol, pos) for pos in PartOfSpeech.objects.all())

    def cache_lc_pos(self):
        if 'lc_pos' not in self.__dict__:
            self.lc_pos = dict(
                (pos.symbol, pos.lexical_class) for pos in
                    PartOfSpeech.objects.all()
            )

    def new_base_form_labels(self):
        self.cache_lc_pos()
        query_result = self.sqlite_cursor.execute("""
            SELECT efobaz, pos FROM paradygmaty
        """)
        for row in query_result:
            yield BaseFormLabel(
                symbol=row[0], lexical_class=self.lc_pos[row[1]])
        query_result = self.sqlite_cursor.execute("""
            SELECT z.efobaz, w.pos FROM zakonczenia z
                JOIN wzory w ON z.wzor = wzory.wzor
        """)
        for row in query_result:
            yield BaseFormLabel(symbol=row[0], lexical_class_id=row[1])

    def cache_bfl(self):
        if 'bfls' not in self.__dict__:
            self.bfls = dict(
                ((bfl.symbol, bfl.lexical_class_id), bfl)
                    for bfl in BaseFormLabel.objects.all())

    def new_genders(self):
        result = self.sqlite_cursor.execute('''
            SELECT DISTINCT charfl FROM paradygmaty WHERE pos = 'subst'
        ''')
        for row in result:
            bfl_symbol = BASIC_FORM_LABELS[row['charfl']]
            bfl = BaseFormLabel.objects.get(
                symbol=bfl_symbol, lexical_class_id='subst')
            yield Gender(
                symbol=row['charfl'], basic_form_label=bfl)

    def cache_genders(self):
        if 'genders' not in self.__dict__:
            self.genders = dict(
                (gender.symbol, gender) for gender in Gender.objects.all()
            )

    def new_vocabularies(self):
        self.cache_vocabs()
        result = self.sqlite_cursor.execute("""
            SELECT slownik FROM leksemy
            UNION
            SELECT slownik_uz FROM slowniki_uzywajace
        """)
        for row in result:
            if row[0] not in self.vocabs:
                yield Vocabulary(id=row[0])

    def cache_vocabs(self):
        if 'vocabs' not in self.__dict__:
            self.vocabs = dict((v.id, v) for v in Vocabulary.objects.all())

    def new_qualifiers(self):
        styl_query = self.sqlite_cursor.execute("""
            select okwal from odmieniasie
            UNION
            SELECT zkwal from zakonczenia
            UNION
            SELECT kwalstyl FROM leksemy WHERE pos = 'subst'
        """)
        styl_quals = set()
        for row in styl_query:
            if row[0] != '' and row[0] is not None:
                for label in row[0].split(', '):
                    styl_quals.add(label)
        query_result = self.sqlite_cursor.execute("""
            SELECT okwal FROM odmieniasie
            UNION
            SELECT zkwal FROM zakonczenia
            UNION
            SELECT kwalzakr FROM leksemy
            UNION
            SELECT kwalstyl FROM leksemy
        """)
        added = set()
        for row in query_result:
            if row[0]:
                for qualifier_label in row[0].split(', '):
                    if qualifier_label not in added:
                        added.add(qualifier_label)
                        if qualifier_label in styl_quals:
                            type = Qualifier.TYPE_STYLE
                        else:
                            type = Qualifier.TYPE_SCOPE
                        yield Qualifier(label=qualifier_label, type=type,
                            vocabulary_id=DEFAULT_VOCAB)

    def cache_qualifiers(self):
        if 'qual' not in self.__dict__:
            self.qual = dict((q.label, q) for q in Qualifier.objects.all())

    def create_attributes(self):
        attr_values = {}
        text_attrs = {}
        for attr_name, attr_data in ATTRS.iteritems():
            (poses, gender), values, import_info, card = attr_data
            la, created = LexemeAttribute.objects.get_or_create(
                name=attr_name, closed=True, required=True,
                takes_gender=bool(gender), multiple=(card == 'multi'))
            for pos in PartOfSpeech.objects.filter(symbol__in=poses):
                la.parts_of_speech.add(pos) #add
            if gender:
                la.genders.add(Gender.objects.get(symbol=gender)) #add
            values_cache = {}
            for val, display_val in values:
                values_cache[val], created = \
                    LexemeAttributeValue.objects.get_or_create(
                        value=val, display_value=display_val, attribute=la)
            attr_values[attr_name] = values_cache
        for attr_name, attr_data in TEXT_ATTRS.iteritems():
            poses, column = attr_data
            la, created = LexemeAttribute.objects.get_or_create(
                name=attr_name, closed=False)
            for pos in poses:
                la.parts_of_speech.add(pos)
            text_attrs[attr_name] = la
            attr_values[attr_name] = dict((v.value, v) for v in la.values.all())
        return attr_values, text_attrs

    def new_lexemes(self):
        self.cache_qualifiers()
        if MINI_MODE:
            result = self.sqlite_cursor.execute(
                MINI_LEXEME_QUERY % '*', (MINI_LEXEME_COUNT,))
        else:
            result = self.sqlite_cursor.execute('SELECT * FROM leksemy')
        attr_values, text_attrs = self.create_attributes()
        date = datetime.datetime.now()
        create_classifications()
        Classification.objects.get(name=u'pospolitość').vocabularies.add(
            DEFAULT_VOCAB)
        cv_table = dict(
            (cv.label, cv) for cv in ClassificationValue.objects.all())
        lexemes = []
        lexeme_associations = []
        lexeme_qualifiers = []
        lexeme_cvs = []
        lexeme_attrs = []
        cursor2 = self.sqlite_cursor.connection.cursor()
        for row in result:
            pos = self.translate_pos(row['pos'])
            slownik = row['slownik']
            if slownik != 'zmiotki':
                status = Lexeme.STATUS_CONFIRMED
            else:
                status = Lexeme.STATUS_CANDIDATE
            if row['typnazwy']:
                comms = row['typnazwy'].split(' a. ')
            else:
                comms = [row['pospolitosc']]
            cvs = [
                cv_table.get(COMMONNESS_TRANSLATION.get(comm, comm))
                for comm in comms if comm]
            lexemes.append(Lexeme(
                id=row['nr'],
                entry=row['haslo'],
                source_id=row['srcid'],
                entry_suffix=row['haslosuf'] or '', # pozostałość historyczna
                gloss=row['glosa'] or '',
                note=row['nota'] or '',
                pronunciation=row['wymowa'] or '',
                valence=row['łączliwość'] or '',
                part_of_speech_id=pos,
                source=row['źródło'] or '',
                status=status,
                comment=row['komentarz'] or '',
                last_modified=date,
                owner_vocabulary_id=slownik,
                qualifiers_dor=row['dorkwal'] or '',
                # tymczasowe:
                qualifiers_style=row['kwalstyl'] or '',
                qualifiers_scope=row['kwalzakr'] or '',
            ))
            lexeme_associations.append(LexemeAssociation(
                lexeme_id=row['nr'], vocabulary_id=slownik))
            for cv in cvs:
                lexeme_cvs.append(
                    LexemeCV(lexeme_id=row['nr'], classification_value=cv))
            for kwal in (row['kwalstyl'], row['kwalzakr']):
                if kwal:
                    for qual in kwal.split(', '):
                        lexeme_qualifiers.append((row['nr'], self.qual[qual]))
            for attr_name, attr_data in ATTRS.iteritems():
                (poses, gender), values, (column, f), card = attr_data
                if pos in poses:
                    if column == 'charfl':
                        cursor2.execute('''
                            select charfl from odmieniasie where nr = ?
                        ''', (row['nr'],))
                        if card == 'multi':
                            data = [r[0] for r in cursor2]
                        else:
                            data = [cursor2.fetchone()[0]]
                    else:
                        data = [row[column]]
                    for data_item in data:
                        attr_value = attr_values[attr_name].get(f(data_item))
                        if attr_value:
                            lexeme_attrs.append(LexemeAV(
                                lexeme_id=row['nr'],
                                attribute_value=attr_value))
                        elif data_item:
                            print 'unknown value of %s: %s' % (
                                attr_name, row[column])
            for attr_name, attr_data in TEXT_ATTRS.iteritems():
                poses, column = attr_data
                if pos in poses:
                    data = row[column] or ''
                    attr = text_attrs[attr_name]
                    attr_val = attr_values[attr_name].get(data)
                    if not attr_val:
                        attr_val = LexemeAttributeValue.objects.create(
                            attribute=attr, value=data)
                        attr_values[attr_name][data] = attr_val
                    lexeme_attrs.append(LexemeAV(
                        lexeme_id=row['nr'], attribute_value=attr_val))
        return (
            lexemes, lexeme_associations, lexeme_cvs, lexeme_qualifiers,
            lexeme_attrs)

    def new_lexeme_associations(self):
        self.cache_vocabs()
        if MINI_MODE:
            result = self.sqlite_cursor.execute(
                'SELECT * FROM slowniki_uzywajace WHERE nr in (%s)'
                % (MINI_LEXEME_QUERY % 'nr'), [MINI_LEXEME_COUNT])
        else:
            result = self.sqlite_cursor.execute(
                'SELECT * FROM slowniki_uzywajace')
        for row in result:
            yield LexemeAssociation(
                vocabulary=self.vocabs[row['slownik_uz']], lexeme_id=row['nr'])

    CR_DESC = {
        ('verppas', 'appas'): u'quasi-imiesłów bierny',
        ('adjnie', 'appas'): u'„zanegowany” quasi-imiesłów bierny',
        ('adjnie', 'adv'): u'przysłówek „zanegowany”',
        ('adjnie', 'osc'): u'„zanegowana” nazwa cechy',
        ('nieadj', 'appas'): u'quasi-imiesłów bierny bez „nie-”',
        ('nieadj', 'adv'): u'przysłówek bez „nie-”',
        ('nieadj', 'osc'): u'nazwa cechy bez „nie-”',
    }

    def new_cross_reference_types(self):
        result = self.sqlite_cursor.execute(
            'select distinct l1.pos pos1, l2.pos pos2, t.* '
            'from odsylacze o join leksemy l1 on nrod=l1.nr '
            'join leksemy l2 on nrdo=l2.nr '
            'join typyodsylaczy t on t.typods=o.typods')
        for row in result:
            desc = self.CR_DESC.get((row['typods'], row['pos2']),
                row['naglowek'])
            yield CrossReferenceType(
                symbol=row['typods'],
                desc=desc,
                index=row['kolejnosc'],
                from_pos=PartOfSpeech.objects.get(symbol=row['pos1']),
                to_pos=PartOfSpeech.objects.get(symbol=row['pos2']),
            )

    def new_cross_references(self):
        if MINI_MODE:
            result = self.sqlite_cursor.execute(
                'SELECT o.*, l1.pos pos1, l2.pos pos2 FROM odsylacze o '
                'JOIN leksemy l1 on nrod=l1.nr '
                'JOIN leksemy l2 on nrdo=l2.nr '
                'WHERE nrod in (%(subq)s) and nrdo in (%(subq)s)'
                % {'subq': MINI_LEXEME_QUERY % 'nr'},
                [MINI_LEXEME_COUNT, MINI_LEXEME_COUNT])
        else:
            result = self.sqlite_cursor.execute(
                'SELECT o.*, l1.pos pos1, l2.pos pos2 FROM odsylacze o '
                'JOIN leksemy l1 on nrod=l1.nr '
                'JOIN leksemy l2 on nrdo=l2.nr'
            )
        cr_type_table = dict(
            ((crt.symbol, crt.from_pos.symbol, crt.to_pos.symbol), crt)
                for crt in CrossReferenceType.objects.all()
        )
        for row in result:
            # POMIJANIE niekompletne odsyłacze zdarzają się dla 'asp'
            if row['nrod'] and row['nrdo']:
                cr_type = cr_type_table[
                    (row['typods'], row['pos1'], row['pos2'])]
                yield CrossReference(
                    from_lexeme_id=row['nrod'], to_lexeme_id=row['nrdo'],
                    type=cr_type)

    def copy_aspects(self):
        aspect_vals = dict(LexemeAttributeValue.objects.filter(
            attribute__name='aspekt').values_list('value', 'pk'))
        if MINI_MODE:
            result = self.sqlite_cursor.execute(
                "select distinct nrdo, aspekt "
                "from odsylacze o "
                "join leksemy l on o.nrod = l.nr "
                "where typods in ('verger', 'verppas', 'verpact') "
                "and nrod in (%(subq)s) and nrdo in (%(subq)s)"
                % {'subq': MINI_LEXEME_QUERY % 'nr'},
                [MINI_LEXEME_COUNT, MINI_LEXEME_COUNT])
        else:
            result = self.sqlite_cursor.execute(
                "select distinct nrdo, aspekt "
                "from odsylacze o "
                "join leksemy l on o.nrod = l.nr "
                "where typods in ('verger', 'verppas', 'verpact')")
        for row in result:
            yield LexemeAV(
                lexeme_id=row['nrdo'],
                attribute_value_id=aspect_vals[row['aspekt']])

    def import_pattern_types(self):
        self.cache_lc_pos()
        result = self.sqlite_cursor.execute(
            'SELECT DISTINCT typr, pos FROM paradygmaty')
        for row in result:
            lc = self.lc_pos[self.translate_pos(row['pos'])]
            PatternType.objects.get_or_create(lexical_class=lc,
                symbol=row['typr'])
            # prowizorka z powodu pustej klasy 'skr'
        self.cache_lc()
        result = self.sqlite_cursor.execute(
            'SELECT DISTINCT typr, pos FROM wzory')
        for row in result:
            lc = self.lc[row['pos']]
            PatternType.objects.get_or_create(lexical_class=lc,
                symbol=row['typr'])

    def cache_ptypes(self):
        if 'ptypes' not in self.__dict__:
            self.ptypes = dict(
                ((pt.lexical_class.symbol, pt.symbol), pt)
                    for pt in PatternType.objects.all()
            )

    def new_patterns(self):
        self.cache_ptypes()
        for row in self.sqlite_cursor.execute('SELECT * FROM wzory'):
            yield Pattern(
                name=row['wzor'],
                type=self.ptypes[(row['pos'], row['typr'])],
                basic_form_ending=row['zakp'],
                example=row['przyklad'] or '',
                comment=row['wkomentarz'] or '',
                status='temp',
            )

    def cache_patterns(self):
        if 'paterns' not in self.__dict__:
            self.patterns = dict((p.name, p) for p in Pattern.objects.all())

    def new_endings(self):
        self.cache_qualifiers()
        self.cache_patterns()
        self.cache_bfl()
        endings = []
        ending_quals = []
        query = self.sqlite_cursor.execute('''
            SELECT z.*, w.pos FROM zakonczenia z
                JOIN wzory w ON z.wzor = wzory.wzor
        ''')
        for row in query:
            # POMIJANIE
            if row['zak'] is not None:
                endings.append(Ending(
                    pattern=self.patterns[row['wzor']],
                    base_form_label=self.bfls[(row['efobaz'], row['pos'])],
                    string=row['zak'],
                    index=row['nrskl'],
                ))
                if row['zkwal']:
                    for qual in row['zkwal'].split(', '):
                        ending_quals.append((
                            self.patterns[row['wzor']],
                            self.bfls[row['efobaz']],
                            row['nrskl'],
                            self.qual[qual]))
        return endings, ending_quals

    def new_lexeme_inflection_patterns(self):
        self.cache_genders()
        self.cache_qualifiers()
        self.cache_patterns()
        if MINI_MODE:
            result = self.sqlite_cursor.execute(
                'SELECT o.*, l.pos FROM odmieniasie o '
                'JOIN leksemy l ON o.nr = l.nr '
                'WHERE l.nr IN (%s)' % (MINI_LEXEME_QUERY % 'nr'),
                (MINI_LEXEME_COUNT,))
        else:
            result = self.sqlite_cursor.execute(
                'SELECT * FROM odmieniasie o JOIN leksemy l ON o.nr = l.nr')
        lips = []
        lip_quals = []
        for row in result:
            lexeme_id = row['nr']
            # POMIJANIE
            if row['wzor'] in self.patterns: # wzór D w zmiotkach
                lips.append(LexemeInflectionPattern(
                    lexeme_id=lexeme_id,
                    index=row['oskl'],
                    pattern=self.patterns[row['wzor']],
                    gender = self.genders.get(row['charfl']),
                    root=row['rdzen'],
                ))
            if row['okwal']:
                for qual in row['okwal'].split(', '):
                    lip_quals.append((lexeme_id, row['oskl'], self.qual[qual]))
        return lips, lip_quals

    def new_variants(self):
        result = self.sqlite_cursor.execute(
            'SELECT DISTINCT wariant FROM paradygmaty')
        for row in result:
            v_type = 'table' if str(row['wariant']) in '01' else 'export'
            yield Variant(id=row['wariant'], type=v_type)

    def delete_and_import(self):
        models = (
            Variant,
            CrossReference,
            CrossReferenceType,
            LexemeAssociation,
            LexemeInflectionPattern,
            Lexeme,
            Ending,
            Pattern,
            PatternType,
            Qualifier,
            #Vocabulary,
            BaseFormLabel,
            #PartOfSpeech,
            #LexicalClass,
            LexemeAttribute,
            History,
        )
        print 'deleting old data...'
        for model in models:
            self.cursor.execute(
                'truncate table %s cascade' % model._meta.db_table)

        print 'importing lexical classes...'
        bulk_create(LexicalClass, self.new_lexical_classes())
        print 'importing parts of speech...'
        bulk_create(PartOfSpeech, self.new_parts_of_speech())
        print 'importing base form labels...'
        bulk_create(BaseFormLabel, self.new_base_form_labels())
        print 'importing genders...'
        bulk_create(Gender, self.new_genders())
        print 'importing vocabularies...'
        for v in self.new_vocabularies():
            v.save()
        print 'importing qualifiers...'
        bulk_create(Qualifier, self.new_qualifiers())
        print 'importing pattern types...'
        self.import_pattern_types()
        print 'importing patterns...'
        bulk_create(Pattern, self.new_patterns())
        print 'importing endings...'
        endings, ending_quals = self.new_endings()
        bulk_create(Ending, endings)
        for pattern, bfl, index, q in ending_quals:
            Ending.objects.get(
                pattern=pattern, base_form_label=bfl,
                index=index).qualifiers.add(q)

        def import_lexemes():
            print 'importing lexemes...'
            (lexemes, lexeme_assoc, lexeme_cvs, lexeme_quals,
            lexeme_attrs) = self.new_lexemes()
            print 'creating...'
            bulk_create(Lexeme, lexemes)
            print 'associations...'
            bulk_create(LexemeAssociation, lexeme_assoc)
            print 'classifications...'
            bulk_create(LexemeCV, lexeme_cvs)
            print 'qualifiers...'
            for lexeme_id, q in lexeme_quals:
                q.lexeme_set.add(lexeme_id) #add
            print 'attributes...'
            bulk_create(LexemeAV, lexeme_attrs)

        import_lexemes()

        def import_lips():
            print 'importing lexeme inflection patterns...'
            lips, lip_quals = self.new_lexeme_inflection_patterns()
            print 'creating...'
            bulk_create(LexemeInflectionPattern, lips)
            print 'qualifiers...'
            for lexeme_id, index, q in lip_quals:
                LexemeInflectionPattern.objects.get(
                    lexeme_id=lexeme_id, index=index).qualifiers.add(q)

        import_lips()
        print 'importing lexeme associations...'
        bulk_create(LexemeAssociation, self.new_lexeme_associations())
        print 'importing cross-reference types...'
        bulk_create(CrossReferenceType,
            self.new_cross_reference_types())
        print 'importing cross-references...'
        bulk_create(CrossReference, self.new_cross_references())
        print 'copying aspect values to derived lexemes...'
        bulk_create(LexemeAV, self.copy_aspects())
        print 'importing variants...'
        bulk_create(Variant, self.new_variants())
        print 'committing to database...'
        self.close()
        print 'now you may want to import templates, create forms, cache qualifiers'

    def single_import(self, model):
        method_name = METHOD_NAMES[model]
        if method_name.startswith('new'):
            bulk_create(model, self.__getattribute__(method_name)())
        elif method_name.startswith('import'):
            self.__getattribute__(method_name)()
        self.close()