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.

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