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)
141 description = models.TextField(_("description"), blank=True, help_text=_('for publication'))
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'
155 adjective_nonmasculine_plural = models.CharField(
156 'przymiotnik mnogi niemęskoosobowy', max_length=255, blank=True,
157 help_text='utwory … Adama Mickiewicza'
161 verbose_name = _('epoch')
162 verbose_name_plural = _('epochs')
165 class Genre(Category):
166 plural = models.CharField(
167 'liczba mnoga', max_length=255, blank=True,
168 help_text='dotyczy gatunków'
170 is_epoch_specific = models.BooleanField(
172 help_text='Po wskazaniu tego gatunku, dodanie epoki byłoby nadmiarowe, np. „dramat romantyczny”'
176 verbose_name = _('genre')
177 verbose_name_plural = _('genres')
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”'
187 verbose_name = _('kind')
188 verbose_name_plural = _('kinds')
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(
196 related_name="translated_book_set",
197 related_query_name="translated_book",
199 verbose_name=_("translators")
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")
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(
215 default=0, choices=[(0, _("Low")), (1, _("Medium")), (2, _("High"))]
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"))
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)
226 free_license = models.BooleanField(_('free license'), default=False)
227 polona_missing = models.BooleanField(_('missing on Polona'), default=False)
229 monthly_views_reader = models.IntegerField(default=0)
230 monthly_views_page = models.IntegerField(default=0)
233 ordering = ("title",)
234 verbose_name = _('book')
235 verbose_name_plural = _('books')
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")
248 if self.original_year:
249 txt = f"{txt} ({self.original_year})"
250 astr = self.authors_str()
252 txt = f"{txt}, {astr}"
253 tstr = self.translators_str()
255 txt = f"{txt}, tłum. {tstr}"
258 def get_absolute_url(self):
259 return reverse("catalogue_book", args=[self.slug])
263 return f'https://wolnelektury.pl/katalog/lektura/{self.slug}/'
265 def authors_str(self):
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')
272 def translators_str(self):
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')
279 def authors_first_names(self):
280 return ', '.join(a.first_name for a in self.authors.all())
282 def authors_last_names(self):
283 return ', '.join(a.last_name for a in self.authors.all())
285 def translators_first_names(self):
286 return ', '.join(a.first_name for a in self.translators.all())
288 def translators_last_names(self):
289 return ', '.join(a.last_name for a in self.translators.all())
291 def document_book__project(self):
292 b = self.document_books.first()
293 if b is None: return ''
294 if b.project is None: return ''
295 return b.project.name
297 def get_estimated_costs(self):
299 work_type: work_type.calculate(self)
300 for work_type in WorkType.objects.all()
303 def update_monthly_stats(self):
304 # Find publication date.
305 # By default, get previous 12 months.
306 this_month = date.today().replace(day=1)
307 cutoff = this_month.replace(year=this_month.year - 1)
310 # If the book was published later,
311 # find out the denominator.
312 pbr = apps.get_model('documents', 'BookPublishRecord').objects.filter(
313 book__catalogue_book=self).order_by('timestamp').first()
314 if pbr is not None and pbr.timestamp.date() > cutoff:
315 months = (this_month - pbr.timestamp.date()).days / 365 * 12
317 stats = self.bookmonthlystats_set.filter(date__gte=cutoff).aggregate(
318 views_page=models.Sum('views_page'),
319 views_reader=models.Sum('views_reader')
321 self.monthly_views_page = stats['views_page'] / months
322 self.monthly_views_reader = stats['views_reader'] / months
323 self.save(update_fields=['monthly_views_page', 'monthly_views_reader'])
326 def content_stats(self):
327 if hasattr(self, '_content_stats'):
328 return self._content_stats
330 stats = self.document_books.first().wldocument().get_statistics()['total']
331 except Exception as e:
333 self._content_stats = stats
336 chars = lambda self: self.content_stats.get('chars', '')
337 chars_with_fn = lambda self: self.content_stats.get('chars_with_fn', '')
338 words = lambda self: self.content_stats.get('words', '')
339 words_with_fn = lambda self: self.content_stats.get('words_with_fn', '')
340 verses = lambda self: self.content_stats.get('verses', '')
341 verses_with_fn = lambda self: self.content_stats.get('verses_with_fn', '')
342 chars_out_verse = lambda self: self.content_stats.get('chars_out_verse', '')
343 chars_out_verse_with_fn = lambda self: self.content_stats.get('chars_out_verse_with_fn', '')
345 class CollectionCategory(models.Model):
346 name = models.CharField(_("name"), max_length=255)
347 parent = models.ForeignKey('self', models.SET_NULL, related_name='children', null=True, blank=True, verbose_name=_("parent"))
348 notes = models.TextField(_("notes"), blank=True, help_text=_('private'))
351 ordering = ('parent__name', 'name')
352 verbose_name = _('collection category')
353 verbose_name_plural = _('collection categories')
357 return f"{self.parent} / {self.name}"
362 class Collection(models.Model):
363 name = models.CharField(_("name"), max_length=255)
364 slug = models.SlugField(max_length=255, unique=True)
365 category = models.ForeignKey(CollectionCategory, models.SET_NULL, null=True, blank=True, verbose_name=_("category"))
366 notes = models.TextField(_("notes"), blank=True, help_text=_('private'))
367 description = models.TextField(_("description"), blank=True)
370 ordering = ('category', 'name')
371 verbose_name = _('collection')
372 verbose_name_plural = _('collections')
376 return f"{self.category} / {self.name}"
380 def get_estimated_costs(self):
382 for book in self.book_set.all():
383 for k, v in book.get_estimated_costs().items():
386 for author in self.author_set.all():
387 for book in author.book_set.all():
388 for k, v in book.get_estimated_costs().items():
390 for book in author.translated_book_set.all():
391 for k, v in book.get_estimated_costs().items():
396 class WorkType(models.Model):
397 name = models.CharField(_("name"), max_length=255)
401 verbose_name = _('work type')
402 verbose_name_plural = _('work types')
404 def get_rate_for(self, book):
405 for workrate in self.workrate_set.all():
406 if workrate.matches(book):
409 def calculate(self, book):
410 workrate = self.get_rate_for(book)
411 if workrate is not None:
412 return workrate.calculate(book)
416 class WorkRate(models.Model):
417 priority = models.IntegerField(_("priority"), default=1)
418 per_normpage = models.DecimalField(_("per normalized page"), decimal_places=2, max_digits=6, null=True, blank=True)
419 per_verse = models.DecimalField(_("per verse"), decimal_places=2, max_digits=6, null=True, blank=True)
420 work_type = models.ForeignKey(WorkType, models.CASCADE, verbose_name=_("work type"))
421 epochs = models.ManyToManyField(Epoch, blank=True, verbose_name=_("epochs"))
422 kinds = models.ManyToManyField(Kind, blank=True, verbose_name=_("kinds"))
423 genres = models.ManyToManyField(Genre, blank=True, verbose_name=_("genres"))
424 collections = models.ManyToManyField(Collection, blank=True, verbose_name=_("collections"))
427 ordering = ('priority',)
428 verbose_name = _('work rate')
429 verbose_name_plural = _('work rates')
431 def matches(self, book):
432 for category in 'epochs', 'kinds', 'genres', 'collections':
433 oneof = getattr(self, category).all()
435 if not set(oneof).intersection(
436 getattr(book, category).all()):
440 def calculate(self, book):
442 if book.estimated_verses:
443 return book.estimated_verses * self.per_verse
444 elif self.per_normpage:
445 if book.estimated_chars:
446 return (decimal.Decimal(book.estimated_chars) / 1800 * self.per_normpage).quantize(decimal.Decimal('1.00'), rounding=decimal.ROUND_HALF_UP)
449 class Place(WikidataModel):
450 name = models.CharField(_('name'), max_length=255, blank=True)
451 locative = models.CharField(_('locative'), max_length=255, blank=True, help_text=_('in…'))
454 verbose_name = _('place')
455 verbose_name_plural = _('places')
464 class BookMonthlyStats(models.Model):
465 book = models.ForeignKey('catalogue.Book', models.CASCADE)
466 date = models.DateField()
467 views_reader = models.IntegerField(default=0)
468 views_page = models.IntegerField(default=0)
471 def build_for_month(cls, date):
472 date = date.replace(day=1)
475 date = date.isoformat()
476 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'
477 data = urlopen(url).read().decode('utf-16')
478 lines = data.split('\n')[1:]
480 m = re.match('^/katalog/lektura/([^,./]+)\.html,', line)
482 which = 'views_reader'
484 m = re.match('^/katalog/lektura/([^,./]+)/,', line)
489 _url, _uviews, views, _rest = line.split(',', 3)
492 book = Book.objects.get(slug=slug)
493 except Book.DoesNotExist:
496 cls.objects.update_or_create(
497 book=book, date=date,
498 defaults={which: views}
500 book.update_monthly_stats()