1 from collections import Counter
2 from datetime import date, timedelta
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
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?)'
28 name_de = models.CharField(_("name (de)"), max_length=255, blank=True)
29 name_lt = models.CharField(_("name (lt)"), max_length=255, blank=True)
31 gender = models.CharField(_("gender"), max_length=255, blank=True)
32 nationality = models.CharField(_("nationality"), max_length=255, blank=True)
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.')
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'
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.')
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'
60 status = models.PositiveSmallIntegerField(
71 notes = models.TextField(_("notes"), blank=True, help_text=_('private'))
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)
80 description = models.TextField(_("description"), blank=True, help_text=_('for publication'))
82 priority = models.PositiveSmallIntegerField(
84 default=0, choices=[(0, _("Low")), (1, _("Medium")), (2, _("High"))]
86 collections = models.ManyToManyField("Collection", blank=True, verbose_name=_("collections"))
89 verbose_name = _('author')
90 verbose_name_plural = _('authors')
91 ordering = ("last_name", "first_name", "year_of_death")
94 first_name = WIKIDATA.GIVEN_NAME
95 last_name = WIKIDATA.LAST_NAME
96 date_of_birth = WIKIDATA.DATE_OF_BIRTH
97 year_of_birth = WIKIDATA.DATE_OF_BIRTH
98 place_of_birth = WIKIDATA.PLACE_OF_BIRTH
99 date_of_death = WIKIDATA.DATE_OF_DEATH
100 year_of_death = WIKIDATA.DATE_OF_DEATH
101 place_of_death = WIKIDATA.PLACE_OF_DEATH
102 gender = WIKIDATA.GENDER
103 notes = WikiMedia.append("description")
105 photo = WikiMedia.download(WIKIDATA.IMAGE)
106 photo_source = WikiMedia.descriptionurl(WIKIDATA.IMAGE)
107 photo_attribution = WikiMedia.attribution(WIKIDATA.IMAGE)
109 def _supplement(obj):
110 if not obj.first_name and not obj.last_name:
111 yield 'first_name', 'label'
114 name = f"{self.first_name} {self.last_name}"
115 if self.year_of_death is not None:
116 name += f' (zm. {self.year_of_death})'
119 def get_absolute_url(self):
120 return reverse("catalogue_author", args=[self.slug])
124 return f"{self.last_name}, {self.first_name}"
128 if self.year_of_death:
129 return self.year_of_death + 71
130 elif self.year_of_death == 0:
135 def generate_description(self):
136 t = render_to_string(
137 'catalogue/author_description.html',
142 def century_description(self, number):
163 def birth_century_description(self):
164 return self.century_description(self.century_of_birth)
166 def death_century_description(self):
167 return self.century_description(self.century_of_death)
170 class NotableBook(OrderableModel):
171 author = models.ForeignKey(Author, models.CASCADE)
172 book = models.ForeignKey('Book', models.CASCADE)
175 class Category(WikidataModel):
176 name = models.CharField(_("name"), max_length=255)
177 slug = models.SlugField(max_length=255, unique=True)
178 description = models.TextField(_("description"), blank=True, help_text=_('for publication'))
187 class Epoch(Category):
188 adjective_feminine_singular = models.CharField(
189 'przymiotnik pojedynczy żeński', max_length=255, blank=True,
190 help_text='twórczość … Adama Mickiewicza'
192 adjective_nonmasculine_plural = models.CharField(
193 'przymiotnik mnogi niemęskoosobowy', max_length=255, blank=True,
194 help_text='utwory … Adama Mickiewicza'
198 verbose_name = _('epoch')
199 verbose_name_plural = _('epochs')
202 class Genre(Category):
203 plural = models.CharField(
204 'liczba mnoga', max_length=255, blank=True,
205 help_text='dotyczy gatunków'
207 is_epoch_specific = models.BooleanField(
209 help_text='Po wskazaniu tego gatunku, dodanie epoki byłoby nadmiarowe, np. „dramat romantyczny”'
213 verbose_name = _('genre')
214 verbose_name_plural = _('genres')
217 class Kind(Category):
218 collective_noun = models.CharField(
219 'określenie zbiorowe', max_length=255, blank=True,
220 help_text='np. „Liryka” albo „Twórczość dramatyczna”'
224 verbose_name = _('kind')
225 verbose_name_plural = _('kinds')
228 class Book(WikidataModel):
229 slug = models.SlugField(max_length=255, blank=True, null=True, unique=True)
230 authors = models.ManyToManyField(Author, blank=True, verbose_name=_("authors"))
231 translators = models.ManyToManyField(
233 related_name="translated_book_set",
234 related_query_name="translated_book",
236 verbose_name=_("translators")
238 epochs = models.ManyToManyField(Epoch, blank=True, verbose_name=_("epochs"))
239 kinds = models.ManyToManyField(Kind, blank=True, verbose_name=_("kinds"))
240 genres = models.ManyToManyField(Genre, blank=True, verbose_name=_("genres"))
241 title = models.CharField(_("title"), max_length=255, blank=True)
242 language = models.CharField(_("language"), max_length=255, blank=True)
243 based_on = models.ForeignKey(
244 "self", models.PROTECT, related_name="translation", null=True, blank=True,
245 verbose_name=_("based on")
247 scans_source = models.CharField(_("scans source"), max_length=255, blank=True)
248 text_source = models.CharField(_("text source"), max_length=255, blank=True)
249 notes = models.TextField(_("notes"), blank=True, help_text=_('private'))
250 priority = models.PositiveSmallIntegerField(
252 default=0, choices=[(0, _("Low")), (1, _("Medium")), (2, _("High"))]
254 original_year = models.IntegerField(_('original publication year'), null=True, blank=True)
255 pd_year = models.IntegerField(_('year of entry into PD'), null=True, blank=True)
256 gazeta_link = models.CharField(_("gazeta link"), max_length=255, blank=True)
257 collections = models.ManyToManyField("Collection", blank=True, verbose_name=_("collections"))
259 estimated_chars = models.IntegerField(_("estimated number of characters"), null=True, blank=True)
260 estimated_verses = models.IntegerField(_("estimated number of verses"), null=True, blank=True)
261 estimate_source = models.CharField(_("source of estimates"), max_length=2048, blank=True)
263 free_license = models.BooleanField(_('free license'), default=False)
264 polona_missing = models.BooleanField(_('missing on Polona'), default=False)
266 monthly_views_reader = models.IntegerField(default=0)
267 monthly_views_page = models.IntegerField(default=0)
270 ordering = ("title",)
271 verbose_name = _('book')
272 verbose_name_plural = _('books')
275 authors = WIKIDATA.AUTHOR
276 translators = WIKIDATA.TRANSLATOR
277 title = WIKIDATA.TITLE
278 language = WIKIDATA.LANGUAGE
279 based_on = WIKIDATA.BASED_ON
280 original_year = WIKIDATA.PUBLICATION_DATE
281 notes = WikiMedia.append("description")
285 if self.original_year:
286 txt = f"{txt} ({self.original_year})"
287 astr = self.authors_str()
289 txt = f"{txt}, {astr}"
290 tstr = self.translators_str()
292 txt = f"{txt}, tłum. {tstr}"
295 def get_absolute_url(self):
296 return reverse("catalogue_book", args=[self.slug])
300 return f'https://wolnelektury.pl/katalog/lektura/{self.slug}/'
302 def authors_str(self):
305 return ", ".join(str(author) for author in self.authors.all())
306 authors_str.admin_order_field = 'authors__last_name'
307 authors_str.short_description = _('Author')
309 def translators_str(self):
312 return ", ".join(str(author) for author in self.translators.all())
313 translators_str.admin_order_field = 'translators__last_name'
314 translators_str.short_description = _('Translator')
316 def authors_first_names(self):
317 return ', '.join(a.first_name for a in self.authors.all())
319 def authors_last_names(self):
320 return ', '.join(a.last_name for a in self.authors.all())
322 def translators_first_names(self):
323 return ', '.join(a.first_name for a in self.translators.all())
325 def translators_last_names(self):
326 return ', '.join(a.last_name for a in self.translators.all())
328 def document_book__project(self):
329 b = self.document_books.first()
330 if b is None: return ''
331 if b.project is None: return ''
332 return b.project.name
336 return self.document_books.first().wldocument().book_info.audience or ''
340 def get_estimated_costs(self):
342 work_type: work_type.calculate(self)
343 for work_type in WorkType.objects.all()
346 def update_monthly_stats(self):
347 # Find publication date.
348 # By default, get previous 12 months.
349 this_month = date.today().replace(day=1)
350 cutoff = this_month.replace(year=this_month.year - 1)
353 # If the book was published later,
354 # find out the denominator.
355 pbr = apps.get_model('documents', 'BookPublishRecord').objects.filter(
356 book__catalogue_book=self).order_by('timestamp').first()
357 if pbr is not None and pbr.timestamp.date() > cutoff:
358 months = (this_month - pbr.timestamp.date()).days / 365 * 12
363 stats = self.bookmonthlystats_set.filter(date__gte=cutoff).aggregate(
364 views_page=models.Sum('views_page'),
365 views_reader=models.Sum('views_reader')
367 self.monthly_views_page = stats['views_page'] / months
368 self.monthly_views_reader = stats['views_reader'] / months
369 self.save(update_fields=['monthly_views_page', 'monthly_views_reader'])
372 def content_stats(self):
373 if hasattr(self, '_content_stats'):
374 return self._content_stats
376 stats = self.document_books.first().wldocument().get_statistics()['total']
377 except Exception as e:
379 self._content_stats = stats
382 chars = lambda self: self.content_stats.get('chars', '')
383 chars_with_fn = lambda self: self.content_stats.get('chars_with_fn', '')
384 words = lambda self: self.content_stats.get('words', '')
385 words_with_fn = lambda self: self.content_stats.get('words_with_fn', '')
386 verses = lambda self: self.content_stats.get('verses', '')
387 verses_with_fn = lambda self: self.content_stats.get('verses_with_fn', '')
388 chars_out_verse = lambda self: self.content_stats.get('chars_out_verse', '')
389 chars_out_verse_with_fn = lambda self: self.content_stats.get('chars_out_verse_with_fn', '')
391 class CollectionCategory(models.Model):
392 name = models.CharField(_("name"), max_length=255)
393 parent = models.ForeignKey('self', models.SET_NULL, related_name='children', null=True, blank=True, verbose_name=_("parent"))
394 notes = models.TextField(_("notes"), blank=True, help_text=_('private'))
397 ordering = ('parent__name', 'name')
398 verbose_name = _('collection category')
399 verbose_name_plural = _('collection categories')
403 return f"{self.parent} / {self.name}"
408 class Collection(models.Model):
409 name = models.CharField(_("name"), max_length=255)
410 slug = models.SlugField(max_length=255, unique=True)
411 category = models.ForeignKey(CollectionCategory, models.SET_NULL, null=True, blank=True, verbose_name=_("category"))
412 notes = models.TextField(_("notes"), blank=True, help_text=_('private'))
413 description = models.TextField(_("description"), blank=True)
416 ordering = ('category', 'name')
417 verbose_name = _('collection')
418 verbose_name_plural = _('collections')
422 return f"{self.category} / {self.name}"
426 def get_estimated_costs(self):
428 for book in self.book_set.all():
429 for k, v in book.get_estimated_costs().items():
432 for author in self.author_set.all():
433 for book in author.book_set.all():
434 for k, v in book.get_estimated_costs().items():
436 for book in author.translated_book_set.all():
437 for k, v in book.get_estimated_costs().items():
442 class WorkType(models.Model):
443 name = models.CharField(_("name"), max_length=255)
447 verbose_name = _('work type')
448 verbose_name_plural = _('work types')
450 def get_rate_for(self, book):
451 for workrate in self.workrate_set.all():
452 if workrate.matches(book):
455 def calculate(self, book):
456 workrate = self.get_rate_for(book)
457 if workrate is not None:
458 return workrate.calculate(book)
462 class WorkRate(models.Model):
463 priority = models.IntegerField(_("priority"), default=1)
464 per_normpage = models.DecimalField(_("per normalized page"), decimal_places=2, max_digits=6, null=True, blank=True)
465 per_verse = models.DecimalField(_("per verse"), decimal_places=2, max_digits=6, null=True, blank=True)
466 work_type = models.ForeignKey(WorkType, models.CASCADE, verbose_name=_("work type"))
467 epochs = models.ManyToManyField(Epoch, blank=True, verbose_name=_("epochs"))
468 kinds = models.ManyToManyField(Kind, blank=True, verbose_name=_("kinds"))
469 genres = models.ManyToManyField(Genre, blank=True, verbose_name=_("genres"))
470 collections = models.ManyToManyField(Collection, blank=True, verbose_name=_("collections"))
473 ordering = ('priority',)
474 verbose_name = _('work rate')
475 verbose_name_plural = _('work rates')
477 def matches(self, book):
478 for category in 'epochs', 'kinds', 'genres', 'collections':
479 oneof = getattr(self, category).all()
481 if not set(oneof).intersection(
482 getattr(book, category).all()):
486 def calculate(self, book):
488 if book.estimated_verses:
489 return book.estimated_verses * self.per_verse
490 elif self.per_normpage:
491 if book.estimated_chars:
492 return (decimal.Decimal(book.estimated_chars) / 1800 * self.per_normpage).quantize(decimal.Decimal('1.00'), rounding=decimal.ROUND_HALF_UP)
495 class Place(WikidataModel):
496 name = models.CharField(_('name'), max_length=255, blank=True)
497 locative = models.CharField(_('locative'), max_length=255, blank=True, help_text=_('in…'))
500 verbose_name = _('place')
501 verbose_name_plural = _('places')
510 class BookMonthlyStats(models.Model):
511 book = models.ForeignKey('catalogue.Book', models.CASCADE)
512 date = models.DateField()
513 views_reader = models.IntegerField(default=0)
514 views_page = models.IntegerField(default=0)
517 def build_for_month(cls, date):
518 date = date.replace(day=1)
521 date = date.isoformat()
522 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'
523 data = urlopen(url).read().decode('utf-16')
524 lines = data.split('\n')[1:]
526 m = re.match('^/katalog/lektura/([^,./]+)\.html,', line)
528 which = 'views_reader'
530 m = re.match('^/katalog/lektura/([^,./]+)/,', line)
535 _url, _uviews, views, _rest = line.split(',', 3)
538 book = Book.objects.get(slug=slug)
539 except Book.DoesNotExist:
542 cls.objects.update_or_create(
543 book=book, date=date,
544 defaults={which: views}
546 book.update_monthly_stats()