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.

310 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 LabelList(generics.ListCreateAPIView):
  80. queryset = Label.objects.all()
  81. serializer_class = LabelSerializer
  82. pagination_class = None
  83. permission_classes = (IsAuthenticated, IsProjectUser, IsAdminUserAndWriteOnly)
  84. def get_queryset(self):
  85. queryset = self.queryset.filter(project=self.kwargs['project_id'])
  86. return queryset
  87. def perform_create(self, serializer):
  88. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  89. serializer.save(project=project)
  90. class LabelDetail(generics.RetrieveUpdateDestroyAPIView):
  91. queryset = Label.objects.all()
  92. serializer_class = LabelSerializer
  93. lookup_url_kwarg = 'label_id'
  94. permission_classes = (IsAuthenticated, IsProjectUser, IsAdminUserAndWriteOnly)
  95. class DocumentList(generics.ListCreateAPIView):
  96. queryset = Document.objects.all()
  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, IsProjectUser, IsAdminUserAndWriteOnly)
  104. def get_queryset(self):
  105. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  106. queryset = self.queryset.filter(project=project)
  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, IsProjectUser, IsAdminUserAndWriteOnly)
  118. class AnnotationList(generics.ListCreateAPIView):
  119. pagination_class = None
  120. permission_classes = (IsAuthenticated, IsProjectUser)
  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. self.queryset = model.objects.filter(document=self.kwargs['doc_id'],
  129. user=self.request.user)
  130. return self.queryset
  131. def create(self, request, *args, **kwargs):
  132. request.data['document'] = self.kwargs['doc_id']
  133. return super().create(request, args, kwargs)
  134. def perform_create(self, serializer):
  135. doc = get_object_or_404(Document, pk=self.kwargs['doc_id'])
  136. serializer.save(document=doc, user=self.request.user)
  137. class AnnotationDetail(generics.RetrieveUpdateDestroyAPIView):
  138. lookup_url_kwarg = 'annotation_id'
  139. permission_classes = (IsAuthenticated, IsProjectUser, IsOwnAnnotation)
  140. def get_serializer_class(self):
  141. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  142. self.serializer_class = project.get_annotation_serializer()
  143. return self.serializer_class
  144. def get_queryset(self):
  145. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  146. model = project.get_annotation_class()
  147. self.queryset = model.objects.all()
  148. return self.queryset
  149. class TextUploadAPI(APIView):
  150. parser_classes = (MultiPartParser,)
  151. permission_classes = (IsAuthenticated, IsProjectUser, IsAdminUser)
  152. def post(self, request, *args, **kwargs):
  153. if 'file' not in request.data:
  154. raise ParseError('Empty content')
  155. self.save_file(
  156. user=request.user,
  157. file=request.data['file'],
  158. file_format=request.data['format'],
  159. project_id=kwargs['project_id'],
  160. )
  161. return Response(status=status.HTTP_201_CREATED)
  162. @classmethod
  163. def save_file(cls, user, file, file_format, project_id):
  164. project = get_object_or_404(Project, pk=project_id)
  165. parser = cls.select_parser(file_format)
  166. data = parser.parse(file)
  167. storage = project.get_storage(data)
  168. storage.save(user)
  169. @classmethod
  170. def select_parser(cls, file_format):
  171. if file_format == 'plain':
  172. return PlainTextParser()
  173. elif file_format == 'csv':
  174. return CSVParser()
  175. elif file_format == 'json':
  176. return JSONParser()
  177. elif file_format == 'conll':
  178. return CoNLLParser()
  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))