be6370837a5a0b564a4eb9aa8de25731ed9b53cf
[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     woblink = models.IntegerField(null=True, blank=True)
89     
90     class Meta:
91         verbose_name = _('author')
92         verbose_name_plural = _('authors')
93         ordering = ("last_name", "first_name", "year_of_death")
94
95     class Wikidata:
96         first_name = WIKIDATA.GIVEN_NAME
97         last_name = WIKIDATA.LAST_NAME
98         date_of_birth = WIKIDATA.DATE_OF_BIRTH
99         year_of_birth = WIKIDATA.DATE_OF_BIRTH
100         place_of_birth = WIKIDATA.PLACE_OF_BIRTH
101         date_of_death = WIKIDATA.DATE_OF_DEATH
102         year_of_death = WIKIDATA.DATE_OF_DEATH
103         place_of_death = WIKIDATA.PLACE_OF_DEATH
104         gender = WIKIDATA.GENDER
105         notes = WikiMedia.append("description")
106         plwiki = "plwiki"
107         photo = WikiMedia.download(WIKIDATA.IMAGE)
108         photo_source = WikiMedia.descriptionurl(WIKIDATA.IMAGE)
109         photo_attribution = WikiMedia.attribution(WIKIDATA.IMAGE)
110
111         def _supplement(obj):
112             if not obj.first_name and not obj.last_name:
113                 yield 'first_name', 'label'
114
115     def __str__(self):
116         name = f"{self.first_name} {self.last_name}"
117         if self.year_of_death is not None:
118             name += f' (zm. {self.year_of_death})'
119         return name
120
121     def get_absolute_url(self):
122         return reverse("catalogue_author", args=[self.slug])
123
124     @classmethod
125     def get_by_literal(cls, literal):
126         names = literal.split(',', 1)
127         names = [n.strip() for n in names]
128         if len(names) == 2:
129             return cls.objects.filter(last_name=names[0], first_name=names[1]).first()
130         else:
131             return cls.objects.filter(last_name=names[0], first_name='').first() or \
132                 cls.objects.filter(first_name=names[0], last_name='').first()
133
134     @property
135     def name(self):
136         return f"{self.last_name}, {self.first_name}"
137     
138     @property
139     def pd_year(self):
140         if self.year_of_death:
141             return self.year_of_death + 71
142         elif self.year_of_death == 0:
143             return 0
144         else:
145             return None
146
147     def generate_description(self):
148         t = render_to_string(
149             'catalogue/author_description.html',
150             {'obj': self}
151         )
152         return t
153
154     def century_description(self, number):
155         n = abs(number)
156         letters = ''
157         while n > 10:
158             letters += 'X'
159             n -= 10
160         if n == 9:
161             letters += 'IX'
162             n = 0
163         elif n >= 5:
164             letters += 'V'
165             n -= 5
166         if n == 4:
167             letters += 'IV'
168             n = 0
169         letters += 'I' * n
170         letters += ' w.'
171         if number < 0:
172             letters += ' p.n.e.'
173         return letters
174
175     def birth_century_description(self):
176         return self.century_description(self.century_of_birth)
177
178     def death_century_description(self):
179         return self.century_description(self.century_of_death)
180
181     def year_description(self, number):
182         n = abs(number)
183         letters = str(n)
184         letters += ' r.'
185         if number < 0:
186             letters += ' p.n.e.'
187         return letters
188
189     def year_of_birth_description(self):
190         return self.year_description(self.year_of_birth)
191     def year_of_death_description(self):
192         return self.year_description(self.year_of_death)
193
194
195 class NotableBook(OrderableModel):
196     author = models.ForeignKey(Author, models.CASCADE)
197     book = models.ForeignKey('Book', models.CASCADE)
198
199
200 class Category(WikidataModel):
201     name = models.CharField(_("name"), max_length=255)
202     slug = models.SlugField(max_length=255, unique=True)
203     description = models.TextField(_("description"), blank=True, help_text=_('for publication'))
204
205     class Meta:
206         abstract = True
207
208     def __str__(self):
209         return self.name
210
211
212 class Epoch(Category):
213     adjective_feminine_singular = models.CharField(
214         'przymiotnik pojedynczy żeński', max_length=255, blank=True,
215         help_text='twórczość … Adama Mickiewicza'
216     )
217     adjective_nonmasculine_plural = models.CharField(
218         'przymiotnik mnogi niemęskoosobowy', max_length=255, blank=True,
219         help_text='utwory … Adama Mickiewicza'
220     )
221
222     class Meta:
223         verbose_name = _('epoch')
224         verbose_name_plural = _('epochs')
225
226
227 class Genre(Category):
228     plural = models.CharField(
229         'liczba mnoga', max_length=255, blank=True,
230     )
231     is_epoch_specific = models.BooleanField(
232         default=False,
233         help_text='Po wskazaniu tego gatunku, dodanie epoki byłoby nadmiarowe, np. „dramat romantyczny”'
234     )
235
236     class Meta:
237         verbose_name = _('genre')
238         verbose_name_plural = _('genres')
239
240
241 class Kind(Category):
242     collective_noun = models.CharField(
243         'określenie zbiorowe', max_length=255, blank=True,
244         help_text='np. „Liryka” albo „Twórczość dramatyczna”'
245     )
246
247     class Meta:
248         verbose_name = _('kind')
249         verbose_name_plural = _('kinds')
250
251
252 class Book(WikidataModel):
253     slug = models.SlugField(max_length=255, blank=True, null=True, unique=True)
254     authors = models.ManyToManyField(Author, blank=True, verbose_name=_("authors"))
255     translators = models.ManyToManyField(
256         Author,
257         related_name="translated_book_set",
258         related_query_name="translated_book",
259         blank=True,
260         verbose_name=_("translators")
261     )
262     epochs = models.ManyToManyField(Epoch, blank=True, verbose_name=_("epochs"))
263     kinds = models.ManyToManyField(Kind, blank=True, verbose_name=_("kinds"))
264     genres = models.ManyToManyField(Genre, blank=True, verbose_name=_("genres"))
265     title = models.CharField(_("title"), max_length=255, blank=True)
266     language = models.CharField(_("language"), max_length=255, blank=True)
267     based_on = models.ForeignKey(
268         "self", models.PROTECT, related_name="translation", null=True, blank=True,
269         verbose_name=_("based on")
270     )
271     scans_source = models.CharField(_("scans source"), max_length=255, blank=True)
272     text_source = models.CharField(_("text source"), max_length=255, blank=True)
273     notes = models.TextField(_("notes"), blank=True, help_text=_('private'))
274     priority = models.PositiveSmallIntegerField(
275         _("priority"),
276         default=0, choices=[(0, _("Low")), (1, _("Medium")), (2, _("High"))]
277     )
278     original_year = models.IntegerField(_('original publication year'), null=True, blank=True)
279     pd_year = models.IntegerField(_('year of entry into PD'), null=True, blank=True)
280     gazeta_link = models.CharField(_("gazeta link"), max_length=255, blank=True)
281     collections = models.ManyToManyField("Collection", blank=True, verbose_name=_("collections"))
282
283     estimated_chars = models.IntegerField(_("estimated number of characters"), null=True, blank=True)
284     estimated_verses = models.IntegerField(_("estimated number of verses"), null=True, blank=True)
285     estimate_source = models.CharField(_("source of estimates"), max_length=2048, blank=True)
286
287     free_license = models.BooleanField(_('free license'), default=False)
288     polona_missing = models.BooleanField(_('missing on Polona'), default=False)
289
290     monthly_views_reader = models.IntegerField(default=0)
291     monthly_views_page = models.IntegerField(default=0)
292     
293     class Meta:
294         ordering = ("title",)
295         verbose_name = _('book')
296         verbose_name_plural = _('books')
297
298     class Wikidata:
299         authors = WIKIDATA.AUTHOR
300         translators = WIKIDATA.TRANSLATOR
301         title = WIKIDATA.TITLE
302         language = WIKIDATA.LANGUAGE
303         based_on = WIKIDATA.BASED_ON
304         original_year = WIKIDATA.PUBLICATION_DATE
305         notes = WikiMedia.append("description")
306
307     def __str__(self):
308         txt = self.title
309         if self.original_year:
310             txt = f"{txt} ({self.original_year})"
311         astr = self.authors_str()
312         if astr:
313             txt = f"{txt}, {astr}"
314         tstr = self.translators_str()
315         if tstr:
316             txt = f"{txt}, tłum. {tstr}"
317         return txt
318
319     def get_absolute_url(self):
320         return reverse("catalogue_book", args=[self.slug])
321
322     @property
323     def wluri(self):
324         return f'https://wolnelektury.pl/katalog/lektura/{self.slug}/'
325     
326     def authors_str(self):
327         if not self.pk:
328             return ''
329         return ", ".join(str(author) for author in self.authors.all())
330     authors_str.admin_order_field = 'authors__last_name'
331     authors_str.short_description = _('Author')
332
333     def translators_str(self):
334         if not self.pk:
335             return ''
336         return ", ".join(str(author) for author in self.translators.all())
337     translators_str.admin_order_field = 'translators__last_name'
338     translators_str.short_description = _('Translator')
339
340     def authors_first_names(self):
341         return ', '.join(a.first_name for a in self.authors.all())
342
343     def authors_last_names(self):
344         return ', '.join(a.last_name for a in self.authors.all())
345
346     def translators_first_names(self):
347         return ', '.join(a.first_name for a in self.translators.all())
348
349     def translators_last_names(self):
350         return ', '.join(a.last_name for a in self.translators.all())
351
352     def document_book__project(self):
353         b = self.document_books.first()
354         if b is None: return ''
355         if b.project is None: return ''
356         return b.project.name
357
358     def audience(self):
359         try:
360             return self.document_books.first().wldocument().book_info.audience or ''
361         except:
362             return ''
363
364     def get_estimated_costs(self):
365         return {
366             work_type: work_type.calculate(self)
367             for work_type in WorkType.objects.all()
368         }
369
370     def update_monthly_stats(self):
371         # Find publication date.
372         # By default, get previous 12 months.
373         this_month = date.today().replace(day=1)
374         cutoff = this_month.replace(year=this_month.year - 1)
375         months = 12
376
377         # If the book was published later,
378         # find out the denominator.
379         pbr = apps.get_model('documents', 'BookPublishRecord').objects.filter(
380             book__catalogue_book=self).order_by('timestamp').first()
381         if pbr is not None and pbr.timestamp.date() > cutoff:
382             months = (this_month - pbr.timestamp.date()).days / 365 * 12
383
384         if not months:
385             return
386
387         stats = self.bookmonthlystats_set.filter(date__gte=cutoff).aggregate(
388             views_page=models.Sum('views_page'),
389             views_reader=models.Sum('views_reader')
390         )
391         self.monthly_views_page = stats['views_page'] / months
392         self.monthly_views_reader = stats['views_reader'] / months
393         self.save(update_fields=['monthly_views_page', 'monthly_views_reader'])
394
395     @property
396     def content_stats(self):
397         if hasattr(self, '_content_stats'):
398             return self._content_stats
399         try:
400             stats = self.document_books.first().wldocument().get_statistics()['total']
401         except Exception as e:
402             stats = {}
403         self._content_stats = stats
404         return stats
405
406     chars = lambda self: self.content_stats.get('chars', '')
407     chars_with_fn = lambda self: self.content_stats.get('chars_with_fn', '')
408     words = lambda self: self.content_stats.get('words', '')
409     words_with_fn = lambda self: self.content_stats.get('words_with_fn', '')
410     verses = lambda self: self.content_stats.get('verses', '')
411     verses_with_fn = lambda self: self.content_stats.get('verses_with_fn', '')
412     chars_out_verse = lambda self: self.content_stats.get('chars_out_verse', '')
413     chars_out_verse_with_fn = lambda self: self.content_stats.get('chars_out_verse_with_fn', '')
414
415 class CollectionCategory(models.Model):
416     name = models.CharField(_("name"), max_length=255)
417     parent = models.ForeignKey('self', models.SET_NULL, related_name='children', null=True, blank=True, verbose_name=_("parent"))
418     notes = models.TextField(_("notes"), blank=True, help_text=_('private'))
419
420     class Meta:
421         ordering = ('parent__name', 'name')
422         verbose_name = _('collection category')
423         verbose_name_plural = _('collection categories')
424
425     def __str__(self):
426         if self.parent:
427             return f"{self.parent} / {self.name}"
428         else:
429             return self.name
430
431
432 class Collection(models.Model):
433     name = models.CharField(_("name"), max_length=255)
434     slug = models.SlugField(max_length=255, unique=True)
435     category = models.ForeignKey(CollectionCategory, models.SET_NULL, null=True, blank=True, verbose_name=_("category"))
436     notes = models.TextField(_("notes"), blank=True, help_text=_('private'))
437     description = models.TextField(_("description"), blank=True)
438
439     class Meta:
440         ordering = ('category', 'name')
441         verbose_name = _('collection')
442         verbose_name_plural = _('collections')
443
444     def __str__(self):
445         if self.category:
446             return f"{self.category} / {self.name}"
447         else:
448             return self.name
449
450     def get_estimated_costs(self):
451         costs = Counter()
452         for book in self.book_set.all():
453             for k, v in book.get_estimated_costs().items():
454                 costs[k] += v or 0
455
456         for author in self.author_set.all():
457             for book in author.book_set.all():
458                 for k, v in book.get_estimated_costs().items():
459                     costs[k] += v or 0
460             for book in author.translated_book_set.all():
461                 for k, v in book.get_estimated_costs().items():
462                     costs[k] += v or 0
463         return costs
464
465
466 class WorkType(models.Model):
467     name = models.CharField(_("name"), max_length=255)
468
469     class Meta:
470         ordering = ('name',)
471         verbose_name = _('work type')
472         verbose_name_plural = _('work types')
473     
474     def get_rate_for(self, book):
475         for workrate in self.workrate_set.all():
476             if workrate.matches(book):
477                 return workrate
478
479     def calculate(self, book):
480         workrate = self.get_rate_for(book)
481         if workrate is not None:
482             return workrate.calculate(book)
483         
484
485
486 class WorkRate(models.Model):
487     priority = models.IntegerField(_("priority"), default=1)
488     per_normpage = models.DecimalField(_("per normalized page"), decimal_places=2, max_digits=6, null=True, blank=True)
489     per_verse = models.DecimalField(_("per verse"), decimal_places=2, max_digits=6, null=True, blank=True)
490     work_type = models.ForeignKey(WorkType, models.CASCADE, verbose_name=_("work type"))
491     epochs = models.ManyToManyField(Epoch, blank=True, verbose_name=_("epochs"))
492     kinds = models.ManyToManyField(Kind, blank=True, verbose_name=_("kinds"))
493     genres = models.ManyToManyField(Genre, blank=True, verbose_name=_("genres"))
494     collections = models.ManyToManyField(Collection, blank=True, verbose_name=_("collections"))
495
496     class Meta:
497         ordering = ('priority',)
498         verbose_name = _('work rate')
499         verbose_name_plural = _('work rates')
500
501     def matches(self, book):
502         for category in 'epochs', 'kinds', 'genres', 'collections':
503             oneof = getattr(self, category).all()
504             if oneof:
505                 if not set(oneof).intersection(
506                         getattr(book, category).all()):
507                     return False
508         return True
509
510     def calculate(self, book):
511         if self.per_verse:
512             if book.estimated_verses:
513                 return book.estimated_verses * self.per_verse
514         elif self.per_normpage:
515             if book.estimated_chars:
516                 return (decimal.Decimal(book.estimated_chars) / 1800 * self.per_normpage).quantize(decimal.Decimal('1.00'), rounding=decimal.ROUND_HALF_UP)
517
518
519 class Place(WikidataModel):
520     name = models.CharField(_('name'), max_length=255, blank=True)
521     locative = models.CharField(_('locative'), max_length=255, blank=True, help_text=_('in…'))
522
523     class Meta:
524         verbose_name = _('place')
525         verbose_name_plural = _('places')
526     
527     class Wikidata:
528         name = 'label'
529
530     def __str__(self):
531         return self.name
532
533
534 class BookMonthlyStats(models.Model):
535     book = models.ForeignKey('catalogue.Book', models.CASCADE)
536     date = models.DateField()
537     views_reader = models.IntegerField(default=0)
538     views_page = models.IntegerField(default=0)
539
540     @classmethod
541     def build_for_month(cls, date):
542         date = date.replace(day=1)
543         period = 'month'
544
545         date = date.isoformat()
546         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'
547         data = urlopen(url).read().decode('utf-16')
548         lines = data.split('\n')[1:]
549         for line in lines:
550             m = re.match('^/katalog/lektura/([^,./]+)\.html,', line)
551             if m is not None:
552                 which = 'views_reader'
553             else:
554                 m = re.match('^/katalog/lektura/([^,./]+)/,', line)
555                 if m is not None:
556                     which = 'views_page'
557             if m is not None:
558                 slug = m.group(1)
559                 _url, _uviews, views, _rest = line.split(',', 3)
560                 views = int(views)
561                 try:
562                     book = Book.objects.get(slug=slug)
563                 except Book.DoesNotExist:
564                     continue
565                 else:
566                     cls.objects.update_or_create(
567                         book=book, date=date,
568                         defaults={which: views}
569                     )
570                     book.update_monthly_stats()
571
572
573 class Thema(models.Model):
574     code = models.CharField(max_length=128, unique=True)
575     name = models.CharField(max_length=1024)
576     slug = models.SlugField(
577         max_length=255, null=True, blank=True, unique=True,
578         help_text='Element adresu na WL, w postaci: /tag/slug/. Można zmieniać.'
579     )
580     plural = models.CharField(
581         'liczba mnoga', max_length=255, blank=True,
582     )
583     description = models.TextField(blank=True)
584     public_description = models.TextField(blank=True)
585     usable = models.BooleanField()
586     usable_as_main = models.BooleanField(default=False)
587     hidden = models.BooleanField(default=False)
588     woblink_category = models.IntegerField(null=True, blank=True)
589
590     class Meta:
591         ordering = ('code',)
592         verbose_name_plural = 'Thema'
593
594
595 class Audience(models.Model):
596     code = models.CharField(
597         max_length=128, unique=True,
598         help_text='Techniczny identifyikator. W miarę możliwości nie należy zmieniać.'
599     )
600     name = models.CharField(
601         max_length=1024,
602         help_text='W formie: „dla … (kogo?)”'
603     )
604     slug = models.SlugField(
605         max_length=255, null=True, blank=True, unique=True,
606         help_text='Element adresu na WL, w postaci: /dla/slug/. Można zmieniać.'
607     )
608     description = models.TextField(blank=True)
609     thema = models.CharField(
610         max_length=32, blank=True,
611         help_text='Odpowiadający kwalifikator Thema.'
612     )
613
614     class Meta:
615         ordering = ('code',)