descriptions 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 get_estimated_costs(self):
292         return {
293             work_type: work_type.calculate(self)
294             for work_type in WorkType.objects.all()
295         }
296
297     def update_monthly_stats(self):
298         # Find publication date.
299         # By default, get previous 12 months.
300         this_month = date.today().replace(day=1)
301         cutoff = this_month.replace(year=this_month.year - 1)
302         months = 12
303
304         # If the book was published later,
305         # find out the denominator.
306         pbr = apps.get_model('documents', 'BookPublishRecord').objects.filter(
307             book__catalogue_book=self).order_by('timestamp').first()
308         if pbr is not None and pbr.timestamp.date() > cutoff:
309             months = (this_month - pbr.timestamp.date()).days / 365 * 12
310
311         stats = self.bookmonthlystats_set.filter(date__gte=cutoff).aggregate(
312             views_page=models.Sum('views_page'),
313             views_reader=models.Sum('views_reader')
314         )
315         self.monthly_views_page = stats['views_page'] / months
316         self.monthly_views_reader = stats['views_reader'] / months
317         self.save(update_fields=['monthly_views_page', 'monthly_views_reader'])
318
319     @property
320     def content_stats(self):
321         if hasattr(self, '_content_stats'):
322             return self._content_stats
323         try:
324             stats = self.document_books.first().wldocument().get_statistics()['total']
325         except Exception as e:
326             stats = {}
327         self._content_stats = stats
328         return stats
329
330     chars = lambda self: self.content_stats.get('chars', '')
331     chars_with_fn = lambda self: self.content_stats.get('chars_with_fn', '')
332     words = lambda self: self.content_stats.get('words', '')
333     words_with_fn = lambda self: self.content_stats.get('words_with_fn', '')
334     verses = lambda self: self.content_stats.get('verses', '')
335     verses_with_fn = lambda self: self.content_stats.get('verses_with_fn', '')
336     chars_out_verse = lambda self: self.content_stats.get('chars_out_verse', '')
337     chars_out_verse_with_fn = lambda self: self.content_stats.get('chars_out_verse_with_fn', '')
338
339 class CollectionCategory(models.Model):
340     name = models.CharField(_("name"), max_length=255)
341     parent = models.ForeignKey('self', models.SET_NULL, related_name='children', null=True, blank=True, verbose_name=_("parent"))
342     notes = models.TextField(_("notes"), blank=True, help_text=_('private'))
343
344     class Meta:
345         ordering = ('parent__name', 'name')
346         verbose_name = _('collection category')
347         verbose_name_plural = _('collection categories')
348
349     def __str__(self):
350         if self.parent:
351             return f"{self.parent} / {self.name}"
352         else:
353             return self.name
354
355
356 class Collection(models.Model):
357     name = models.CharField(_("name"), max_length=255)
358     slug = models.SlugField(max_length=255, unique=True)
359     category = models.ForeignKey(CollectionCategory, models.SET_NULL, null=True, blank=True, verbose_name=_("category"))
360     notes = models.TextField(_("notes"), blank=True, help_text=_('private'))
361     description = models.TextField(_("description"), blank=True)
362
363     class Meta:
364         ordering = ('category', 'name')
365         verbose_name = _('collection')
366         verbose_name_plural = _('collections')
367
368     def __str__(self):
369         if self.category:
370             return f"{self.category} / {self.name}"
371         else:
372             return self.name
373
374     def get_estimated_costs(self):
375         costs = Counter()
376         for book in self.book_set.all():
377             for k, v in book.get_estimated_costs().items():
378                 costs[k] += v or 0
379
380         for author in self.author_set.all():
381             for book in author.book_set.all():
382                 for k, v in book.get_estimated_costs().items():
383                     costs[k] += v or 0
384             for book in author.translated_book_set.all():
385                 for k, v in book.get_estimated_costs().items():
386                     costs[k] += v or 0
387         return costs
388
389
390 class WorkType(models.Model):
391     name = models.CharField(_("name"), max_length=255)
392
393     class Meta:
394         ordering = ('name',)
395         verbose_name = _('work type')
396         verbose_name_plural = _('work types')
397     
398     def get_rate_for(self, book):
399         for workrate in self.workrate_set.all():
400             if workrate.matches(book):
401                 return workrate
402
403     def calculate(self, book):
404         workrate = self.get_rate_for(book)
405         if workrate is not None:
406             return workrate.calculate(book)
407         
408
409
410 class WorkRate(models.Model):
411     priority = models.IntegerField(_("priority"), default=1)
412     per_normpage = models.DecimalField(_("per normalized page"), decimal_places=2, max_digits=6, null=True, blank=True)
413     per_verse = models.DecimalField(_("per verse"), decimal_places=2, max_digits=6, null=True, blank=True)
414     work_type = models.ForeignKey(WorkType, models.CASCADE, verbose_name=_("work type"))
415     epochs = models.ManyToManyField(Epoch, blank=True, verbose_name=_("epochs"))
416     kinds = models.ManyToManyField(Kind, blank=True, verbose_name=_("kinds"))
417     genres = models.ManyToManyField(Genre, blank=True, verbose_name=_("genres"))
418     collections = models.ManyToManyField(Collection, blank=True, verbose_name=_("collections"))
419
420     class Meta:
421         ordering = ('priority',)
422         verbose_name = _('work rate')
423         verbose_name_plural = _('work rates')
424
425     def matches(self, book):
426         for category in 'epochs', 'kinds', 'genres', 'collections':
427             oneof = getattr(self, category).all()
428             if oneof:
429                 if not set(oneof).intersection(
430                         getattr(book, category).all()):
431                     return False
432         return True
433
434     def calculate(self, book):
435         if self.per_verse:
436             if book.estimated_verses:
437                 return book.estimated_verses * self.per_verse
438         elif self.per_normpage:
439             if book.estimated_chars:
440                 return (decimal.Decimal(book.estimated_chars) / 1800 * self.per_normpage).quantize(decimal.Decimal('1.00'), rounding=decimal.ROUND_HALF_UP)
441
442
443 class Place(WikidataModel):
444     name = models.CharField(_('name'), max_length=255, blank=True)
445     locative = models.CharField(_('locative'), max_length=255, blank=True, help_text=_('in…'))
446
447     class Meta:
448         verbose_name = _('place')
449         verbose_name_plural = _('places')
450     
451     class Wikidata:
452         name = 'label'
453
454     def __str__(self):
455         return self.name
456
457
458 class BookMonthlyStats(models.Model):
459     book = models.ForeignKey('catalogue.Book', models.CASCADE)
460     date = models.DateField()
461     views_reader = models.IntegerField(default=0)
462     views_page = models.IntegerField(default=0)
463
464     @classmethod
465     def build_for_month(cls, date):
466         date = date.replace(day=1)
467         period = 'month'
468
469         date = date.isoformat()
470         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'
471         data = urlopen(url).read().decode('utf-16')
472         lines = data.split('\n')[1:]
473         for line in lines:
474             m = re.match('^/katalog/lektura/([^,./]+)\.html,', line)
475             if m is not None:
476                 which = 'views_reader'
477             else:
478                 m = re.match('^/katalog/lektura/([^,./]+)/,', line)
479                 if m is not None:
480                     which = 'views_page'
481             if m is not None:
482                 slug = m.group(1)
483                 _url, _uviews, views, _rest = line.split(',', 3)
484                 views = int(views)
485                 try:
486                     book = Book.objects.get(slug=slug)
487                 except Book.DoesNotExist:
488                     continue
489                 else:
490                     cls.objects.update_or_create(
491                         book=book, date=date,
492                         defaults={which: views}
493                     )
494                     book.update_monthly_stats()