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 class CollectionCategory(models.Model):
320 name = models.CharField(_("name"), max_length=255)
321 parent = models.ForeignKey('self', models.SET_NULL, related_name='children', null=True, blank=True, verbose_name=_("parent"))
322 notes = models.TextField(_("notes"), blank=True, help_text=_('private'))
325 ordering = ('parent__name', 'name')
326 verbose_name = _('collection category')
327 verbose_name_plural = _('collection categories')
331 return f"{self.parent} / {self.name}"
336 class Collection(models.Model):
337 name = models.CharField(_("name"), max_length=255)
338 slug = models.SlugField(max_length=255, unique=True)
339 category = models.ForeignKey(CollectionCategory, models.SET_NULL, null=True, blank=True, verbose_name=_("category"))
340 notes = models.TextField(_("notes"), blank=True, help_text=_('private'))
341 description = models.TextField(_("description"), blank=True)
344 ordering = ('category', 'name')
345 verbose_name = _('collection')
346 verbose_name_plural = _('collections')
350 return f"{self.category} / {self.name}"
354 def get_estimated_costs(self):
356 for book in self.book_set.all():
357 for k, v in book.get_estimated_costs().items():
360 for author in self.author_set.all():
361 for book in author.book_set.all():
362 for k, v in book.get_estimated_costs().items():
364 for book in author.translated_book_set.all():
365 for k, v in book.get_estimated_costs().items():
370 class WorkType(models.Model):
371 name = models.CharField(_("name"), max_length=255)
375 verbose_name = _('work type')
376 verbose_name_plural = _('work types')
378 def get_rate_for(self, book):
379 for workrate in self.workrate_set.all():
380 if workrate.matches(book):
383 def calculate(self, book):
384 workrate = self.get_rate_for(book)
385 if workrate is not None:
386 return workrate.calculate(book)
390 class WorkRate(models.Model):
391 priority = models.IntegerField(_("priority"), default=1)
392 per_normpage = models.DecimalField(_("per normalized page"), decimal_places=2, max_digits=6, null=True, blank=True)
393 per_verse = models.DecimalField(_("per verse"), decimal_places=2, max_digits=6, null=True, blank=True)
394 work_type = models.ForeignKey(WorkType, models.CASCADE, verbose_name=_("work type"))
395 epochs = models.ManyToManyField(Epoch, blank=True, verbose_name=_("epochs"))
396 kinds = models.ManyToManyField(Kind, blank=True, verbose_name=_("kinds"))
397 genres = models.ManyToManyField(Genre, blank=True, verbose_name=_("genres"))
398 collections = models.ManyToManyField(Collection, blank=True, verbose_name=_("collections"))
401 ordering = ('priority',)
402 verbose_name = _('work rate')
403 verbose_name_plural = _('work rates')
405 def matches(self, book):
406 for category in 'epochs', 'kinds', 'genres', 'collections':
407 oneof = getattr(self, category).all()
409 if not set(oneof).intersection(
410 getattr(book, category).all()):
414 def calculate(self, book):
416 if book.estimated_verses:
417 return book.estimated_verses * self.per_verse
418 elif self.per_normpage:
419 if book.estimated_chars:
420 return (decimal.Decimal(book.estimated_chars) / 1800 * self.per_normpage).quantize(decimal.Decimal('1.00'), rounding=decimal.ROUND_HALF_UP)
423 class Place(WikidataModel):
424 name = models.CharField(_('name'), max_length=255, blank=True)
425 locative = models.CharField(_('locative'), max_length=255, blank=True, help_text=_('in…'))
428 verbose_name = _('place')
429 verbose_name_plural = _('places')
438 class BookMonthlyStats(models.Model):
439 book = models.ForeignKey('catalogue.Book', models.CASCADE)
440 date = models.DateField()
441 views_reader = models.IntegerField(default=0)
442 views_page = models.IntegerField(default=0)
445 def build_for_month(cls, date):
446 date = date.replace(day=1)
449 date = date.isoformat()
450 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'
451 data = urlopen(url).read().decode('utf-16')
452 lines = data.split('\n')[1:]
454 m = re.match('^/katalog/lektura/([^,./]+)\.html,', line)
456 which = 'views_reader'
458 m = re.match('^/katalog/lektura/([^,./]+)/,', line)
463 _url, _uviews, views, _rest = line.split(',', 3)
466 book = Book.objects.get(slug=slug)
467 except Book.DoesNotExist:
470 cls.objects.update_or_create(
471 book=book, date=date,
472 defaults={which: views}
474 book.update_monthly_stats()