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.

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