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.

323 lines
12 KiB

6 years ago
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
5 years ago
  1. from collections import Counter
  2. from django.conf import settings
  3. from django.shortcuts import get_object_or_404, redirect
  4. from django_filters.rest_framework import DjangoFilterBackend
  5. from django.db.models import Count, F
  6. from libcloud.base import DriverType, get_driver
  7. from libcloud.storage.types import ContainerDoesNotExistError, ObjectDoesNotExistError
  8. from rest_framework import generics, filters, status
  9. from rest_framework.exceptions import ParseError, ValidationError
  10. from rest_framework.permissions import IsAuthenticated, IsAdminUser
  11. from rest_framework.response import Response
  12. from rest_framework.views import APIView
  13. from rest_framework.parsers import MultiPartParser
  14. from rest_framework_csv.renderers import CSVRenderer
  15. from .filters import DocumentFilter
  16. from .models import Project, Label, Document, Seq2seqAnnotation
  17. from .permissions import IsAdminUserAndWriteOnly, IsProjectUser, IsOwnAnnotation
  18. from .serializers import ProjectSerializer, LabelSerializer, DocumentSerializer, UserSerializer
  19. from .serializers import ProjectPolymorphicSerializer
  20. from .utils import CSVParser, JSONParser, PlainTextParser, CoNLLParser, iterable_to_io
  21. from .utils import JSONLRenderer
  22. from .utils import JSONPainter, CSVPainter
  23. class Me(APIView):
  24. permission_classes = (IsAuthenticated,)
  25. def get(self, request, *args, **kwargs):
  26. serializer = UserSerializer(request.user, context={'request': request})
  27. return Response(serializer.data)
  28. class Features(APIView):
  29. permission_classes = (IsAuthenticated,)
  30. def get(self, request, *args, **kwargs):
  31. return Response({
  32. 'cloud_upload': bool(settings.CLOUD_BROWSER_APACHE_LIBCLOUD_PROVIDER),
  33. })
  34. class ProjectList(generics.ListCreateAPIView):
  35. serializer_class = ProjectPolymorphicSerializer
  36. pagination_class = None
  37. permission_classes = (IsAuthenticated, IsAdminUserAndWriteOnly)
  38. def get_queryset(self):
  39. return self.request.user.projects
  40. def perform_create(self, serializer):
  41. serializer.save(users=[self.request.user])
  42. class ProjectDetail(generics.RetrieveUpdateDestroyAPIView):
  43. queryset = Project.objects.all()
  44. serializer_class = ProjectSerializer
  45. lookup_url_kwarg = 'project_id'
  46. permission_classes = (IsAuthenticated, IsProjectUser, IsAdminUserAndWriteOnly)
  47. class StatisticsAPI(APIView):
  48. pagination_class = None
  49. permission_classes = (IsAuthenticated, IsProjectUser, IsAdminUserAndWriteOnly)
  50. def get(self, request, *args, **kwargs):
  51. p = get_object_or_404(Project, pk=self.kwargs['project_id'])
  52. label_count, user_count = self.label_per_data(p)
  53. progress = self.progress(project=p)
  54. response = dict()
  55. response['label'] = label_count
  56. response['user'] = user_count
  57. response.update(progress)
  58. return Response(response)
  59. def progress(self, project):
  60. docs = project.documents
  61. annotation_class = project.get_annotation_class()
  62. total = docs.count()
  63. done = annotation_class.objects.filter(document_id__in=docs.all(),
  64. user_id=self.request.user).\
  65. aggregate(Count('document', distinct=True))['document__count']
  66. remaining = total - done
  67. return {'total': total, 'remaining': remaining}
  68. def label_per_data(self, project):
  69. label_count = Counter()
  70. user_count = Counter()
  71. annotation_class = project.get_annotation_class()
  72. docs = project.documents.all()
  73. annotations = annotation_class.objects.filter(document_id__in=docs.all())
  74. if annotation_class == Seq2seqAnnotation:
  75. for d in annotations.values('text', 'user__username').annotate(Count('text'), Count('user')):
  76. label_count[d['text']] += d['text__count']
  77. user_count[d['user__username']] += d['user__count']
  78. else:
  79. for d in annotations.values('label__text', 'user__username').annotate(Count('label'), Count('user')):
  80. label_count[d['label__text']] += d['label__count']
  81. user_count[d['user__username']] += d['user__count']
  82. return label_count, user_count
  83. class ApproveLabelsAPI(APIView):
  84. permission_classes = (IsAuthenticated, IsProjectUser, IsAdminUser)
  85. def post(self, request, *args, **kwargs):
  86. approved = self.request.data.get('approved', True)
  87. document = get_object_or_404(Document, pk=self.kwargs['doc_id'])
  88. document.annotations_approved_by = self.request.user if approved else None
  89. document.save()
  90. return Response(DocumentSerializer(document).data)
  91. class LabelList(generics.ListCreateAPIView):
  92. serializer_class = LabelSerializer
  93. pagination_class = None
  94. permission_classes = (IsAuthenticated, IsProjectUser, IsAdminUserAndWriteOnly)
  95. def get_queryset(self):
  96. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  97. return project.labels
  98. def perform_create(self, serializer):
  99. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  100. serializer.save(project=project)
  101. class LabelDetail(generics.RetrieveUpdateDestroyAPIView):
  102. queryset = Label.objects.all()
  103. serializer_class = LabelSerializer
  104. lookup_url_kwarg = 'label_id'
  105. permission_classes = (IsAuthenticated, IsProjectUser, IsAdminUserAndWriteOnly)
  106. class DocumentList(generics.ListCreateAPIView):
  107. serializer_class = DocumentSerializer
  108. filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
  109. search_fields = ('text', )
  110. ordering_fields = ('created_at', 'updated_at', 'doc_annotations__updated_at',
  111. 'seq_annotations__updated_at', 'seq2seq_annotations__updated_at')
  112. filter_class = DocumentFilter
  113. permission_classes = (IsAuthenticated, IsProjectUser, IsAdminUserAndWriteOnly)
  114. def get_queryset(self):
  115. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  116. queryset = project.documents
  117. if project.randomize_document_order:
  118. queryset = queryset.annotate(sort_id=F('id') % self.request.user.id).order_by('sort_id')
  119. return queryset
  120. def perform_create(self, serializer):
  121. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  122. serializer.save(project=project)
  123. class DocumentDetail(generics.RetrieveUpdateDestroyAPIView):
  124. queryset = Document.objects.all()
  125. serializer_class = DocumentSerializer
  126. lookup_url_kwarg = 'doc_id'
  127. permission_classes = (IsAuthenticated, IsProjectUser, IsAdminUserAndWriteOnly)
  128. class AnnotationList(generics.ListCreateAPIView):
  129. pagination_class = None
  130. permission_classes = (IsAuthenticated, IsProjectUser)
  131. def get_serializer_class(self):
  132. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  133. self.serializer_class = project.get_annotation_serializer()
  134. return self.serializer_class
  135. def get_queryset(self):
  136. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  137. model = project.get_annotation_class()
  138. self.queryset = model.objects.filter(document=self.kwargs['doc_id'],
  139. user=self.request.user)
  140. return self.queryset
  141. def create(self, request, *args, **kwargs):
  142. request.data['document'] = self.kwargs['doc_id']
  143. return super().create(request, args, kwargs)
  144. def perform_create(self, serializer):
  145. doc = get_object_or_404(Document, pk=self.kwargs['doc_id'])
  146. serializer.save(document=doc, user=self.request.user)
  147. class AnnotationDetail(generics.RetrieveUpdateDestroyAPIView):
  148. lookup_url_kwarg = 'annotation_id'
  149. permission_classes = (IsAuthenticated, IsProjectUser, IsOwnAnnotation)
  150. def get_serializer_class(self):
  151. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  152. self.serializer_class = project.get_annotation_serializer()
  153. return self.serializer_class
  154. def get_queryset(self):
  155. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  156. model = project.get_annotation_class()
  157. self.queryset = model.objects.all()
  158. return self.queryset
  159. class TextUploadAPI(APIView):
  160. parser_classes = (MultiPartParser,)
  161. permission_classes = (IsAuthenticated, IsProjectUser, IsAdminUser)
  162. def post(self, request, *args, **kwargs):
  163. if 'file' not in request.data:
  164. raise ParseError('Empty content')
  165. self.save_file(
  166. user=request.user,
  167. file=request.data['file'],
  168. file_format=request.data['format'],
  169. project_id=kwargs['project_id'],
  170. )
  171. return Response(status=status.HTTP_201_CREATED)
  172. @classmethod
  173. def save_file(cls, user, file, file_format, project_id):
  174. project = get_object_or_404(Project, pk=project_id)
  175. parser = cls.select_parser(file_format)
  176. data = parser.parse(file)
  177. storage = project.get_storage(data)
  178. storage.save(user)
  179. @classmethod
  180. def select_parser(cls, file_format):
  181. if file_format == 'plain':
  182. return PlainTextParser()
  183. elif file_format == 'csv':
  184. return CSVParser()
  185. elif file_format == 'json':
  186. return JSONParser()
  187. elif file_format == 'conll':
  188. return CoNLLParser()
  189. else:
  190. raise ValidationError('format {} is invalid.'.format(file_format))
  191. class CloudUploadAPI(APIView):
  192. permission_classes = TextUploadAPI.permission_classes
  193. def get(self, request, *args, **kwargs):
  194. try:
  195. project_id = request.query_params['project_id']
  196. file_format = request.query_params['upload_format']
  197. cloud_container = request.query_params['container']
  198. cloud_object = request.query_params['object']
  199. except KeyError as ex:
  200. raise ValidationError('query parameter {} is missing'.format(ex))
  201. try:
  202. cloud_file = self.get_cloud_object_as_io(cloud_container, cloud_object)
  203. except ContainerDoesNotExistError:
  204. raise ValidationError('cloud container {} does not exist'.format(cloud_container))
  205. except ObjectDoesNotExistError:
  206. raise ValidationError('cloud object {} does not exist'.format(cloud_object))
  207. TextUploadAPI.save_file(
  208. user=request.user,
  209. file=cloud_file,
  210. file_format=file_format,
  211. project_id=project_id,
  212. )
  213. next_url = request.query_params.get('next')
  214. if next_url == 'about:blank':
  215. return Response(data='', content_type='text/plain', status=status.HTTP_201_CREATED)
  216. if next_url:
  217. return redirect(next_url)
  218. return Response(status=status.HTTP_201_CREATED)
  219. @classmethod
  220. def get_cloud_object_as_io(cls, container_name, object_name):
  221. provider = settings.CLOUD_BROWSER_APACHE_LIBCLOUD_PROVIDER.lower()
  222. account = settings.CLOUD_BROWSER_APACHE_LIBCLOUD_ACCOUNT
  223. key = settings.CLOUD_BROWSER_APACHE_LIBCLOUD_SECRET_KEY
  224. driver = get_driver(DriverType.STORAGE, provider)
  225. client = driver(account, key)
  226. cloud_container = client.get_container(container_name)
  227. cloud_object = cloud_container.get_object(object_name)
  228. return iterable_to_io(cloud_object.as_stream())
  229. class TextDownloadAPI(APIView):
  230. permission_classes = (IsAuthenticated, IsProjectUser, IsAdminUser)
  231. renderer_classes = (CSVRenderer, JSONLRenderer)
  232. def get(self, request, *args, **kwargs):
  233. format = request.query_params.get('q')
  234. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  235. documents = project.documents.all()
  236. painter = self.select_painter(format)
  237. # json1 format prints text labels while json format prints annotations with label ids
  238. # json1 format - "labels": [[0, 15, "PERSON"], ..]
  239. # json format - "annotations": [{"label": 5, "start_offset": 0, "end_offset": 2, "user": 1},..]
  240. if format == "json1":
  241. labels = project.labels.all()
  242. data = JSONPainter.paint_labels(documents, labels)
  243. else:
  244. data = painter.paint(documents)
  245. return Response(data)
  246. def select_painter(self, format):
  247. if format == 'csv':
  248. return CSVPainter()
  249. elif format == 'json' or format == "json1":
  250. return JSONPainter()
  251. else:
  252. raise ValidationError('format {} is invalid.'.format(format))