Thema metadata support, and fixes.
[redakcja.git] / src / catalogue / models.py
1 from collections import Counter
2 from datetime import date, timedelta
3 import decimal
4 import re
5 from urllib.request import urlopen
6 from django.apps import apps
7 from django.conf import settings
8 from django.db import models
9 from django.template.loader import render_to_string
10 from django.urls import reverse
11 from django.utils.translation import gettext_lazy as _
12 from admin_ordering.models import OrderableModel
13 from wikidata.client import Client
14 from .constants import WIKIDATA
15 from .wikidata import WikidataModel
16 from .wikimedia import WikiMedia
17
18
19 class Author(WikidataModel):
20     slug = models.SlugField(max_length=255, null=True, blank=True, unique=True)
21     first_name = models.CharField(_("first name"), max_length=255, blank=True)
22     last_name = models.CharField(_("last name"), max_length=255, blank=True)
23     genitive = models.CharField(
24         'dopełniacz', max_length=255, blank=True,
25         help_text='utwory … (czyje?)'
26     )
27
28     name_de = models.CharField(_("name (de)"), max_length=255, blank=True)
29     name_lt = models.CharField(_("name (lt)"), max_length=255, blank=True)
30
31     gender = models.CharField(_("gender"), max_length=255, blank=True)
32     nationality = models.CharField(_("nationality"), max_length=255, blank=True)
33
34     year_of_birth = models.SmallIntegerField(_("year of birth"), null=True, blank=True)
35     year_of_birth_inexact = models.BooleanField(_("inexact"), default=False)
36     year_of_birth_range = models.SmallIntegerField(_("year of birth, range end"), null=True, blank=True)
37     date_of_birth = models.DateField(_("date_of_birth"), null=True, blank=True)
38     century_of_birth = models.SmallIntegerField(
39         _("century of birth"), null=True, blank=True,
40         help_text=_('Set if year unknown. Negative for BC.')
41     )
42     place_of_birth = models.ForeignKey(
43         'Place', models.PROTECT, null=True, blank=True,
44         verbose_name=_('place of birth'),
45         related_name='authors_born'
46     )
47     year_of_death = models.SmallIntegerField(_("year of death"), null=True, blank=True)
48     year_of_death_inexact = models.BooleanField(_("inexact"), default=False)
49     year_of_death_range = models.SmallIntegerField(_("year of death, range end"), null=True, blank=True)
50     date_of_death = models.DateField(_("date_of_death"), null=True, blank=True)
51     century_of_death = models.SmallIntegerField(
52         _("century of death"), null=True, blank=True,
53         help_text=_('Set if year unknown. Negative for BC.')
54     )
55     place_of_death = models.ForeignKey(
56         'Place', models.PROTECT, null=True, blank=True,
57         verbose_name=_('place of death'),
58         related_name='authors_died'
59     )
60     status = models.PositiveSmallIntegerField(
61         _("status"), 
62         null=True,
63         blank=True,
64         choices=[
65             (1, _("Alive")),
66             (2, _("Dead")),
67             (3, _("Long dead")),
68             (4, _("Unknown")),
69         ],
70     )
71     notes = models.TextField(_("notes"), blank=True, help_text=_('private'))
72
73     gazeta_link = models.CharField(_("gazeta link"), max_length=255, blank=True)
74     culturepl_link = models.CharField(_("culture.pl link"), max_length=255, blank=True)
75     plwiki = models.CharField(blank=True, max_length=255)
76     photo = models.ImageField(blank=True, null=True, upload_to='catalogue/author/')
77     photo_source = models.CharField(blank=True, max_length=255)
78     photo_attribution = models.CharField(max_length=255, blank=True)
79
80     description = models.TextField(_("description"), blank=True, help_text=_('for publication'))
81
82     priority = models.PositiveSmallIntegerField(
83         _("priority"), 
84         default=0, choices=[(0, _("Low")), (1, _("Medium")), (2, _("High"))]
85     )
86     collections = models.ManyToManyField("Collection", blank=True, verbose_name=_("collections"))
87
88     class Meta:
89         verbose_name = _('author')
90         verbose_name_plural = _('authors')
91         ordering = ("last_name", "first_name", "year_of_death")
92
93     class Wikidata:
94         first_name = WIKIDATA.GIVEN_NAME
95         last_name = WIKIDATA.LAST_NAME
96         date_of_birth = WIKIDATA.DATE_OF_BIRTH
97         year_of_birth = WIKIDATA.DATE_OF_BIRTH
98         place_of_birth = WIKIDATA.PLACE_OF_BIRTH
99         date_of_death = WIKIDATA.DATE_OF_DEATH
100         year_of_death = WIKIDATA.DATE_OF_DEATH
101         place_of_death = WIKIDATA.PLACE_OF_DEATH
102         gender = WIKIDATA.GENDER
103         notes = WikiMedia.append("description")
104         plwiki = "plwiki"
105         photo = WikiMedia.download(WIKIDATA.IMAGE)
106         photo_source = WikiMedia.descriptionurl(WIKIDATA.IMAGE)
107         photo_attribution = WikiMedia.attribution(WIKIDATA.IMAGE)
108
109         def _supplement(obj):
110             if not obj.first_name and not obj.last_name:
111                 yield 'first_name', 'label'
112
113     def __str__(self):
114         name = f"{self.first_name} {self.last_name}"
115         if self.year_of_death is not None:
116             name += f' (zm. {self.year_of_death})'
117         return name
118
119     def get_absolute_url(self):
120         return reverse("catalogue_author", args=[self.slug])
121
122     @property
123     def name(self):
124         return f"{self.last_name}, {self.first_name}"
125     
126     @property
127     def pd_year(self):
128         if self.year_of_death:
129             return self.year_of_death + 71
130         elif self.year_of_death == 0:
131             return 0
132         else:
133             return None
134
135     def generate_description(self):
136         t = render_to_string(
137             'catalogue/author_description.html',
138             {'obj': self}
139         )
140         return t
141
142     def century_description(self, number):
143         n = abs(number)
144         letters = ''
145         while n > 10:
146             letters += 'X'
147             n -= 10
148         if n == 9:
149             letters += 'IX'
150             n = 0
151         elif n >= 5:
152             letters += 'V'
153             n -= 5
154         if n == 4:
155             letters += 'IV'
156             n = 0
157         letters += 'I' * n
158         letters += ' w.'
159         if number < 0:
160             letters += ' p.n.e.'
161         return letters
162
163     def birth_century_description(self):
164         return self.century_description(self.century_of_birth)
165
166     def death_century_description(self):
167         return self.century_description(self.century_of_death)
168
169     def year_description(self, number):
170         n = abs(number)
171         letters = str(n)
172         letters += ' r.'
173         if number < 0:
174             letters += ' p.n.e.'
175         return letters
176
177     def year_of_birth_description(self):
178         return self.year_description(self.year_of_birth)
179     def year_of_death_description(self):
180         return self.year_description(self.year_of_death)
181
182
183 class NotableBook(OrderableModel):
184     author = models.ForeignKey(Author, models.CASCADE)
185     book = models.ForeignKey('Book', models.CASCADE)
186
187
188 class Category(WikidataModel):
189     name = models.CharField(_("name"), max_length=255)
190     slug = models.SlugField(max_length=255, unique=True)
191     description = models.TextField(_("description"), blank=True, help_text=_('for publication'))
192
193     class Meta:
194         abstract = True
195
196     def __str__(self):
197         return self.name
198
199
200 class Epoch(Category):
201     adjective_feminine_singular = models.CharField(
202         'przymiotnik pojedynczy żeński', max_length=255, blank=True,
203         help_text='twórczość … Adama Mickiewicza'
204     )
205     adjective_nonmasculine_plural = models.CharField(
206         'przymiotnik mnogi niemęskoosobowy', max_length=255, blank=True,
207         help_text='utwory … Adama Mickiewicza'
208     )
209
210     class Meta:
211         verbose_name = _('epoch')
212         verbose_name_plural = _('epochs')
213
214
215 class Genre(Category):
216     plural = models.CharField(
217         'liczba mnoga', max_length=255, blank=True,
218         help_text='dotyczy gatunków'
219     )
220     is_epoch_specific = models.BooleanField(
221         default=False,
222         help_text='Po wskazaniu tego gatunku, dodanie epoki byłoby nadmiarowe, np. „dramat romantyczny”'
223     )
224
225     class Meta:
226         verbose_name = _('genre')
227         verbose_name_plural = _('genres')
228
229
230 class Kind(Category):
231     collective_noun = models.CharField(
232         'określenie zbiorowe', max_length=255, blank=True,
233         help_text='np. „Liryka” albo „Twórczość dramatyczna”'
234     )
235
236     class Meta:
237         verbose_name = _('kind')
238         verbose_name_plural = _('kinds')
239
240
241 class Book(WikidataModel):
242     slug = models.SlugField(max_length=255, blank=True, null=True, unique=True)
243     authors = models.ManyToManyField(Author, blank=True, verbose_name=_("authors"))
244     translators = models.ManyToManyField(
245         Author,
246         related_name="translated_book_set",
247         related_query_name="translated_book",
248         blank=True,
249         verbose_name=_("translators")
250     )
251     epochs = models.ManyToManyField(Epoch, blank=True, verbose_name=_("epochs"))
252     kinds = models.ManyToManyField(Kind, blank=True, verbose_name=_("kinds"))
253     genres = models.ManyToManyField(Genre, blank=True, verbose_name=_("genres"))
254     title = models.CharField(_("title"), max_length=255, blank=True)
255     language = models.CharField(_("language"), max_length=255, blank=True)
256     based_on = models.ForeignKey(
257         "self", models.PROTECT, related_name="translation", null=True, blank=True,
258         verbose_name=_("based on")
259     )
260     scans_source = models.CharField(_("scans source"), max_length=255, blank=True)
261     text_source = models.CharField(_("text source"), max_length=255, blank=True)
262     notes = models.TextField(_("notes"), blank=True, help_text=_('private'))
263     priority = models.PositiveSmallIntegerField(
264         _("priority"),
265         default=0, choices=[(0, _("Low")), (1, _("Medium")), (2, _("High"))]
266     )
267     original_year = models.IntegerField(_('original publication year'), null=True, blank=True)
268     pd_year = models.IntegerField(_('year of entry into PD'), null=True, blank=True)
269     gazeta_link = models.CharField(_("gazeta link"), max_length=255, blank=True)
270     collections = models.ManyToManyField("Collection", blank=True, verbose_name=_("collections"))
271
272     estimated_chars = models.IntegerField(_("estimated number of characters"), null=True, blank=True)
273     estimated_verses = models.IntegerField(_("estimated number of verses"), null=True, blank=True)
274     estimate_source = models.CharField(_("source of estimates"), max_length=2048, blank=True)
275
276     free_license = models.BooleanField(_('free license'), default=False)
277     polona_missing = models.BooleanField(_('missing on Polona'), default=False)
278
279     monthly_views_reader = models.IntegerField(default=0)
280     monthly_views_page = models.IntegerField(default=0)
281     
282     class Meta:
283         ordering = ("title",)
284         verbose_name = _('book')
285         verbose_name_plural = _('books')
286
287     class Wikidata:
288         authors = WIKIDATA.AUTHOR
289         translators = WIKIDATA.TRANSLATOR
290         title = WIKIDATA.TITLE
291         language = WIKIDATA.LANGUAGE
292         based_on = WIKIDATA.BASED_ON
293         original_year = WIKIDATA.PUBLICATION_DATE
294         notes = WikiMedia.append("description")
295
296     def __str__(self):
297         txt = self.title
298         if self.original_year:
299             txt = f"{txt} ({self.original_year})"
300         astr = self.authors_str()
301         if astr:
302             txt = f"{txt}, {astr}"
303         tstr = self.translators_str()
304         if tstr:
305             txt = f"{txt}, tłum. {tstr}"
306         return txt
307
308     def get_absolute_url(self):
309         return reverse("catalogue_book", args=[self.slug])
310
311     @property
312     def wluri(self):
313         return f'https://wolnelektury.pl/katalog/lektura/{self.slug}/'
314     
315     def authors_str(self):
316         if not self.pk:
317             return ''
318         return ", ".join(str(author) for author in self.authors.all())
319     authors_str.admin_order_field = 'authors__last_name'
320     authors_str.short_description = _('Author')
321
322     def translators_str(self):
323         if not self.pk:
324             return ''
325         return ", ".join(str(author) for author in self.translators.all())
326     translators_str.admin_order_field = 'translators__last_name'
327     translators_str.short_description = _('Translator')
328
329     def authors_first_names(self):
330         return ', '.join(a.first_name for a in self.authors.all())
331
332     def authors_last_names(self):
333         return ', '.join(a.last_name for a in self.authors.all())
334
335     def translators_first_names(self):
336         return ', '.join(a.first_name for a in self.translators.all())
337
338     def translators_last_names(self):
339         return ', '.join(a.last_name for a in self.translators.all())
340
341     def document_book__project(self):
342         b = self.document_books.first()
343         if b is None: return ''
344         if b.project is None: return ''
345         return b.project.name
346
347     def audience(self):
348         try:
349             return self.document_books.first().wldocument().book_info.audience or ''
350         except:
351             return ''
352
353     def get_estimated_costs(self):
354         return {
355             work_type: work_type.calculate(self)
356             for work_type in WorkType.objects.all()
357         }
358
359     def update_monthly_stats(self):
360         # Find publication date.
361         # By default, get previous 12 months.
362         this_month = date.today().replace(day=1)
363         cutoff = this_month.replace(year=this_month.year - 1)
364         months = 12
365
366         # If the book was published later,
367         # find out the denominator.
368         pbr = apps.get_model('documents', 'BookPublishRecord').objects.filter(
369             book__catalogue_book=self).order_by('timestamp').first()
370         if pbr is not None and pbr.timestamp.date() > cutoff:
371             months = (this_month - pbr.timestamp.date()).days / 365 * 12
372
373         if not months:
374             return
375
376         stats = self.bookmonthlystats_set.filter(date__gte=cutoff).aggregate(
377             views_page=models.Sum('views_page'),
378             views_reader=models.Sum('views_reader')
379         )
380         self.monthly_views_page = stats['views_page'] / months
381         self.monthly_views_reader = stats['views_reader'] / months
382         self.save(update_fields=['monthly_views_page', 'monthly_views_reader'])
383
384     @property
385     def content_stats(self):
386         if hasattr(self, '_content_stats'):
387             return self._content_stats
388         try:
389             stats = self.document_books.first().wldocument().get_statistics()['total']
390         except Exception as e:
391             stats = {}
392         self._content_stats = stats
393         return stats
394
395     chars = lambda self: self.content_stats.get('chars', '')
396     chars_with_fn = lambda self: self.content_stats.get('chars_with_fn', '')
397     words = lambda self: self.content_stats.get('words', '')
398     words_with_fn = lambda self: self.content_stats.get('words_with_fn', '')
399     verses = lambda self: self.content_stats.get('verses', '')
400     verses_with_fn = lambda self: self.content_stats.get('verses_with_fn', '')
401     chars_out_verse = lambda self: self.content_stats.get('chars_out_verse', '')
402     chars_out_verse_with_fn = lambda self: self.content_stats.get('chars_out_verse_with_fn', '')
403
404 class CollectionCategory(models.Model):
405     name = models.CharField(_("name"), max_length=255)
406     parent = models.ForeignKey('self', models.SET_NULL, related_name='children', null=True, blank=True, verbose_name=_("parent"))
407     notes = models.TextField(_("notes"), blank=True, help_text=_('private'))
408
409     class Meta:
410         ordering = ('parent__name', 'name')
411         verbose_name = _('collection category')
412         verbose_name_plural = _('collection categories')
413
414     def __str__(self):
415         if self.parent:
416             return f"{self.parent} / {self.name}"
417         else:
418             return self.name
419
420
421 class Collection(models.Model):
422     name = models.CharField(_("name"), max_length=255)
423     slug = models.SlugField(max_length=255, unique=True)
424     category = models.ForeignKey(CollectionCategory, models.SET_NULL, null=True, blank=True, verbose_name=_("category"))
425     notes = models.TextField(_("notes"), blank=True, help_text=_('private'))
426     description = models.TextField(_("description"), blank=True)
427
428     class Meta:
429         ordering = ('category', 'name')
430         verbose_name = _('collection')
431         verbose_name_plural = _('collections')
432
433     def __str__(self):
434         if self.category:
435             return f"{self.category} / {self.name}"
436         else:
437             return self.name
438
439     def get_estimated_costs(self):
440         costs = Counter()
441         for book in self.book_set.all():
442             for k, v in book.get_estimated_costs().items():
443                 costs[k] += v or 0
444
445         for author in self.author_set.all():
446             for book in author.book_set.all():
447                 for k, v in book.get_estimated_costs().items():
448                     costs[k] += v or 0
449             for book in author.translated_book_set.all():
450                 for k, v in book.get_estimated_costs().items():
451                     costs[k] += v or 0
452         return costs
453
454
455 class WorkType(models.Model):
456     name = models.CharField(_("name"), max_length=255)
457
458     class Meta:
459         ordering = ('name',)
460         verbose_name = _('work type')
461         verbose_name_plural = _('work types')
462     
463     def get_rate_for(self, book):
464         for workrate in self.workrate_set.all():
465             if workrate.matches(book):
466                 return workrate
467
468     def calculate(self, book):
469         workrate = self.get_rate_for(book)
470         if workrate is not None:
471             return workrate.calculate(book)
472         
473
474
475 class WorkRate(models.Model):
476     priority = models.IntegerField(_("priority"), default=1)
477     per_normpage = models.DecimalField(_("per normalized page"), decimal_places=2, max_digits=6, null=True, blank=True)
478     per_verse = models.DecimalField(_("per verse"), decimal_places=2, max_digits=6, null=True, blank=True)
479     work_type = models.ForeignKey(WorkType, models.CASCADE, verbose_name=_("work type"))
480     epochs = models.ManyToManyField(Epoch, blank=True, verbose_name=_("epochs"))
481     kinds = models.ManyToManyField(Kind, blank=True, verbose_name=_("kinds"))
482     genres = models.ManyToManyField(Genre, blank=True, verbose_name=_("genres"))
483     collections = models.ManyToManyField(Collection, blank=True, verbose_name=_("collections"))
484
485     class Meta:
486         ordering = ('priority',)
487         verbose_name = _('work rate')
488         verbose_name_plural = _('work rates')
489
490     def matches(self, book):
491         for category in 'epochs', 'kinds', 'genres', 'collections':
492             oneof = getattr(self, category).all()
493             if oneof:
494                 if not set(oneof).intersection(
495                         getattr(book, category).all()):
496                     return False
497         return True
498
499     def calculate(self, book):
500         if self.per_verse:
501             if book.estimated_verses:
502                 return book.estimated_verses * self.per_verse
503         elif self.per_normpage:
504             if book.estimated_chars:
505                 return (decimal.Decimal(book.estimated_chars) / 1800 * self.per_normpage).quantize(decimal.Decimal('1.00'), rounding=decimal.ROUND_HALF_UP)
506
507
508 class Place(WikidataModel):
509     name = models.CharField(_('name'), max_length=255, blank=True)
510     locative = models.CharField(_('locative'), max_length=255, blank=True, help_text=_('in…'))
511
512     class Meta:
513         verbose_name = _('place')
514         verbose_name_plural = _('places')
515     
516     class Wikidata:
517         name = 'label'
518
519     def __str__(self):
520         return self.name
521
522
523 class BookMonthlyStats(models.Model):
524     book = models.ForeignKey('catalogue.Book', models.CASCADE)
525     date = models.DateField()
526     views_reader = models.IntegerField(default=0)
527     views_page = models.IntegerField(default=0)
528
529     @classmethod
530     def build_for_month(cls, date):
531         date = date.replace(day=1)
532         period = 'month'
533
534         date = date.isoformat()
535         url = f'{settings.PIWIK_URL}?date={date}&filter_limit=-1&format=CSV&idSite={settings.PIWIK_WL_SITE_ID}&language=pl&method=Actions.getPageUrls&module=API&period={period}&segment=&token_auth={settings.PIWIK_TOKEN}&flat=1'
536         data = urlopen(url).read().decode('utf-16')
537         lines = data.split('\n')[1:]
538         for line in lines:
539             m = re.match('^/katalog/lektura/([^,./]+)\.html,', line)
540             if m is not None:
541                 which = 'views_reader'
542             else:
543                 m = re.match('^/katalog/lektura/([^,./]+)/,', line)
544                 if m is not None:
545                     which = 'views_page'
546             if m is not None:
547                 slug = m.group(1)
548                 _url, _uviews, views, _rest = line.split(',', 3)
549                 views = int(views)
550                 try:
551                     book = Book.objects.get(slug=slug)
552                 except Book.DoesNotExist:
553                     continue
554                 else:
555                     cls.objects.update_or_create(
556                         book=book, date=date,
557                         defaults={which: views}
558                     )
559                     book.update_monthly_stats()
560
561
562 class Thema(models.Model):
563     code = models.CharField(max_length=128, unique=True)
564     name = models.CharField(max_length=1024)
565     description = models.TextField(blank=True)
566     usable = models.BooleanField()
567     hidden = models.BooleanField(default=False)
568
569     class Meta:
570         ordering = ('code',)