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