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