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.

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