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