Author description generator
[redakcja.git] / src / catalogue / models.py
1 from collections import Counter
2 import decimal
3 from django.apps import apps
4 from django.db import models
5 from django.template.loader import render_to_string
6 from django.urls import reverse
7 from django.utils.translation import gettext_lazy as _
8 from admin_ordering.models import OrderableModel
9 from wikidata.client import Client
10 from .constants import WIKIDATA
11 from .wikidata import WikidataModel
12
13
14 class Author(WikidataModel):
15     slug = models.SlugField(max_length=255, null=True, blank=True, unique=True)
16     first_name = models.CharField(_("first name"), max_length=255, blank=True)
17     last_name = models.CharField(_("last name"), max_length=255, blank=True)
18
19     name_de = models.CharField(_("name (de)"), max_length=255, blank=True)
20     name_lt = models.CharField(_("name (lt)"), max_length=255, blank=True)
21
22     gender = models.CharField(_("gender"), max_length=255, blank=True)
23     nationality = models.CharField(_("nationality"), max_length=255, blank=True)
24     year_of_birth = models.SmallIntegerField(_("year of birth"), null=True, blank=True)
25     year_of_birth_inexact = models.BooleanField(_("inexact"), default=False)
26     year_of_birth_range = models.SmallIntegerField(_("year of birth, range end"), null=True, blank=True)
27     date_of_birth = models.DateField(_("date_of_birth"), null=True, blank=True)
28     place_of_birth = models.ForeignKey(
29         'Place', models.PROTECT, null=True, blank=True,
30         verbose_name=_('place of birth'),
31         related_name='authors_born'
32     )
33     year_of_death = models.SmallIntegerField(_("year of death"), null=True, blank=True)
34     year_of_death_inexact = models.BooleanField(_("inexact"), default=False)
35     year_of_death_range = models.SmallIntegerField(_("year of death, range end"), null=True, blank=True)
36     date_of_death = models.DateField(_("date_of_death"), null=True, blank=True)
37     place_of_death = models.ForeignKey(
38         'Place', models.PROTECT, null=True, blank=True,
39         verbose_name=_('place of death'),
40         related_name='authors_died'
41     )
42     status = models.PositiveSmallIntegerField(
43         _("status"), 
44         null=True,
45         blank=True,
46         choices=[
47             (1, _("Alive")),
48             (2, _("Dead")),
49             (3, _("Long dead")),
50             (4, _("Unknown")),
51         ],
52     )
53     notes = models.TextField(_("notes"), blank=True)
54     gazeta_link = models.CharField(_("gazeta link"), max_length=255, blank=True)
55     culturepl_link = models.CharField(_("culture.pl link"), max_length=255, blank=True)
56
57     description = models.TextField(_("description"), blank=True)
58
59     priority = models.PositiveSmallIntegerField(
60         _("priority"), 
61         default=0, choices=[(0, _("Low")), (1, _("Medium")), (2, _("High"))]
62     )
63     collections = models.ManyToManyField("Collection", blank=True, verbose_name=_("collections"))
64
65     class Meta:
66         verbose_name = _('author')
67         verbose_name_plural = _('authors')
68         ordering = ("last_name", "first_name", "year_of_death")
69
70     class Wikidata:
71         first_name = WIKIDATA.GIVEN_NAME
72         last_name = WIKIDATA.LAST_NAME
73         date_of_birth = WIKIDATA.DATE_OF_BIRTH
74         year_of_birth = WIKIDATA.DATE_OF_BIRTH
75         place_of_birth = WIKIDATA.PLACE_OF_BIRTH
76         date_of_death = WIKIDATA.DATE_OF_DEATH
77         year_of_death = WIKIDATA.DATE_OF_DEATH
78         place_of_death = WIKIDATA.PLACE_OF_DEATH
79         gender = WIKIDATA.GENDER
80         notes = "description"
81
82         def _supplement(obj):
83             if not obj.first_name and not obj.last_name:
84                 yield 'first_name', 'label'
85
86     def __str__(self):
87         name = f"{self.first_name} {self.last_name}"
88         if self.year_of_death is not None:
89             name += f' (zm. {self.year_of_death})'
90         return name
91
92     def get_absolute_url(self):
93         return reverse("catalogue_author", args=[self.slug])
94
95     @property
96     def name(self):
97         return f"{self.last_name}, {self.first_name}"
98     
99     @property
100     def pd_year(self):
101         if self.year_of_death:
102             return self.year_of_death + 71
103         elif self.year_of_death == 0:
104             return 0
105         else:
106             return None
107
108     def generate_description(self):
109         t = render_to_string(
110             'catalogue/author_description.html',
111             {'obj': self}
112         )
113         return t
114
115 class NotableBook(OrderableModel):
116     author = models.ForeignKey(Author, models.CASCADE)
117     book = models.ForeignKey('Book', models.CASCADE)
118
119
120 class Category(WikidataModel):
121     name = models.CharField(_("name"), max_length=255)
122     slug = models.SlugField(max_length=255, unique=True)
123
124     class Meta:
125         abstract = True
126
127     def __str__(self):
128         return self.name
129
130 class Epoch(Category):
131     class Meta:
132         verbose_name = _('epoch')
133         verbose_name_plural = _('epochs')
134
135
136 class Genre(Category):
137     class Meta:
138         verbose_name = _('genre')
139         verbose_name_plural = _('genres')
140
141
142 class Kind(Category):
143     class Meta:
144         verbose_name = _('kind')
145         verbose_name_plural = _('kinds')
146
147
148 class Book(WikidataModel):
149     slug = models.SlugField(max_length=255, blank=True, null=True, unique=True)
150     authors = models.ManyToManyField(Author, blank=True, verbose_name=_("authors"))
151     translators = models.ManyToManyField(
152         Author,
153         related_name="translated_book_set",
154         related_query_name="translated_book",
155         blank=True,
156         verbose_name=_("translators")
157     )
158     epochs = models.ManyToManyField(Epoch, blank=True, verbose_name=_("epochs"))
159     kinds = models.ManyToManyField(Kind, blank=True, verbose_name=_("kinds"))
160     genres = models.ManyToManyField(Genre, blank=True, verbose_name=_("genres"))
161     title = models.CharField(_("title"), max_length=255, blank=True)
162     language = models.CharField(_("language"), max_length=255, blank=True)
163     based_on = models.ForeignKey(
164         "self", models.PROTECT, related_name="translation", null=True, blank=True,
165         verbose_name=_("based on")
166     )
167     scans_source = models.CharField(_("scans source"), max_length=255, blank=True)
168     text_source = models.CharField(_("text source"), max_length=255, blank=True)
169     notes = models.TextField(_("notes"), blank=True)
170     priority = models.PositiveSmallIntegerField(
171         _("priority"),
172         default=0, choices=[(0, _("Low")), (1, _("Medium")), (2, _("High"))]
173     )
174     original_year = models.IntegerField(_('original publication year'), null=True, blank=True)
175     pd_year = models.IntegerField(_('year of entry into PD'), null=True, blank=True)
176     gazeta_link = models.CharField(_("gazeta link"), max_length=255, blank=True)
177     collections = models.ManyToManyField("Collection", blank=True, verbose_name=_("collections"))
178
179     estimated_chars = models.IntegerField(_("estimated number of characters"), null=True, blank=True)
180     estimated_verses = models.IntegerField(_("estimated number of verses"), null=True, blank=True)
181     estimate_source = models.CharField(_("source of estimates"), max_length=2048, blank=True)
182
183     free_license = models.BooleanField(_('free license'), default=False)
184     polona_missing = models.BooleanField(_('missing on Polona'), default=False)
185
186     class Meta:
187         ordering = ("title",)
188         verbose_name = _('book')
189         verbose_name_plural = _('books')
190
191     class Wikidata:
192         authors = WIKIDATA.AUTHOR
193         translators = WIKIDATA.TRANSLATOR
194         title = WIKIDATA.TITLE
195         language = WIKIDATA.LANGUAGE
196         based_on = WIKIDATA.BASED_ON
197         original_year = WIKIDATA.PUBLICATION_DATE
198         notes = "description"
199
200     def __str__(self):
201         txt = self.title
202         if self.original_year:
203             txt = f"{txt} ({self.original_year})"
204         astr = self.authors_str()
205         if astr:
206             txt = f"{txt}, {astr}"
207         tstr = self.translators_str()
208         if tstr:
209             txt = f"{txt}, tłum. {tstr}"
210         return txt
211
212     def get_absolute_url(self):
213         return reverse("catalogue_book", args=[self.slug])
214
215     @property
216     def wluri(self):
217         return f'https://wolnelektury.pl/katalog/lektura/{self.slug}/'
218     
219     def authors_str(self):
220         return ", ".join(str(author) for author in self.authors.all())
221     authors_str.admin_order_field = 'authors__last_name'
222     authors_str.short_description = _('Author')
223
224     def translators_str(self):
225         return ", ".join(str(author) for author in self.translators.all())
226     translators_str.admin_order_field = 'translators__last_name'
227     translators_str.short_description = _('Translator')
228
229     def get_estimated_costs(self):
230         return {
231             work_type: work_type.calculate(self)
232             for work_type in WorkType.objects.all()
233         }
234
235
236 class CollectionCategory(models.Model):
237     name = models.CharField(_("name"), max_length=255)
238     parent = models.ForeignKey('self', models.SET_NULL, related_name='children', null=True, blank=True, verbose_name=_("parent"))
239     notes = models.TextField(_("notes"), blank=True)
240
241     class Meta:
242         ordering = ('parent__name', 'name')
243         verbose_name = _('collection category')
244         verbose_name_plural = _('collection categories')
245
246     def __str__(self):
247         if self.parent:
248             return f"{self.parent} / {self.name}"
249         else:
250             return self.name
251
252
253 class Collection(models.Model):
254     name = models.CharField(_("name"), max_length=255)
255     slug = models.SlugField(max_length=255, unique=True)
256     category = models.ForeignKey(CollectionCategory, models.SET_NULL, null=True, blank=True, verbose_name=_("category"))
257     notes = models.TextField(_("notes"), blank=True)
258
259     class Meta:
260         ordering = ('category', 'name')
261         verbose_name = _('collection')
262         verbose_name_plural = _('collections')
263
264     def __str__(self):
265         if self.category:
266             return f"{self.category} / {self.name}"
267         else:
268             return self.name
269
270     def get_estimated_costs(self):
271         costs = Counter()
272         for book in self.book_set.all():
273             for k, v in book.get_estimated_costs().items():
274                 costs[k] += v or 0
275
276         for author in self.author_set.all():
277             for book in author.book_set.all():
278                 for k, v in book.get_estimated_costs().items():
279                     costs[k] += v or 0
280             for book in author.translated_book_set.all():
281                 for k, v in book.get_estimated_costs().items():
282                     costs[k] += v or 0
283         return costs
284
285
286 class WorkType(models.Model):
287     name = models.CharField(_("name"), max_length=255)
288
289     class Meta:
290         ordering = ('name',)
291         verbose_name = _('work type')
292         verbose_name_plural = _('work types')
293     
294     def get_rate_for(self, book):
295         for workrate in self.workrate_set.all():
296             if workrate.matches(book):
297                 return workrate
298
299     def calculate(self, book):
300         workrate = self.get_rate_for(book)
301         if workrate is not None:
302             return workrate.calculate(book)
303         
304
305
306 class WorkRate(models.Model):
307     priority = models.IntegerField(_("priority"), default=1)
308     per_normpage = models.DecimalField(_("per normalized page"), decimal_places=2, max_digits=6, null=True, blank=True)
309     per_verse = models.DecimalField(_("per verse"), decimal_places=2, max_digits=6, null=True, blank=True)
310     work_type = models.ForeignKey(WorkType, models.CASCADE, verbose_name=_("work type"))
311     epochs = models.ManyToManyField(Epoch, blank=True, verbose_name=_("epochs"))
312     kinds = models.ManyToManyField(Kind, blank=True, verbose_name=_("kinds"))
313     genres = models.ManyToManyField(Genre, blank=True, verbose_name=_("genres"))
314     collections = models.ManyToManyField(Collection, blank=True, verbose_name=_("collections"))
315
316     class Meta:
317         ordering = ('priority',)
318         verbose_name = _('work rate')
319         verbose_name_plural = _('work rates')
320
321     def matches(self, book):
322         for category in 'epochs', 'kinds', 'genres', 'collections':
323             oneof = getattr(self, category).all()
324             if oneof:
325                 if not set(oneof).intersection(
326                         getattr(book, category).all()):
327                     return False
328         return True
329
330     def calculate(self, book):
331         if self.per_verse:
332             if book.estimated_verses:
333                 return book.estimated_verses * self.per_verse
334         elif self.per_normpage:
335             if book.estimated_chars:
336                 return (decimal.Decimal(book.estimated_chars) / 1800 * self.per_normpage).quantize(decimal.Decimal('1.00'), rounding=decimal.ROUND_HALF_UP)
337
338
339 class Place(WikidataModel):
340     name = models.CharField(_('name'), max_length=255, blank=True)
341     locative = models.CharField(_('locative'), max_length=255, blank=True, help_text=_('in…'))
342
343     class Meta:
344         verbose_name = _('place')
345         verbose_name_plural = _('places')
346     
347     class Wikidata:
348         name = 'label'
349
350     def __str__(self):
351         return self.name