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.

119 lines
3.7 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. import abc
  2. import itertools
  3. from collections import defaultdict
  4. from typing import Any, Dict, List
  5. from django.conf import settings
  6. from api.models import Example, Project
  7. from label_types.models import CategoryType, SpanType
  8. from .exceptions import FileParseException
  9. from .readers import BaseReader
  10. class Writer(abc.ABC):
  11. @abc.abstractmethod
  12. def save(self, reader: BaseReader, project: Project, user, cleaner):
  13. """Save the read contents to DB."""
  14. raise NotImplementedError('Please implement this method in the subclass.')
  15. def errors(self) -> List[Dict[Any, Any]]:
  16. """Return errors."""
  17. raise NotImplementedError('Please implement this method in the subclass.')
  18. def group_by_class(instances):
  19. groups = defaultdict(list)
  20. for instance in instances:
  21. groups[instance.__class__].append(instance)
  22. return groups
  23. class Examples:
  24. def __init__(self, buffer_size: int = settings.IMPORT_BATCH_SIZE):
  25. self.buffer_size = buffer_size
  26. self.buffer = []
  27. def __len__(self):
  28. return len(self.buffer)
  29. @property
  30. def data(self):
  31. return self.buffer
  32. def add(self, data):
  33. self.buffer.append(data)
  34. def clear(self):
  35. self.buffer = []
  36. def is_full(self):
  37. return len(self) >= self.buffer_size
  38. def is_empty(self):
  39. return len(self) == 0
  40. def save_label(self, project: Project):
  41. labels = list(itertools.chain.from_iterable([example.create_label(project) for example in self.buffer]))
  42. labels = list(filter(None, labels))
  43. groups = group_by_class(labels)
  44. for klass, instances in groups.items():
  45. klass.objects.bulk_create(instances, ignore_conflicts=True)
  46. def save_data(self, project: Project) -> List[Example]:
  47. examples = [example.create_data(project) for example in self.buffer]
  48. return Example.objects.bulk_create(examples)
  49. def save_annotation(self, project: Project, user, examples):
  50. # mapping = {label.text: label for label in project.labels.all()}
  51. # Todo: move annotation class
  52. mapping = {}
  53. for model in [CategoryType, SpanType]:
  54. for label in model.objects.all():
  55. mapping[label.text] = label
  56. annotations = list(itertools.chain.from_iterable([
  57. data.create_annotation(user, example, mapping) for data, example in zip(self.buffer, examples)
  58. ]))
  59. groups = group_by_class(annotations)
  60. for klass, instances in groups.items():
  61. klass.objects.bulk_create(instances)
  62. class BulkWriter(Writer):
  63. def __init__(self, batch_size: int):
  64. self.examples = Examples(batch_size)
  65. self._errors = []
  66. def save(self, reader: BaseReader, project: Project, user, cleaner):
  67. it = iter(reader)
  68. while True:
  69. try:
  70. example = next(it)
  71. except StopIteration:
  72. break
  73. try:
  74. example.clean(cleaner)
  75. except FileParseException as err:
  76. self._errors.append(err)
  77. self.examples.add(example)
  78. if self.examples.is_full():
  79. self.create(project, user)
  80. self.examples.clear()
  81. if not self.examples.is_empty():
  82. self.create(project, user)
  83. self.examples.clear()
  84. self._errors.extend(reader.errors)
  85. @property
  86. def errors(self) -> List[Dict[Any, Any]]:
  87. self._errors.sort(key=lambda e: e.line_num)
  88. return [error.dict() for error in self._errors]
  89. def create(self, project: Project, user):
  90. self.examples.save_label(project)
  91. ids = self.examples.save_data(project)
  92. self.examples.save_annotation(project, user, ids)