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