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.

61 lines
2.5 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. import collections
  2. from django.db.models import Count, Q
  3. from django.shortcuts import get_object_or_404
  4. from rest_framework.permissions import IsAuthenticated
  5. from rest_framework.response import Response
  6. from rest_framework.views import APIView
  7. from ..models import Project
  8. from ..permissions import IsInProjectReadOnlyOrAdmin
  9. class StatisticsAPI(APIView):
  10. pagination_class = None
  11. permission_classes = [IsAuthenticated & IsInProjectReadOnlyOrAdmin]
  12. def get(self, request, *args, **kwargs):
  13. p = get_object_or_404(Project, pk=self.kwargs['project_id'])
  14. include = set(request.GET.getlist('include'))
  15. response = {}
  16. if not include or 'label' in include:
  17. label_count, user_count = self.label_per_data(p)
  18. response['label'] = label_count
  19. # TODO: Make user_label count chart
  20. response['user_label'] = user_count
  21. if not include or 'total' in include or 'remaining' in include or 'user' in include:
  22. progress = self.progress(project=p)
  23. response.update(progress)
  24. if include:
  25. response = {key: value for (key, value) in response.items() if key in include}
  26. return Response(response)
  27. @staticmethod
  28. def _get_user_completion_data(annotation_class, annotation_filter):
  29. all_annotation_objects = annotation_class.objects.filter(annotation_filter)
  30. set_user_data = collections.defaultdict(set)
  31. for ind_obj in all_annotation_objects.values('user__username', 'example__id'):
  32. set_user_data[ind_obj['user__username']].add(ind_obj['example__id'])
  33. return {i: len(set_user_data[i]) for i in set_user_data}
  34. def progress(self, project):
  35. docs = project.examples
  36. annotation_class = project.get_annotation_class()
  37. total = docs.count()
  38. annotation_filter = Q(example_id__in=docs.all())
  39. user_data = self._get_user_completion_data(annotation_class, annotation_filter)
  40. if not project.collaborative_annotation:
  41. annotation_filter &= Q(user_id=self.request.user)
  42. done = annotation_class.objects.filter(annotation_filter)\
  43. .aggregate(Count('example', distinct=True))['example__count']
  44. remaining = total - done
  45. return {'total': total, 'remaining': remaining, 'user': user_data}
  46. def label_per_data(self, project):
  47. annotation_class = project.get_annotation_class()
  48. return annotation_class.objects.get_label_per_data(project=project)