You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

358 lines
11 KiB

5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. import string
  2. from django.db import models
  3. from django.dispatch import receiver
  4. from django.db.models.signals import post_save, pre_delete
  5. from django.urls import reverse
  6. from django.conf import settings
  7. from django.contrib.auth.models import User
  8. from django.contrib.staticfiles.storage import staticfiles_storage
  9. from django.core.exceptions import ValidationError
  10. from polymorphic.models import PolymorphicModel
  11. from .managers import AnnotationManager, Seq2seqAnnotationManager
  12. DOCUMENT_CLASSIFICATION = 'DocumentClassification'
  13. SEQUENCE_LABELING = 'SequenceLabeling'
  14. SEQ2SEQ = 'Seq2seq'
  15. SPEECH2TEXT = 'Speech2text'
  16. PROJECT_CHOICES = (
  17. (DOCUMENT_CLASSIFICATION, 'document classification'),
  18. (SEQUENCE_LABELING, 'sequence labeling'),
  19. (SEQ2SEQ, 'sequence to sequence'),
  20. (SPEECH2TEXT, 'speech to text'),
  21. )
  22. class Project(PolymorphicModel):
  23. name = models.CharField(max_length=100)
  24. description = models.TextField(default='')
  25. guideline = models.TextField(default='')
  26. created_at = models.DateTimeField(auto_now_add=True)
  27. updated_at = models.DateTimeField(auto_now=True)
  28. users = models.ManyToManyField(User, related_name='projects')
  29. project_type = models.CharField(max_length=30, choices=PROJECT_CHOICES)
  30. randomize_document_order = models.BooleanField(default=False)
  31. collaborative_annotation = models.BooleanField(default=False)
  32. single_class_classification = models.BooleanField(default=False)
  33. def get_absolute_url(self):
  34. return reverse('upload', args=[self.id])
  35. @property
  36. def image(self):
  37. raise NotImplementedError()
  38. def get_bundle_name(self):
  39. raise NotImplementedError()
  40. def get_bundle_name_upload(self):
  41. raise NotImplementedError()
  42. def get_bundle_name_download(self):
  43. raise NotImplementedError()
  44. def get_annotation_serializer(self):
  45. raise NotImplementedError()
  46. def get_annotation_class(self):
  47. raise NotImplementedError()
  48. def get_storage(self, data):
  49. raise NotImplementedError()
  50. def __str__(self):
  51. return self.name
  52. class TextClassificationProject(Project):
  53. @property
  54. def image(self):
  55. return staticfiles_storage.url('assets/images/cats/text_classification.jpg')
  56. def get_bundle_name(self):
  57. return 'document_classification'
  58. def get_bundle_name_upload(self):
  59. return 'upload_text_classification'
  60. def get_bundle_name_download(self):
  61. return 'download_text_classification'
  62. def get_annotation_serializer(self):
  63. from .serializers import DocumentAnnotationSerializer
  64. return DocumentAnnotationSerializer
  65. def get_annotation_class(self):
  66. return DocumentAnnotation
  67. def get_storage(self, data):
  68. from .utils import ClassificationStorage
  69. return ClassificationStorage(data, self)
  70. class SequenceLabelingProject(Project):
  71. @property
  72. def image(self):
  73. return staticfiles_storage.url('assets/images/cats/sequence_labeling.jpg')
  74. def get_bundle_name(self):
  75. return 'sequence_labeling'
  76. def get_bundle_name_upload(self):
  77. return 'upload_sequence_labeling'
  78. def get_bundle_name_download(self):
  79. return 'download_sequence_labeling'
  80. def get_annotation_serializer(self):
  81. from .serializers import SequenceAnnotationSerializer
  82. return SequenceAnnotationSerializer
  83. def get_annotation_class(self):
  84. return SequenceAnnotation
  85. def get_storage(self, data):
  86. from .utils import SequenceLabelingStorage
  87. return SequenceLabelingStorage(data, self)
  88. class Seq2seqProject(Project):
  89. @property
  90. def image(self):
  91. return staticfiles_storage.url('assets/images/cats/seq2seq.jpg')
  92. def get_bundle_name(self):
  93. return 'seq2seq'
  94. def get_bundle_name_upload(self):
  95. return 'upload_seq2seq'
  96. def get_bundle_name_download(self):
  97. return 'download_seq2seq'
  98. def get_annotation_serializer(self):
  99. from .serializers import Seq2seqAnnotationSerializer
  100. return Seq2seqAnnotationSerializer
  101. def get_annotation_class(self):
  102. return Seq2seqAnnotation
  103. def get_storage(self, data):
  104. from .utils import Seq2seqStorage
  105. return Seq2seqStorage(data, self)
  106. class Speech2textProject(Project):
  107. @property
  108. def image(self):
  109. return staticfiles_storage.url('images/cats/speech2text.jpg')
  110. def get_bundle_name(self):
  111. return 'speech2text'
  112. def get_bundle_name_upload(self):
  113. return 'upload_speech2text'
  114. def get_bundle_name_download(self):
  115. return 'download_speech2text'
  116. def get_annotation_serializer(self):
  117. from .serializers import Speech2textAnnotationSerializer
  118. return Speech2textAnnotationSerializer
  119. def get_annotation_class(self):
  120. return Speech2textAnnotation
  121. def get_storage(self, data):
  122. from .utils import Speech2textStorage
  123. return Speech2textStorage(data, self)
  124. class Label(models.Model):
  125. PREFIX_KEYS = (
  126. ('ctrl', 'ctrl'),
  127. ('shift', 'shift'),
  128. ('ctrl shift', 'ctrl shift')
  129. )
  130. SUFFIX_KEYS = tuple(
  131. (c, c) for c in string.digits + string.ascii_lowercase
  132. )
  133. text = models.CharField(max_length=100)
  134. prefix_key = models.CharField(max_length=10, blank=True, null=True, choices=PREFIX_KEYS)
  135. suffix_key = models.CharField(max_length=1, blank=True, null=True, choices=SUFFIX_KEYS)
  136. project = models.ForeignKey(Project, related_name='labels', on_delete=models.CASCADE)
  137. background_color = models.CharField(max_length=7, default='#209cee')
  138. text_color = models.CharField(max_length=7, default='#ffffff')
  139. created_at = models.DateTimeField(auto_now_add=True)
  140. updated_at = models.DateTimeField(auto_now=True)
  141. def __str__(self):
  142. return self.text
  143. def clean(self):
  144. # Don't allow shortcut key not to have a suffix key.
  145. if self.prefix_key and not self.suffix_key:
  146. raise ValidationError('Shortcut key may not have a suffix key.')
  147. # each shortcut (prefix key + suffix key) can only be assigned to one label
  148. if self.suffix_key or self.prefix_key:
  149. other_labels = self.project.labels.exclude(id=self.id)
  150. if other_labels.filter(suffix_key=self.suffix_key, prefix_key=self.prefix_key).exists():
  151. raise ValidationError('A label with this shortcut already exists in the project')
  152. super().clean()
  153. class Meta:
  154. unique_together = (
  155. ('project', 'text'),
  156. )
  157. class Document(models.Model):
  158. text = models.TextField()
  159. project = models.ForeignKey(Project, related_name='documents', on_delete=models.CASCADE)
  160. meta = models.TextField(default='{}')
  161. created_at = models.DateTimeField(auto_now_add=True)
  162. updated_at = models.DateTimeField(auto_now=True)
  163. annotations_approved_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
  164. def __str__(self):
  165. return self.text[:50]
  166. class Annotation(models.Model):
  167. objects = AnnotationManager()
  168. prob = models.FloatField(default=0.0)
  169. manual = models.BooleanField(default=False)
  170. user = models.ForeignKey(User, on_delete=models.CASCADE)
  171. created_at = models.DateTimeField(auto_now_add=True)
  172. updated_at = models.DateTimeField(auto_now=True)
  173. class Meta:
  174. abstract = True
  175. class DocumentAnnotation(Annotation):
  176. document = models.ForeignKey(Document, related_name='doc_annotations', on_delete=models.CASCADE)
  177. label = models.ForeignKey(Label, on_delete=models.CASCADE)
  178. class Meta:
  179. unique_together = ('document', 'user', 'label')
  180. class SequenceAnnotation(Annotation):
  181. document = models.ForeignKey(Document, related_name='seq_annotations', on_delete=models.CASCADE)
  182. label = models.ForeignKey(Label, on_delete=models.CASCADE)
  183. start_offset = models.IntegerField()
  184. end_offset = models.IntegerField()
  185. def clean(self):
  186. if self.start_offset >= self.end_offset:
  187. raise ValidationError('start_offset is after end_offset')
  188. class Meta:
  189. unique_together = ('document', 'user', 'label', 'start_offset', 'end_offset')
  190. class Seq2seqAnnotation(Annotation):
  191. # Override AnnotationManager for custom functionality
  192. objects = Seq2seqAnnotationManager()
  193. document = models.ForeignKey(Document, related_name='seq2seq_annotations', on_delete=models.CASCADE)
  194. text = models.CharField(max_length=500)
  195. class Meta:
  196. unique_together = ('document', 'user', 'text')
  197. class Speech2textAnnotation(Annotation):
  198. document = models.ForeignKey(Document, related_name='speech2text_annotations', on_delete=models.CASCADE)
  199. text = models.TextField()
  200. class Meta:
  201. unique_together = ('document', 'user')
  202. class Role(models.Model):
  203. name = models.CharField(max_length=100, unique=True)
  204. description = models.TextField(default='')
  205. created_at = models.DateTimeField(auto_now_add=True)
  206. updated_at = models.DateTimeField(auto_now=True)
  207. def __str__(self):
  208. return self.name
  209. class RoleMapping(models.Model):
  210. user = models.ForeignKey(User, related_name='role_mappings', on_delete=models.CASCADE)
  211. project = models.ForeignKey(Project, related_name='role_mappings', on_delete=models.CASCADE)
  212. role = models.ForeignKey(Role, on_delete=models.CASCADE)
  213. created_at = models.DateTimeField(auto_now_add=True)
  214. updated_at = models.DateTimeField(auto_now=True)
  215. def clean(self):
  216. other_rolemappings = self.project.role_mappings.exclude(id=self.id)
  217. if other_rolemappings.filter(user=self.user, project=self.project).exists():
  218. raise ValidationError('This user is already assigned to a role in this project.')
  219. class Meta:
  220. unique_together = ("user", "project", "role")
  221. @receiver(post_save, sender=RoleMapping)
  222. def add_linked_project(sender, instance, created, **kwargs):
  223. if not created:
  224. return
  225. userInstance = instance.user
  226. projectInstance = instance.project
  227. if userInstance and projectInstance:
  228. user = User.objects.get(pk=userInstance.pk)
  229. project = Project.objects.get(pk=projectInstance.pk)
  230. user.projects.add(project)
  231. user.save()
  232. @receiver(post_save)
  233. def add_superusers_to_project(sender, instance, created, **kwargs):
  234. if not created:
  235. return
  236. if sender not in Project.__subclasses__():
  237. return
  238. superusers = User.objects.filter(is_superuser=True)
  239. admin_role = Role.objects.filter(name=settings.ROLE_PROJECT_ADMIN).first()
  240. if superusers and admin_role:
  241. RoleMapping.objects.bulk_create(
  242. [RoleMapping(role_id=admin_role.id, user_id=superuser.id, project_id=instance.id)
  243. for superuser in superusers]
  244. )
  245. @receiver(post_save, sender=User)
  246. def add_new_superuser_to_projects(sender, instance, created, **kwargs):
  247. if created and instance.is_superuser:
  248. admin_role = Role.objects.filter(name=settings.ROLE_PROJECT_ADMIN).first()
  249. projects = Project.objects.all()
  250. if admin_role and projects:
  251. RoleMapping.objects.bulk_create(
  252. [RoleMapping(role_id=admin_role.id, user_id=instance.id, project_id=project.id)
  253. for project in projects]
  254. )
  255. @receiver(pre_delete, sender=RoleMapping)
  256. def delete_linked_project(sender, instance, using, **kwargs):
  257. userInstance = instance.user
  258. projectInstance = instance.project
  259. if userInstance and projectInstance:
  260. user = User.objects.get(pk=userInstance.pk)
  261. project = Project.objects.get(pk=projectInstance.pk)
  262. user.projects.remove(project)
  263. user.save()