export_patterns.py 1.75 KB
# -*- coding: utf-8 -*-
import os.path
import codecs

from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.core.management.base import BaseCommand

from dictionary.models import Inflection
from patterns.models import Pattern
from patterns.util import get_detailed_counts


def new_file(name):
    return codecs.open(os.path.join(settings.BASE_DIR, name), 'w', 'utf-8')


class Command(BaseCommand):
    help = "Export pattern data."

    def handle(self, **options):
        user = AnonymousUser()
        patterns_file = new_file('wzory.txt')
        detailed_file = new_file('rodzaje.txt')
        endings_file = new_file('zakonczenia.txt')
        for p in Pattern.objects.all():
            name = p.name
            infl_type = p.type.inflection_type_id
            ptype = p.type.symbol
            inflections = Inflection.filter_visible(p.inflection_set, user)
            lexeme_count = Inflection.lexeme_count(inflections)
            print >>patterns_file, '\t'.join((
                name, infl_type, ptype, str(lexeme_count)))
            for symbol, count, example in get_detailed_counts(p, inflections):
                print >>detailed_file, '\t'.join((
                    name, symbol, str(count), example[0].entry))
            endings = p.endings.select_related('base_form_label')
            endings = endings.prefetch_related('qualifiers')
            for ending in endings:
                print >>endings_file, '\t'.join((
                    name,
                    ending.base_form_label.symbol,
                    ending.string,
                    '|'.join(ending.qualifiers.values_list('label', flat=True))
                ))
        patterns_file.close()
        detailed_file.close()
        endings_file.close()