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