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.

213 lines
8.1 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 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
  1. from collections import Counter
  2. from django.shortcuts import get_object_or_404
  3. from django_filters.rest_framework import DjangoFilterBackend
  4. from django.db.models import Count
  5. from rest_framework import generics, filters, status
  6. from rest_framework.exceptions import ParseError, ValidationError
  7. from rest_framework.permissions import IsAuthenticated, IsAdminUser
  8. from rest_framework.response import Response
  9. from rest_framework.views import APIView
  10. from rest_framework.parsers import MultiPartParser
  11. from rest_framework_csv.renderers import CSVRenderer
  12. from .filters import DocumentFilter
  13. from .models import Project, Label, Document
  14. from .permissions import IsAdminUserAndWriteOnly, IsProjectUser, IsOwnAnnotation
  15. from .serializers import ProjectSerializer, LabelSerializer, DocumentSerializer
  16. from .serializers import ProjectPolymorphicSerializer
  17. from .utils import CSVParser, JSONParser, PlainTextParser, CoNLLParser
  18. from .utils import JSONLRenderer
  19. from .utils import JSONPainter, CSVPainter
  20. class ProjectList(generics.ListCreateAPIView):
  21. queryset = Project.objects.all()
  22. serializer_class = ProjectPolymorphicSerializer
  23. pagination_class = None
  24. permission_classes = (IsAuthenticated, IsAdminUserAndWriteOnly)
  25. def get_queryset(self):
  26. return self.request.user.projects
  27. def perform_create(self, serializer):
  28. serializer.save(users=[self.request.user])
  29. class ProjectDetail(generics.RetrieveUpdateDestroyAPIView):
  30. queryset = Project.objects.all()
  31. serializer_class = ProjectSerializer
  32. lookup_url_kwarg = 'project_id'
  33. permission_classes = (IsAuthenticated, IsProjectUser, IsAdminUserAndWriteOnly)
  34. class StatisticsAPI(APIView):
  35. pagination_class = None
  36. permission_classes = (IsAuthenticated, IsProjectUser, IsAdminUserAndWriteOnly)
  37. def get(self, request, *args, **kwargs):
  38. p = get_object_or_404(Project, pk=self.kwargs['project_id'])
  39. label_count, user_count = self.label_per_data(p)
  40. progress = self.progress(project=p)
  41. response = dict()
  42. response['label'] = label_count
  43. response['user'] = user_count
  44. response.update(progress)
  45. return Response(response)
  46. def progress(self, project):
  47. docs = project.documents
  48. annotation_class = project.get_annotation_class()
  49. total = docs.count()
  50. done = annotation_class.objects.filter(document_id__in=docs.all()).\
  51. aggregate(Count('document', distinct=True))['document__count']
  52. remaining = total - done
  53. return {'total': total, 'remaining': remaining}
  54. def label_per_data(self, project):
  55. label_count = Counter()
  56. user_count = Counter()
  57. annotation_class = project.get_annotation_class()
  58. docs = project.documents.all()
  59. annotations = annotation_class.objects.filter(document_id__in=docs.all())
  60. for d in annotations.values('label__text', 'user__username').annotate(Count('label'), Count('user')):
  61. label_count[d['label__text']] += d['label__count']
  62. user_count[d['user__username']] += d['user__count']
  63. return label_count, user_count
  64. class LabelList(generics.ListCreateAPIView):
  65. queryset = Label.objects.all()
  66. serializer_class = LabelSerializer
  67. pagination_class = None
  68. permission_classes = (IsAuthenticated, IsProjectUser, IsAdminUserAndWriteOnly)
  69. def get_queryset(self):
  70. queryset = self.queryset.filter(project=self.kwargs['project_id'])
  71. return queryset
  72. def perform_create(self, serializer):
  73. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  74. serializer.save(project=project)
  75. class LabelDetail(generics.RetrieveUpdateDestroyAPIView):
  76. queryset = Label.objects.all()
  77. serializer_class = LabelSerializer
  78. lookup_url_kwarg = 'label_id'
  79. permission_classes = (IsAuthenticated, IsProjectUser, IsAdminUserAndWriteOnly)
  80. class DocumentList(generics.ListCreateAPIView):
  81. queryset = Document.objects.all()
  82. serializer_class = DocumentSerializer
  83. filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
  84. search_fields = ('text', )
  85. ordering_fields = ('created_at', 'updated_at', 'doc_annotations__updated_at',
  86. 'seq_annotations__updated_at', 'seq2seq_annotations__updated_at')
  87. filter_class = DocumentFilter
  88. permission_classes = (IsAuthenticated, IsProjectUser, IsAdminUserAndWriteOnly)
  89. def get_queryset(self):
  90. queryset = self.queryset.filter(project=self.kwargs['project_id'])
  91. return queryset
  92. def perform_create(self, serializer):
  93. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  94. serializer.save(project=project)
  95. class DocumentDetail(generics.RetrieveUpdateDestroyAPIView):
  96. queryset = Document.objects.all()
  97. serializer_class = DocumentSerializer
  98. lookup_url_kwarg = 'doc_id'
  99. permission_classes = (IsAuthenticated, IsProjectUser, IsAdminUserAndWriteOnly)
  100. class AnnotationList(generics.ListCreateAPIView):
  101. pagination_class = None
  102. permission_classes = (IsAuthenticated, IsProjectUser)
  103. def get_serializer_class(self):
  104. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  105. self.serializer_class = project.get_annotation_serializer()
  106. return self.serializer_class
  107. def get_queryset(self):
  108. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  109. model = project.get_annotation_class()
  110. self.queryset = model.objects.filter(document=self.kwargs['doc_id'],
  111. user=self.request.user)
  112. return self.queryset
  113. def create(self, request, *args, **kwargs):
  114. request.data['document'] = self.kwargs['doc_id']
  115. return super().create(request, args, kwargs)
  116. def perform_create(self, serializer):
  117. doc = get_object_or_404(Document, pk=self.kwargs['doc_id'])
  118. serializer.save(document=doc, user=self.request.user)
  119. class AnnotationDetail(generics.RetrieveUpdateDestroyAPIView):
  120. lookup_url_kwarg = 'annotation_id'
  121. permission_classes = (IsAuthenticated, IsProjectUser, IsOwnAnnotation)
  122. def get_serializer_class(self):
  123. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  124. self.serializer_class = project.get_annotation_serializer()
  125. return self.serializer_class
  126. def get_queryset(self):
  127. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  128. model = project.get_annotation_class()
  129. self.queryset = model.objects.all()
  130. return self.queryset
  131. class TextUploadAPI(APIView):
  132. parser_classes = (MultiPartParser,)
  133. permission_classes = (IsAuthenticated, IsProjectUser, IsAdminUser)
  134. def post(self, request, *args, **kwargs):
  135. if 'file' not in request.data:
  136. raise ParseError('Empty content')
  137. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  138. parser = self.select_parser(request.data['format'])
  139. data = parser.parse(request.data['file'])
  140. storage = project.get_storage(data)
  141. storage.save(self.request.user)
  142. return Response(status=status.HTTP_201_CREATED)
  143. def select_parser(self, format):
  144. if format == 'plain':
  145. return PlainTextParser()
  146. elif format == 'csv':
  147. return CSVParser()
  148. elif format == 'json':
  149. return JSONParser()
  150. elif format == 'conll':
  151. return CoNLLParser()
  152. else:
  153. raise ValidationError('format {} is invalid.'.format(format))
  154. class TextDownloadAPI(APIView):
  155. permission_classes = (IsAuthenticated, IsProjectUser, IsAdminUser)
  156. renderer_classes = (CSVRenderer, JSONLRenderer)
  157. def get(self, request, *args, **kwargs):
  158. format = request.query_params.get('q')
  159. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  160. documents = project.documents.all()
  161. painter = self.select_painter(format)
  162. data = painter.paint(documents)
  163. return Response(data)
  164. def select_painter(self, format):
  165. if format == 'csv':
  166. return CSVPainter()
  167. elif format == 'json':
  168. return JSONPainter()
  169. else:
  170. raise ValidationError('format {} is invalid.'.format(format))