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)
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'
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'
51 status = models.PositiveSmallIntegerField(
62 notes = models.TextField(_("notes"), blank=True, help_text=_('private'))
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)
71 description = models.TextField(_("description"), blank=True, help_text=_('for publication'))
73 priority = models.PositiveSmallIntegerField(
75 default=0, choices=[(0, _("Low")), (1, _("Medium")), (2, _("High"))]
77 collections = models.ManyToManyField("Collection", blank=True, verbose_name=_("collections"))
80 verbose_name = _('author')
81 verbose_name_plural = _('authors')
82 ordering = ("last_name", "first_name", "year_of_death")
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")
96 photo = WikiMedia.download(WIKIDATA.IMAGE)
97 photo_source = WikiMedia.descriptionurl(WIKIDATA.IMAGE)
98 photo_attribution = WikiMedia.attribution(WIKIDATA.IMAGE)
100 def _supplement(obj):
101 if not obj.first_name and not obj.last_name:
102 yield 'first_name', 'label'
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})'
110 def get_absolute_url(self):
111 return reverse("catalogue_author", args=[self.slug])
115 return f"{self.last_name}, {self.first_name}"
119 if self.year_of_death:
120 return self.year_of_death + 71
121 elif self.year_of_death == 0:
126 def generate_description(self):
127 t = render_to_string(
128 'catalogue/author_description.html',
133 class NotableBook(OrderableModel):
134 author = models.ForeignKey(Author, models.CASCADE)
135 book = models.ForeignKey('Book', models.CASCADE)
138 class Category(WikidataModel):
139 name = models.CharField(_("name"), max_length=255)
140 slug = models.SlugField(max_length=255, unique=True)
149 class Epoch(Category):
150 adjective_feminine_singular = models.CharField(
151 'przymiotnik pojedynczy żeński', max_length=255, blank=True,
152 help_text='twórczość … Adama Mickiewicza'
154 adjective_nonmasculine_plural = models.CharField(
155 'przymiotnik mnogi niemęskoosobowy', max_length=255, blank=True,
156 help_text='utwory … Adama Mickiewicza'
160 verbose_name = _('epoch')
161 verbose_name_plural = _('epochs')
164 class Genre(Category):
165 plural = models.CharField(
166 'liczba mnoga', max_length=255, blank=True,
167 help_text='dotyczy gatunków'
169 is_epoch_specific = models.BooleanField(
171 help_text='Po wskazaniu tego gatunku, dodanie epoki byłoby nadmiarowe, np. „dramat romantyczny”'
175 verbose_name = _('genre')
176 verbose_name_plural = _('genres')
179 class Kind(Category):
180 collective_noun = models.CharField(
181 'określenie zbiorowe', max_length=255, blank=True,
182 help_text='np. „Liryka” albo „Twórczość dramatyczna”'
186 verbose_name = _('kind')
187 verbose_name_plural = _('kinds')
190 class Book(WikidataModel):
191 slug = models.SlugField(max_length=255, blank=True, null=True, unique=True)
192 authors = models.ManyToManyField(Author, blank=True, verbose_name=_("authors"))
193 translators = models.ManyToManyField(
195 related_name="translated_book_set",
196 related_query_name="translated_book",
198 verbose_name=_("translators")
200 epochs = models.ManyToManyField(Epoch, blank=True, verbose_name=_("epochs"))
201 kinds = models.ManyToManyField(Kind, blank=True, verbose_name=_("kinds"))
202 genres = models.ManyToManyField(Genre, blank=True, verbose_name=_("genres"))
203 title = models.CharField(_("title"), max_length=255, blank=True)
204 language = models.CharField(_("language"), max_length=255, blank=True)
205 based_on = models.ForeignKey(
206 "self", models.PROTECT, related_name="translation", null=True, blank=True,
207 verbose_name=_("based on")
209 scans_source = models.CharField(_("scans source"), max_length=255, blank=True)
210 text_source = models.CharField(_("text source"), max_length=255, blank=True)
211 notes = models.TextField(_("notes"), blank=True, help_text=_('private'))
212 priority = models.PositiveSmallIntegerField(
214 default=0, choices=[(0, _("Low")), (1, _("Medium")), (2, _("High"))]
216 original_year = models.IntegerField(_('original publication year'), null=True, blank=True)
217 pd_year = models.IntegerField(_('year of entry into PD'), null=True, blank=True)
218 gazeta_link = models.CharField(_("gazeta link"), max_length=255, blank=True)
219 collections = models.ManyToManyField("Collection", blank=True, verbose_name=_("collections"))
221 estimated_chars = models.IntegerField(_("estimated number of characters"), null=True, blank=True)
222 estimated_verses = models.IntegerField(_("estimated number of verses"), null=True, blank=True)
223 estimate_source = models.CharField(_("source of estimates"), max_length=2048, blank=True)
225 free_license = models.BooleanField(_('free license'), default=False)
226 polona_missing = models.BooleanField(_('missing on Polona'), default=False)
228 monthly_views_reader = models.IntegerField(default=0)
229 monthly_views_page = models.IntegerField(default=0)
232 ordering = ("title",)
233 verbose_name = _('book')
234 verbose_name_plural = _('books')
237 authors = WIKIDATA.AUTHOR
238 translators = WIKIDATA.TRANSLATOR
239 title = WIKIDATA.TITLE
240 language = WIKIDATA.LANGUAGE
241 based_on = WIKIDATA.BASED_ON
242 original_year = WIKIDATA.PUBLICATION_DATE
243 notes = WikiMedia.append("description")
247 if self.original_year:
248 txt = f"{txt} ({self.original_year})"
249 astr = self.authors_str()
251 txt = f"{txt}, {astr}"
252 tstr = self.translators_str()
254 txt = f"{txt}, tłum. {tstr}"
257 def get_absolute_url(self):
258 return reverse("catalogue_book", args=[self.slug])
262 return f'https://wolnelektury.pl/katalog/lektura/{self.slug}/'
264 def authors_str(self):
267 return ", ".join(str(author) for author in self.authors.all())
268 authors_str.admin_order_field = 'authors__last_name'
269 authors_str.short_description = _('Author')
271 def translators_str(self):
274 return ", ".join(str(author) for author in self.translators.all())
275 translators_str.admin_order_field = 'translators__last_name'
276 translators_str.short_description = _('Translator')
278 def authors_first_names(self):
279 return ', '.join(a.first_name for a in self.authors.all())
281 def authors_last_names(self):
282 return ', '.join(a.last_name for a in self.authors.all())
284 def translators_first_names(self):
285 return ', '.join(a.first_name for a in self.translators.all())
287 def translators_last_names(self):
288 return ', '.join(a.last_name for a in self.translators.all())
290 def get_estimated_costs(self):
292 work_type: work_type.calculate(self)
293 for work_type in WorkType.objects.all()
296 def update_monthly_stats(self):
297 # Find publication date.
298 # By default, get previous 12 months.
299 this_month = date.today().replace(day=1)
300 cutoff = this_month.replace(year=this_month.year - 1)
303 # If the book was published later,
304 # find out the denominator.
305 pbr = apps.get_model('documents', 'BookPublishRecord').objects.filter(
306 book__catalogue_book=self).order_by('timestamp').first()
307 if pbr is not None and pbr.timestamp.date() > cutoff:
308 months = (this_month - pbr.timestamp.date()).days / 365 * 12
310 stats = self.bookmonthlystats_set.filter(date__gte=cutoff).aggregate(
311 views_page=models.Sum('views_page'),
312 views_reader=models.Sum('views_reader')
314 self.monthly_views_page = stats['views_page'] / months
315 self.monthly_views_reader = stats['views_reader'] / months
316 self.save(update_fields=['monthly_views_page', 'monthly_views_reader'])
319 def content_stats(self):
320 if hasattr(self, '_content_stats'):
321 return self._content_stats
323 stats = self.document_books.first().wldocument().get_statistics()['total']
324 except Exception as e:
326 self._content_stats = stats
329 chars = lambda self: self.content_stats.get('chars', '')
330 chars_with_fn = lambda self: self.content_stats.get('chars_with_fn', '')
331 words = lambda self: self.content_stats.get('words', '')
332 words_with_fn = lambda self: self.content_stats.get('words_with_fn', '')
333 verses = lambda self: self.content_stats.get('verses', '')
334 verses_with_fn = lambda self: self.content_stats.get('verses_with_fn', '')
335 chars_out_verse = lambda self: self.content_stats.get('chars_out_verse', '')
336 chars_out_verse_with_fn = lambda self: self.content_stats.get('chars_out_verse_with_fn', '')
338 class CollectionCategory(models.Model):
339 name = models.CharField(_("name"), max_length=255)
340 parent = models.ForeignKey('self', models.SET_NULL, related_name='children', null=True, blank=True, verbose_name=_("parent"))
341 notes = models.TextField(_("notes"), blank=True, help_text=_('private'))
344 ordering = ('parent__name', 'name')
345 verbose_name = _('collection category')
346 verbose_name_plural = _('collection categories')
350 return f"{self.parent} / {self.name}"
355 class Collection(models.Model):
356 name = models.CharField(_("name"), max_length=255)
357 slug = models.SlugField(max_length=255, unique=True)
358 category = models.ForeignKey(CollectionCategory, models.SET_NULL, null=True, blank=True, verbose_name=_("category"))
359 notes = models.TextField(_("notes"), blank=True, help_text=_('private'))
360 description = models.TextField(_("description"), blank=True)
363 ordering = ('category', 'name')
364 verbose_name = _('collection')
365 verbose_name_plural = _('collections')
369 return f"{self.category} / {self.name}"
373 def get_estimated_costs(self):
375 for book in self.book_set.all():
376 for k, v in book.get_estimated_costs().items():
379 for author in self.author_set.all():
380 for book in author.book_set.all():
381 for k, v in book.get_estimated_costs().items():
383 for book in author.translated_book_set.all():
384 for k, v in book.get_estimated_costs().items():
389 class WorkType(models.Model):
390 name = models.CharField(_("name"), max_length=255)
394 verbose_name = _('work type')
395 verbose_name_plural = _('work types')
397 def get_rate_for(self, book):
398 for workrate in self.workrate_set.all():
399 if workrate.matches(book):
402 def calculate(self, book):
403 workrate = self.get_rate_for(book)
404 if workrate is not None:
405 return workrate.calculate(book)
409 class WorkRate(models.Model):
410 priority = models.IntegerField(_("priority"), default=1)
411 per_normpage = models.DecimalField(_("per normalized page"), decimal_places=2, max_digits=6, null=True, blank=True)
412 per_verse = models.DecimalField(_("per verse"), decimal_places=2, max_digits=6, null=True, blank=True)
413 work_type = models.ForeignKey(WorkType, models.CASCADE, verbose_name=_("work type"))
414 epochs = models.ManyToManyField(Epoch, blank=True, verbose_name=_("epochs"))
415 kinds = models.ManyToManyField(Kind, blank=True, verbose_name=_("kinds"))
416 genres = models.ManyToManyField(Genre, blank=True, verbose_name=_("genres"))
417 collections = models.ManyToManyField(Collection, blank=True, verbose_name=_("collections"))
420 ordering = ('priority',)
421 verbose_name = _('work rate')
422 verbose_name_plural = _('work rates')
424 def matches(self, book):
425 for category in 'epochs', 'kinds', 'genres', 'collections':
426 oneof = getattr(self, category).all()
428 if not set(oneof).intersection(
429 getattr(book, category).all()):
433 def calculate(self, book):
435 if book.estimated_verses:
436 return book.estimated_verses * self.per_verse
437 elif self.per_normpage:
438 if book.estimated_chars:
439 return (decimal.Decimal(book.estimated_chars) / 1800 * self.per_normpage).quantize(decimal.Decimal('1.00'), rounding=decimal.ROUND_HALF_UP)
442 class Place(WikidataModel):
443 name = models.CharField(_('name'), max_length=255, blank=True)
444 locative = models.CharField(_('locative'), max_length=255, blank=True, help_text=_('in…'))
447 verbose_name = _('place')
448 verbose_name_plural = _('places')
457 class BookMonthlyStats(models.Model):
458 book = models.ForeignKey('catalogue.Book', models.CASCADE)
459 date = models.DateField()
460 views_reader = models.IntegerField(default=0)
461 views_page = models.IntegerField(default=0)
464 def build_for_month(cls, date):
465 date = date.replace(day=1)
468 date = date.isoformat()
469 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'
470 data = urlopen(url).read().decode('utf-16')
471 lines = data.split('\n')[1:]
473 m = re.match('^/katalog/lektura/([^,./]+)\.html,', line)
475 which = 'views_reader'
477 m = re.match('^/katalog/lektura/([^,./]+)/,', line)
482 _url, _uviews, views, _rest = line.split(',', 3)
485 book = Book.objects.get(slug=slug)
486 except Book.DoesNotExist:
489 cls.objects.update_or_create(
490 book=book, date=date,
491 defaults={which: views}
493 book.update_monthly_stats()