1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
7 from cPickle import load, dump
8 from optparse import make_option
10 from django.core.management.base import BaseCommand
11 from django.core.management.color import color_style
12 from django.conf import settings
14 from catalogue.models import Book, Tag
16 # extract text from text file
17 re_text = re.compile(r'\n{3,}(.*?)\n*-----\n', re.S).search
20 class Command(BaseCommand):
21 option_list = BaseCommand.option_list + (
22 make_option('-t', '--tags', dest='tags', metavar='SLUG,...',
23 help='Use only books tagged with this tags'),
24 make_option('-i', '--include', dest='include', metavar='SLUG,...',
25 help='Include specific books by slug'),
26 make_option('-e', '--exclude', dest='exclude', metavar='SLUG,...',
27 help='Exclude specific books by slug')
29 help = 'Prepare data for Lesmianator.'
31 def handle(self, *args, **options):
32 self.style = color_style()
33 verbose = int(options.get('verbosity'))
34 tags = options.get('tags')
35 include = options.get('include')
36 exclude = options.get('exclude')
39 path = settings.LESMIANATOR_PICKLE
41 print self.style.ERROR('LESMIANATOR_PICKLE not set in the settings.')
47 books += list(Book.objects.filter(slug__in=include.split(',')).only('slug', 'txt_file'))
50 books += list(Book.tagged.with_all(Tag.objects.filter(slug__in=tags.split(','))).only('slug', 'txt_file'))
52 books = list(Book.objects.all().only('slug', 'txt_file'))
55 books = [book for book in books if book.slug not in exclude.split(',')]
60 processed = skipped = 0
63 print 'Parsing', book.slug
66 print self.style.NOTICE('%s has no TXT file' % book.slug)
69 f = open(book.txt_file.path)
72 print self.style.ERROR("Unknown text format: %s" % book.slug)
78 text = unicode(m.group(1), 'utf-8').lower()
80 mydict = lesmianator.setdefault(last_word, {})
81 myval = mydict.setdefault(letter, 0)
83 last_word = last_word[-2:] + letter
88 print self.style.ERROR("No books with TXT files found")
90 print self.style.ERROR("No books found")
94 dump(lesmianator, open(path, 'w'))
96 print self.style.ERROR("Couldn't write to $s" % path)
99 dump(lesmianator, open(path, 'w'))
101 print "%d processed, %d skipped" % (processed, skipped)
102 print "Results dumped to %s" % path