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"))
88 woblink = models.IntegerField(null=True, blank=True)
91 verbose_name = _('author')
92 verbose_name_plural = _('authors')
93 ordering = ("last_name", "first_name", "year_of_death")
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")
107 photo = WikiMedia.download(WIKIDATA.IMAGE)
108 photo_source = WikiMedia.descriptionurl(WIKIDATA.IMAGE)
109 photo_attribution = WikiMedia.attribution(WIKIDATA.IMAGE)
111 def _supplement(obj):
112 if not obj.first_name and not obj.last_name:
113 yield 'first_name', 'label'
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})'
121 def get_absolute_url(self):
122 return reverse("catalogue_author", args=[self.slug])
125 def get_by_literal(cls, literal):
126 names = literal.split(',', 1)
127 names = [n.strip() for n in names]
129 return cls.objects.filter(last_name=names[0], first_name=names[1]).first()
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()
138 return f"{self.last_name}, {self.first_name}"
142 if self.year_of_death:
143 return self.year_of_death + 71
144 elif self.year_of_death == 0:
149 def generate_description(self):
150 t = render_to_string(
151 'catalogue/author_description.html',
156 def century_description(self, number):
177 def birth_century_description(self):
178 return self.century_description(self.century_of_birth)
180 def death_century_description(self):
181 return self.century_description(self.century_of_death)
183 def year_description(self, number):
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)
197 class NotableBook(OrderableModel):
198 author = models.ForeignKey(Author, models.CASCADE)
199 book = models.ForeignKey('Book', models.CASCADE)
202 return self.book.title
205 class Category(WikidataModel):
206 name = models.CharField(_("name"), max_length=255)
207 slug = models.SlugField(max_length=255, unique=True)
208 description = models.TextField(_("description"), blank=True, help_text=_('for publication'))
217 class Epoch(Category):
218 adjective_feminine_singular = models.CharField(
219 'przymiotnik pojedynczy żeński', max_length=255, blank=True,
220 help_text='twórczość … Adama Mickiewicza'
222 adjective_nonmasculine_plural = models.CharField(
223 'przymiotnik mnogi niemęskoosobowy', max_length=255, blank=True,
224 help_text='utwory … Adama Mickiewicza'
228 verbose_name = _('epoch')
229 verbose_name_plural = _('epochs')
232 class Genre(Category):
233 thema = models.CharField(
234 max_length=32, blank=True,
235 help_text='Odpowiadający kwalifikator Thema.'
237 plural = models.CharField(
238 'liczba mnoga', max_length=255, blank=True,
240 is_epoch_specific = models.BooleanField(
242 help_text='Po wskazaniu tego gatunku, dodanie epoki byłoby nadmiarowe, np. „dramat romantyczny”'
246 verbose_name = _('genre')
247 verbose_name_plural = _('genres')
250 class Kind(Category):
251 collective_noun = models.CharField(
252 'określenie zbiorowe', max_length=255, blank=True,
253 help_text='np. „Liryka” albo „Twórczość dramatyczna”'
257 verbose_name = _('kind')
258 verbose_name_plural = _('kinds')
261 class Book(WikidataModel):
262 slug = models.SlugField(max_length=255, blank=True, null=True, unique=True)
263 authors = models.ManyToManyField(Author, blank=True, verbose_name=_("authors"))
264 translators = models.ManyToManyField(
266 related_name="translated_book_set",
267 related_query_name="translated_book",
269 verbose_name=_("translators")
271 epochs = models.ManyToManyField(Epoch, blank=True, verbose_name=_("epochs"))
272 kinds = models.ManyToManyField(Kind, blank=True, verbose_name=_("kinds"))
273 genres = models.ManyToManyField(Genre, blank=True, verbose_name=_("genres"))
274 title = models.CharField(_("title"), max_length=255, blank=True)
275 language = models.CharField(_("language"), max_length=255, blank=True)
276 based_on = models.ForeignKey(
277 "self", models.PROTECT, related_name="translation", null=True, blank=True,
278 verbose_name=_("based on")
280 scans_source = models.CharField(_("scans source"), max_length=255, blank=True)
281 text_source = models.CharField(_("text source"), max_length=255, blank=True)
282 notes = models.TextField(_("notes"), blank=True, help_text=_('private'))
283 priority = models.PositiveSmallIntegerField(
285 default=0, choices=[(0, _("Low")), (1, _("Medium")), (2, _("High"))]
287 original_year = models.IntegerField(_('original publication year'), null=True, blank=True)
288 pd_year = models.IntegerField(_('year of entry into PD'), null=True, blank=True)
289 plwiki = models.CharField(blank=True, max_length=255)
290 gazeta_link = models.CharField(_("gazeta link"), max_length=255, blank=True)
291 collections = models.ManyToManyField("Collection", blank=True, verbose_name=_("collections"))
293 estimated_chars = models.IntegerField(_("estimated number of characters"), null=True, blank=True)
294 estimated_verses = models.IntegerField(_("estimated number of verses"), null=True, blank=True)
295 estimate_source = models.CharField(_("source of estimates"), max_length=2048, blank=True)
297 free_license = models.BooleanField(_('free license'), default=False)
298 polona_missing = models.BooleanField(_('missing on Polona'), default=False)
300 monthly_views_reader = models.IntegerField(default=0)
301 monthly_views_page = models.IntegerField(default=0)
304 ordering = ("title",)
305 verbose_name = _('book')
306 verbose_name_plural = _('books')
310 authors = WIKIDATA.AUTHOR
311 translators = WIKIDATA.TRANSLATOR
312 title = WIKIDATA.TITLE
313 language = WIKIDATA.LANGUAGE
314 based_on = WIKIDATA.BASED_ON
315 original_year = WIKIDATA.PUBLICATION_DATE
316 notes = WikiMedia.append("description")
320 if self.original_year:
321 txt = f"{txt} ({self.original_year})"
322 astr = self.authors_str()
324 txt = f"{txt}, {astr}"
325 tstr = self.translators_str()
327 txt = f"{txt}, tłum. {tstr}"
330 def get_absolute_url(self):
331 return reverse("catalogue_book", args=[self.slug])
333 def is_text_public(self):
334 return self.free_license or (self.pd_year is not None and self.pd_year <= date.today().year)
336 def audio_status(self):
341 return f'https://wolnelektury.pl/katalog/lektura/{self.slug}/'
343 def authors_str(self):
346 return ", ".join(str(author) for author in self.authors.all())
347 authors_str.admin_order_field = 'authors__last_name'
348 authors_str.short_description = _('Author')
350 def translators_str(self):
353 return ", ".join(str(author) for author in self.translators.all())
354 translators_str.admin_order_field = 'translators__last_name'
355 translators_str.short_description = _('Translator')
357 def authors_first_names(self):
358 return ', '.join(a.first_name for a in self.authors.all())
360 def authors_last_names(self):
361 return ', '.join(a.last_name for a in self.authors.all())
363 def translators_first_names(self):
364 return ', '.join(a.first_name for a in self.translators.all())
366 def translators_last_names(self):
367 return ', '.join(a.last_name for a in self.translators.all())
369 def document_book__project(self):
370 b = self.document_books.first()
371 if b is None: return ''
372 if b.project is None: return ''
373 return b.project.name
377 return self.document_books.first().wldocument().book_info.audience or ''
381 def get_estimated_costs(self):
383 work_type: work_type.calculate(self)
384 for work_type in WorkType.objects.all()
387 def scans_gallery(self):
388 bs = self.booksource_set.first()
393 def is_published(self):
394 return any(b.is_published() for b in self.document_books.all())
396 def update_monthly_stats(self):
397 # Find publication date.
398 # By default, get previous 12 months.
399 this_month = date.today().replace(day=1)
400 cutoff = this_month.replace(year=this_month.year - 1)
403 # If the book was published later,
404 # find out the denominator.
405 pbr = apps.get_model('documents', 'BookPublishRecord').objects.filter(
406 book__catalogue_book=self).order_by('timestamp').first()
407 if pbr is not None and pbr.timestamp.date() > cutoff:
408 months = (this_month - pbr.timestamp.date()).days / 365 * 12
413 stats = self.bookmonthlystats_set.filter(date__gte=cutoff).aggregate(
414 views_page=models.Sum('views_page'),
415 views_reader=models.Sum('views_reader')
417 self.monthly_views_page = stats['views_page'] / months
418 self.monthly_views_reader = stats['views_reader'] / months
419 self.save(update_fields=['monthly_views_page', 'monthly_views_reader'])
422 def content_stats(self):
423 if hasattr(self, '_content_stats'):
424 return self._content_stats
426 stats = self.document_books.first().wldocument(librarian2=True).get_statistics()['total']
427 except Exception as e:
429 self._content_stats = stats
432 chars = lambda self: self.content_stats.get('chars', '')
433 chars_with_fn = lambda self: self.content_stats.get('chars_with_fn', '')
434 words = lambda self: self.content_stats.get('words', '')
435 words_with_fn = lambda self: self.content_stats.get('words_with_fn', '')
436 verses = lambda self: self.content_stats.get('verses', '')
437 verses_with_fn = lambda self: self.content_stats.get('verses_with_fn', '')
438 chars_out_verse = lambda self: self.content_stats.get('chars_out_verse', '')
439 chars_out_verse_with_fn = lambda self: self.content_stats.get('chars_out_verse_with_fn', '')
441 class CollectionCategory(models.Model):
442 name = models.CharField(_("name"), max_length=255)
443 parent = models.ForeignKey('self', models.SET_NULL, related_name='children', null=True, blank=True, verbose_name=_("parent"))
444 notes = models.TextField(_("notes"), blank=True, help_text=_('private'))
447 ordering = ('parent__name', 'name')
448 verbose_name = _('collection category')
449 verbose_name_plural = _('collection categories')
453 return f"{self.parent} / {self.name}"
458 class Collection(models.Model):
459 name = models.CharField(_("name"), max_length=255)
460 slug = models.SlugField(max_length=255, unique=True)
461 category = models.ForeignKey(CollectionCategory, models.SET_NULL, null=True, blank=True, verbose_name=_("category"))
462 notes = models.TextField(_("notes"), blank=True, help_text=_('private'))
463 description = models.TextField(_("description"), blank=True)
466 ordering = ('category', 'name')
467 verbose_name = _('collection')
468 verbose_name_plural = _('collections')
472 return f"{self.category} / {self.name}"
476 def get_estimated_costs(self):
478 for book in self.book_set.all():
479 for k, v in book.get_estimated_costs().items():
482 for author in self.author_set.all():
483 for book in author.book_set.all():
484 for k, v in book.get_estimated_costs().items():
486 for book in author.translated_book_set.all():
487 for k, v in book.get_estimated_costs().items():
492 class WorkType(models.Model):
493 name = models.CharField(_("name"), max_length=255)
497 verbose_name = _('work type')
498 verbose_name_plural = _('work types')
500 def get_rate_for(self, book):
501 for workrate in self.workrate_set.all():
502 if workrate.matches(book):
505 def calculate(self, book):
506 workrate = self.get_rate_for(book)
507 if workrate is not None:
508 return workrate.calculate(book)
512 class WorkRate(models.Model):
513 priority = models.IntegerField(_("priority"), default=1)
514 per_normpage = models.DecimalField(_("per normalized page"), decimal_places=2, max_digits=6, null=True, blank=True)
515 per_verse = models.DecimalField(_("per verse"), decimal_places=2, max_digits=6, null=True, blank=True)
516 work_type = models.ForeignKey(WorkType, models.CASCADE, verbose_name=_("work type"))
517 epochs = models.ManyToManyField(Epoch, blank=True, verbose_name=_("epochs"))
518 kinds = models.ManyToManyField(Kind, blank=True, verbose_name=_("kinds"))
519 genres = models.ManyToManyField(Genre, blank=True, verbose_name=_("genres"))
520 collections = models.ManyToManyField(Collection, blank=True, verbose_name=_("collections"))
523 ordering = ('priority',)
524 verbose_name = _('work rate')
525 verbose_name_plural = _('work rates')
527 def matches(self, book):
528 for category in 'epochs', 'kinds', 'genres', 'collections':
529 oneof = getattr(self, category).all()
531 if not set(oneof).intersection(
532 getattr(book, category).all()):
536 def calculate(self, book):
538 if book.estimated_verses:
539 return book.estimated_verses * self.per_verse
540 elif self.per_normpage:
541 if book.estimated_chars:
542 return (decimal.Decimal(book.estimated_chars) / 1800 * self.per_normpage).quantize(decimal.Decimal('1.00'), rounding=decimal.ROUND_HALF_UP)
545 class Place(WikidataModel):
546 name = models.CharField(_('name'), max_length=255, blank=True)
547 locative = models.CharField(_('locative'), max_length=255, blank=True, help_text=_('in…'))
550 verbose_name = _('place')
551 verbose_name_plural = _('places')
560 class BookMonthlyStats(models.Model):
561 book = models.ForeignKey('catalogue.Book', models.CASCADE)
562 date = models.DateField()
563 views_reader = models.IntegerField(default=0)
564 views_page = models.IntegerField(default=0)
567 def build_for_month(cls, date):
568 date = date.replace(day=1)
571 date = date.isoformat()
572 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'
573 data = urlopen(url).read().decode('utf-16')
574 lines = data.split('\n')[1:]
576 m = re.match('^/katalog/lektura/([^,./]+)\.html,', line)
578 which = 'views_reader'
580 m = re.match('^/katalog/lektura/([^,./]+)/,', line)
585 _url, _uviews, views, _rest = line.split(',', 3)
588 book = Book.objects.get(slug=slug)
589 except Book.DoesNotExist:
592 cls.objects.update_or_create(
593 book=book, date=date,
594 defaults={which: views}
596 book.update_monthly_stats()
599 class Thema(models.Model):
600 code = models.CharField(
601 max_length=128, unique=True,
602 help_text='Używamy rozszerzenia <code>.WL-</code> do oznaczania własnych kodów.<br> '
603 'Przykładowo, w przypadku potrzeby stworzenia nowej kategorii „insurekcja kościuszkowska”, '
604 'można by ją utworzyć jako 3MLQ‑PL‑A.WL-A, czyli w ramach już istniejącej wyższej kategorii 3MLQ‑PL‑A „rozbiory Polski”.',
606 name = models.CharField(max_length=1024)
607 slug = models.SlugField(
608 max_length=255, null=True, blank=True, unique=True,
609 help_text='Element adresu na WL, w postaci: /tag/slug/. Można zmieniać.'
611 plural = models.CharField(
612 'liczba mnoga', max_length=255, blank=True,
614 description = models.TextField(blank=True)
615 public_description = models.TextField(blank=True)
616 usable = models.BooleanField()
617 usable_as_main = models.BooleanField(default=False)
618 hidden = models.BooleanField(default=False)
619 woblink_category = models.IntegerField(null=True, blank=True)
623 verbose_name_plural = 'Thema'
626 class Audience(models.Model):
627 code = models.CharField(
628 max_length=128, unique=True,
629 help_text='Techniczny identifyikator. W miarę możliwości nie należy zmieniać.'
631 name = models.CharField(
633 help_text='W formie: „dla … (kogo?)”'
635 slug = models.SlugField(
636 max_length=255, null=True, blank=True, unique=True,
637 help_text='Element adresu na WL, w postaci: /dla/slug/. Można zmieniać.'
639 description = models.TextField(blank=True)
640 thema = models.CharField(
641 max_length=32, blank=True,
642 help_text='Odpowiadający kwalifikator Thema.'
644 woblink = models.IntegerField(null=True, blank=True)