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.

76 lines
2.4 KiB

  1. from django.db.models import Manager, Count
  2. class LabelManager(Manager):
  3. def calc_label_distribution(self, examples, members, labels):
  4. """Calculate label distribution.
  5. Args:
  6. examples: example queryset.
  7. members: user queryset.
  8. labels: label queryset.
  9. Returns:
  10. label distribution per user.
  11. Examples:
  12. >>> self.calc_label_distribution(examples, members, labels)
  13. {'admin': {'positive': 10, 'negative': 5}}
  14. """
  15. distribution = {member.username: {label.text: 0 for label in labels} for member in members}
  16. items = self.filter(example_id__in=examples)\
  17. .values('user__username', 'label__text')\
  18. .annotate(count=Count('label__text'))
  19. for item in items:
  20. username = item['user__username']
  21. label = item['label__text']
  22. count = item['count']
  23. distribution[username][label] = count
  24. return distribution
  25. def get_labels(self, label, project):
  26. if project.collaborative_annotation:
  27. return self.filter(example=label.example)
  28. else:
  29. return self.filter(example=label.example, user=label.user)
  30. def can_annotate(self, label, project) -> bool:
  31. raise NotImplementedError('Please implement this method in the subclass')
  32. def filter_annotatable_labels(self, labels, project):
  33. return [label for label in labels if self.can_annotate(label, project)]
  34. class CategoryManager(LabelManager):
  35. def can_annotate(self, label, project) -> bool:
  36. is_exclusive = project.single_class_classification
  37. categories = self.get_labels(label, project)
  38. if is_exclusive:
  39. return not categories.exists()
  40. else:
  41. return not categories.filter(label=label.label).exists()
  42. class SpanManager(LabelManager):
  43. def can_annotate(self, label, project) -> bool:
  44. overlapping = getattr(project, 'allow_overlapping', False)
  45. spans = self.get_labels(label, project)
  46. if overlapping:
  47. return True
  48. for span in spans:
  49. if span.is_overlapping(label):
  50. return False
  51. return True
  52. class TextLabelManager(LabelManager):
  53. def can_annotate(self, label, project) -> bool:
  54. texts = self.get_labels(label, project)
  55. for text in texts:
  56. if text.is_same_text(label):
  57. return False
  58. return True