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.

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