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.

318 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
  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. for d in annotations.values('label__text', 'user__username').annotate(Count('label'), Count('user')):
  75. label_count[d['label__text']] += d['label__count']
  76. user_count[d['user__username']] += d['user__count']
  77. return label_count, user_count
  78. class ApproveLabelsAPI(APIView):
  79. permission_classes = (IsAuthenticated, IsProjectUser, IsAdminUser)
  80. def post(self, request, *args, **kwargs):
  81. approved = self.request.data.get('approved', True)
  82. document = get_object_or_404(Document, pk=self.kwargs['doc_id'])
  83. document.annotations_approved_by = self.request.user if approved else None
  84. document.save()
  85. return Response(DocumentSerializer(document).data)
  86. class LabelList(generics.ListCreateAPIView):
  87. serializer_class = LabelSerializer
  88. pagination_class = None
  89. permission_classes = (IsAuthenticated, IsProjectUser, IsAdminUserAndWriteOnly)
  90. def get_queryset(self):
  91. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  92. return project.labels
  93. def perform_create(self, serializer):
  94. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  95. serializer.save(project=project)
  96. class LabelDetail(generics.RetrieveUpdateDestroyAPIView):
  97. queryset = Label.objects.all()
  98. serializer_class = LabelSerializer
  99. lookup_url_kwarg = 'label_id'
  100. permission_classes = (IsAuthenticated, IsProjectUser, IsAdminUserAndWriteOnly)
  101. class DocumentList(generics.ListCreateAPIView):
  102. serializer_class = DocumentSerializer
  103. filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
  104. search_fields = ('text', )
  105. ordering_fields = ('created_at', 'updated_at', 'doc_annotations__updated_at',
  106. 'seq_annotations__updated_at', 'seq2seq_annotations__updated_at')
  107. filter_class = DocumentFilter
  108. permission_classes = (IsAuthenticated, IsProjectUser, IsAdminUserAndWriteOnly)
  109. def get_queryset(self):
  110. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  111. queryset = project.documents
  112. if project.randomize_document_order:
  113. queryset = queryset.annotate(sort_id=F('id') % self.request.user.id).order_by('sort_id')
  114. return queryset
  115. def perform_create(self, serializer):
  116. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  117. serializer.save(project=project)
  118. class DocumentDetail(generics.RetrieveUpdateDestroyAPIView):
  119. queryset = Document.objects.all()
  120. serializer_class = DocumentSerializer
  121. lookup_url_kwarg = 'doc_id'
  122. permission_classes = (IsAuthenticated, IsProjectUser, IsAdminUserAndWriteOnly)
  123. class AnnotationList(generics.ListCreateAPIView):
  124. pagination_class = None
  125. permission_classes = (IsAuthenticated, IsProjectUser)
  126. def get_serializer_class(self):
  127. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  128. self.serializer_class = project.get_annotation_serializer()
  129. return self.serializer_class
  130. def get_queryset(self):
  131. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  132. model = project.get_annotation_class()
  133. self.queryset = model.objects.filter(document=self.kwargs['doc_id'],
  134. user=self.request.user)
  135. return self.queryset
  136. def create(self, request, *args, **kwargs):
  137. request.data['document'] = self.kwargs['doc_id']
  138. return super().create(request, args, kwargs)
  139. def perform_create(self, serializer):
  140. doc = get_object_or_404(Document, pk=self.kwargs['doc_id'])
  141. serializer.save(document=doc, user=self.request.user)
  142. class AnnotationDetail(generics.RetrieveUpdateDestroyAPIView):
  143. lookup_url_kwarg = 'annotation_id'
  144. permission_classes = (IsAuthenticated, IsProjectUser, IsOwnAnnotation)
  145. def get_serializer_class(self):
  146. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  147. self.serializer_class = project.get_annotation_serializer()
  148. return self.serializer_class
  149. def get_queryset(self):
  150. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  151. model = project.get_annotation_class()
  152. self.queryset = model.objects.all()
  153. return self.queryset
  154. class TextUploadAPI(APIView):
  155. parser_classes = (MultiPartParser,)
  156. permission_classes = (IsAuthenticated, IsProjectUser, IsAdminUser)
  157. def post(self, request, *args, **kwargs):
  158. if 'file' not in request.data:
  159. raise ParseError('Empty content')
  160. self.save_file(
  161. user=request.user,
  162. file=request.data['file'],
  163. file_format=request.data['format'],
  164. project_id=kwargs['project_id'],
  165. )
  166. return Response(status=status.HTTP_201_CREATED)
  167. @classmethod
  168. def save_file(cls, user, file, file_format, project_id):
  169. project = get_object_or_404(Project, pk=project_id)
  170. parser = cls.select_parser(file_format)
  171. data = parser.parse(file)
  172. storage = project.get_storage(data)
  173. storage.save(user)
  174. @classmethod
  175. def select_parser(cls, file_format):
  176. if file_format == 'plain':
  177. return PlainTextParser()
  178. elif file_format == 'csv':
  179. return CSVParser()
  180. elif file_format == 'json':
  181. return JSONParser()
  182. elif file_format == 'conll':
  183. return CoNLLParser()
  184. else:
  185. raise ValidationError('format {} is invalid.'.format(file_format))
  186. class CloudUploadAPI(APIView):
  187. permission_classes = TextUploadAPI.permission_classes
  188. def get(self, request, *args, **kwargs):
  189. try:
  190. project_id = request.query_params['project_id']
  191. file_format = request.query_params['upload_format']
  192. cloud_container = request.query_params['container']
  193. cloud_object = request.query_params['object']
  194. except KeyError as ex:
  195. raise ValidationError('query parameter {} is missing'.format(ex))
  196. try:
  197. cloud_file = self.get_cloud_object_as_io(cloud_container, cloud_object)
  198. except ContainerDoesNotExistError:
  199. raise ValidationError('cloud container {} does not exist'.format(cloud_container))
  200. except ObjectDoesNotExistError:
  201. raise ValidationError('cloud object {} does not exist'.format(cloud_object))
  202. TextUploadAPI.save_file(
  203. user=request.user,
  204. file=cloud_file,
  205. file_format=file_format,
  206. project_id=project_id,
  207. )
  208. next_url = request.query_params.get('next')
  209. if next_url == 'about:blank':
  210. return Response(data='', content_type='text/plain', status=status.HTTP_201_CREATED)
  211. if next_url:
  212. return redirect(next_url)
  213. return Response(status=status.HTTP_201_CREATED)
  214. @classmethod
  215. def get_cloud_object_as_io(cls, container_name, object_name):
  216. provider = settings.CLOUD_BROWSER_APACHE_LIBCLOUD_PROVIDER.lower()
  217. account = settings.CLOUD_BROWSER_APACHE_LIBCLOUD_ACCOUNT
  218. key = settings.CLOUD_BROWSER_APACHE_LIBCLOUD_SECRET_KEY
  219. driver = get_driver(DriverType.STORAGE, provider)
  220. client = driver(account, key)
  221. cloud_container = client.get_container(container_name)
  222. cloud_object = cloud_container.get_object(object_name)
  223. return iterable_to_io(cloud_object.as_stream())
  224. class TextDownloadAPI(APIView):
  225. permission_classes = (IsAuthenticated, IsProjectUser, IsAdminUser)
  226. renderer_classes = (CSVRenderer, JSONLRenderer)
  227. def get(self, request, *args, **kwargs):
  228. format = request.query_params.get('q')
  229. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  230. documents = project.documents.all()
  231. painter = self.select_painter(format)
  232. # json1 format prints text labels while json format prints annotations with label ids
  233. # json1 format - "labels": [[0, 15, "PERSON"], ..]
  234. # json format - "annotations": [{"label": 5, "start_offset": 0, "end_offset": 2, "user": 1},..]
  235. if format == "json1":
  236. labels = project.labels.all()
  237. data = JSONPainter.paint_labels(documents, labels)
  238. else:
  239. data = painter.paint(documents)
  240. return Response(data)
  241. def select_painter(self, format):
  242. if format == 'csv':
  243. return CSVPainter()
  244. elif format == 'json' or format == "json1":
  245. return JSONPainter()
  246. else:
  247. raise ValidationError('format {} is invalid.'.format(format))