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.

504 lines
16 KiB

5 years ago
5 years ago
5 years ago
  1. import csv
  2. import io
  3. import itertools
  4. import json
  5. import re
  6. from collections import defaultdict
  7. import conllu
  8. from chardet import UniversalDetector
  9. from django.db import transaction
  10. from django.conf import settings
  11. from colour import Color
  12. import pyexcel
  13. from rest_framework.renderers import JSONRenderer
  14. from seqeval.metrics.sequence_labeling import get_entities
  15. from .exceptions import FileParseException
  16. from .models import Label
  17. from .serializers import DocumentSerializer, LabelSerializer
  18. def extract_label(tag):
  19. ptn = re.compile(r'(B|I|E|S)-(.+)')
  20. m = ptn.match(tag)
  21. if m:
  22. return m.groups()[1]
  23. else:
  24. return tag
  25. class BaseStorage(object):
  26. def __init__(self, data, project):
  27. self.data = data
  28. self.project = project
  29. @transaction.atomic
  30. def save(self, user):
  31. raise NotImplementedError()
  32. def save_doc(self, data):
  33. serializer = DocumentSerializer(data=data, many=True)
  34. serializer.is_valid(raise_exception=True)
  35. doc = serializer.save(project=self.project)
  36. return doc
  37. def save_label(self, data):
  38. serializer = LabelSerializer(data=data, many=True)
  39. serializer.is_valid(raise_exception=True)
  40. label = serializer.save(project=self.project)
  41. return label
  42. def save_annotation(self, data, user):
  43. annotation_serializer = self.project.get_annotation_serializer()
  44. serializer = annotation_serializer(data=data, many=True)
  45. serializer.is_valid(raise_exception=True)
  46. annotation = serializer.save(user=user)
  47. return annotation
  48. @classmethod
  49. def extract_label(cls, data):
  50. return [d.get('labels', []) for d in data]
  51. @classmethod
  52. def exclude_created_labels(cls, labels, created):
  53. return [label for label in labels if label not in created]
  54. @classmethod
  55. def to_serializer_format(cls, labels, created):
  56. existing_shortkeys = {(label.suffix_key, label.prefix_key)
  57. for label in created.values()}
  58. serializer_labels = []
  59. for label in sorted(labels):
  60. serializer_label = {'text': label}
  61. shortkey = cls.get_shortkey(label, existing_shortkeys)
  62. if shortkey:
  63. serializer_label['suffix_key'] = shortkey[0]
  64. serializer_label['prefix_key'] = shortkey[1]
  65. existing_shortkeys.add(shortkey)
  66. background_color = Color(pick_for=label)
  67. text_color = Color('white') if background_color.get_luminance() < 0.5 else Color('black')
  68. serializer_label['background_color'] = background_color.hex
  69. serializer_label['text_color'] = text_color.hex
  70. serializer_labels.append(serializer_label)
  71. return serializer_labels
  72. @classmethod
  73. def get_shortkey(cls, label, existing_shortkeys):
  74. model_prefix_keys = [key for (key, _) in Label.PREFIX_KEYS]
  75. prefix_keys = [None] + model_prefix_keys
  76. model_suffix_keys = {key for (key, _) in Label.SUFFIX_KEYS}
  77. suffix_keys = [key for key in label.lower() if key in model_suffix_keys]
  78. for shortkey in itertools.product(suffix_keys, prefix_keys):
  79. if shortkey not in existing_shortkeys:
  80. return shortkey
  81. return None
  82. @classmethod
  83. def update_saved_labels(cls, saved, new):
  84. for label in new:
  85. saved[label.text] = label
  86. return saved
  87. class PlainStorage(BaseStorage):
  88. @transaction.atomic
  89. def save(self, user):
  90. for text in self.data:
  91. self.save_doc(text)
  92. class ClassificationStorage(BaseStorage):
  93. """Store json for text classification.
  94. The format is as follows:
  95. {"text": "Python is awesome!", "labels": ["positive"]}
  96. ...
  97. """
  98. @transaction.atomic
  99. def save(self, user):
  100. saved_labels = {label.text: label for label in self.project.labels.all()}
  101. for data in self.data:
  102. docs = self.save_doc(data)
  103. labels = self.extract_label(data)
  104. unique_labels = self.extract_unique_labels(labels)
  105. unique_labels = self.exclude_created_labels(unique_labels, saved_labels)
  106. unique_labels = self.to_serializer_format(unique_labels, saved_labels)
  107. new_labels = self.save_label(unique_labels)
  108. saved_labels = self.update_saved_labels(saved_labels, new_labels)
  109. annotations = self.make_annotations(docs, labels, saved_labels)
  110. self.save_annotation(annotations, user)
  111. @classmethod
  112. def extract_unique_labels(cls, labels):
  113. return set(itertools.chain(*labels))
  114. @classmethod
  115. def make_annotations(cls, docs, labels, saved_labels):
  116. annotations = []
  117. for doc, label in zip(docs, labels):
  118. for name in label:
  119. label = saved_labels[name]
  120. annotations.append({'document': doc.id, 'label': label.id})
  121. return annotations
  122. class SequenceLabelingStorage(BaseStorage):
  123. """Upload jsonl for sequence labeling.
  124. The format is as follows:
  125. {"text": "Python is awesome!", "labels": [[0, 6, "Product"],]}
  126. ...
  127. """
  128. @transaction.atomic
  129. def save(self, user):
  130. saved_labels = {label.text: label for label in self.project.labels.all()}
  131. for data in self.data:
  132. docs = self.save_doc(data)
  133. labels = self.extract_label(data)
  134. unique_labels = self.extract_unique_labels(labels)
  135. unique_labels = self.exclude_created_labels(unique_labels, saved_labels)
  136. unique_labels = self.to_serializer_format(unique_labels, saved_labels)
  137. new_labels = self.save_label(unique_labels)
  138. saved_labels = self.update_saved_labels(saved_labels, new_labels)
  139. annotations = self.make_annotations(docs, labels, saved_labels)
  140. self.save_annotation(annotations, user)
  141. @classmethod
  142. def extract_unique_labels(cls, labels):
  143. return set([label for _, _, label in itertools.chain(*labels)])
  144. @classmethod
  145. def make_annotations(cls, docs, labels, saved_labels):
  146. annotations = []
  147. for doc, spans in zip(docs, labels):
  148. for span in spans:
  149. start_offset, end_offset, name = span
  150. label = saved_labels[name]
  151. annotations.append({'document': doc.id,
  152. 'label': label.id,
  153. 'start_offset': start_offset,
  154. 'end_offset': end_offset})
  155. return annotations
  156. class Seq2seqStorage(BaseStorage):
  157. """Store json for seq2seq.
  158. The format is as follows:
  159. {"text": "Hello, World!", "labels": ["こんにちは、世界!"]}
  160. ...
  161. """
  162. @transaction.atomic
  163. def save(self, user):
  164. for data in self.data:
  165. doc = self.save_doc(data)
  166. labels = self.extract_label(data)
  167. annotations = self.make_annotations(doc, labels)
  168. self.save_annotation(annotations, user)
  169. @classmethod
  170. def make_annotations(cls, docs, labels):
  171. annotations = []
  172. for doc, texts in zip(docs, labels):
  173. for text in texts:
  174. annotations.append({'document': doc.id, 'text': text})
  175. return annotations
  176. class FileParser(object):
  177. def parse(self, file):
  178. raise NotImplementedError()
  179. class CoNLLParser(FileParser):
  180. """Uploads CoNLL format file.
  181. The file format is tab-separated values.
  182. A blank line is required at the end of a sentence.
  183. For example:
  184. ```
  185. EU B-ORG
  186. rejects O
  187. German B-MISC
  188. call O
  189. to O
  190. boycott O
  191. British B-MISC
  192. lamb O
  193. . O
  194. Peter B-PER
  195. Blackburn I-PER
  196. ...
  197. ```
  198. """
  199. def parse(self, file):
  200. data = []
  201. file = EncodedIO(file)
  202. file = io.TextIOWrapper(file, encoding=file.encoding)
  203. # Add check exception
  204. field_parsers = {
  205. "ne": lambda line, i: conllu.parser.parse_nullable_value(line[i]),
  206. }
  207. gen_parser = conllu.parse_incr(
  208. file,
  209. fields=("form", "ne"),
  210. field_parsers=field_parsers
  211. )
  212. try:
  213. for sentence in gen_parser:
  214. if not sentence:
  215. continue
  216. if len(data) >= settings.IMPORT_BATCH_SIZE:
  217. yield data
  218. data = []
  219. words, labels = [], []
  220. for item in sentence:
  221. word = item.get("form")
  222. tag = item.get("ne")
  223. if tag is not None:
  224. char_left = sum(map(len, words)) + len(words)
  225. char_right = char_left + len(word)
  226. span = [char_left, char_right, tag]
  227. labels.append(span)
  228. words.append(word)
  229. # Create and add JSONL
  230. data.append({'text': ' '.join(words), 'labels': labels})
  231. except conllu.parser.ParseException as e:
  232. raise FileParseException(line_num=-1, line=str(e))
  233. if data:
  234. yield data
  235. class PlainTextParser(FileParser):
  236. """Uploads plain text.
  237. The file format is as follows:
  238. ```
  239. EU rejects German call to boycott British lamb.
  240. President Obama is speaking at the White House.
  241. ...
  242. ```
  243. """
  244. def parse(self, file):
  245. file = EncodedIO(file)
  246. file = io.TextIOWrapper(file, encoding=file.encoding)
  247. while True:
  248. batch = list(itertools.islice(file, settings.IMPORT_BATCH_SIZE))
  249. if not batch:
  250. break
  251. yield [{'text': line.strip()} for line in batch]
  252. class CSVParser(FileParser):
  253. """Uploads csv file.
  254. The file format is comma separated values.
  255. Column names are required at the top of a file.
  256. For example:
  257. ```
  258. text, label
  259. "EU rejects German call to boycott British lamb.",Politics
  260. "President Obama is speaking at the White House.",Politics
  261. "He lives in Newark, Ohio.",Other
  262. ...
  263. ```
  264. """
  265. def parse(self, file):
  266. file = EncodedIO(file)
  267. file = io.TextIOWrapper(file, encoding=file.encoding)
  268. reader = csv.reader(file)
  269. yield from ExcelParser.parse_excel_csv_reader(reader)
  270. class ExcelParser(FileParser):
  271. def parse(self, file):
  272. excel_book = pyexcel.iget_book(file_type="xlsx", file_content=file.read())
  273. # Handle multiple sheets
  274. for sheet_name in excel_book.sheet_names():
  275. reader = excel_book[sheet_name].to_array()
  276. yield from self.parse_excel_csv_reader(reader)
  277. @staticmethod
  278. def parse_excel_csv_reader(reader):
  279. columns = next(reader)
  280. data = []
  281. if len(columns) == 1 and columns[0] != 'text':
  282. data.append({'text': columns[0]})
  283. for i, row in enumerate(reader, start=2):
  284. if len(data) >= settings.IMPORT_BATCH_SIZE:
  285. yield data
  286. data = []
  287. # Only text column
  288. if len(row) == len(columns) and len(row) == 1:
  289. data.append({'text': row[0]})
  290. # Text, labels and metadata columns
  291. elif len(row) == len(columns) and len(row) >= 2:
  292. text, label = row[:2]
  293. meta = json.dumps(dict(zip(columns[2:], row[2:])))
  294. j = {'text': text, 'labels': [label], 'meta': meta}
  295. data.append(j)
  296. else:
  297. raise FileParseException(line_num=i, line=row)
  298. if data:
  299. yield data
  300. class JSONParser(FileParser):
  301. def parse(self, file):
  302. file = EncodedIO(file)
  303. file = io.TextIOWrapper(file, encoding=file.encoding)
  304. data = []
  305. for i, line in enumerate(file, start=1):
  306. if len(data) >= settings.IMPORT_BATCH_SIZE:
  307. yield data
  308. data = []
  309. try:
  310. j = json.loads(line)
  311. j['meta'] = json.dumps(j.get('meta', {}))
  312. data.append(j)
  313. except json.decoder.JSONDecodeError:
  314. raise FileParseException(line_num=i, line=line)
  315. if data:
  316. yield data
  317. class JSONLRenderer(JSONRenderer):
  318. def render(self, data, accepted_media_type=None, renderer_context=None):
  319. """
  320. Render `data` into JSON, returning a bytestring.
  321. """
  322. if data is None:
  323. return bytes()
  324. if not isinstance(data, list):
  325. data = [data]
  326. for d in data:
  327. yield json.dumps(d,
  328. cls=self.encoder_class,
  329. ensure_ascii=self.ensure_ascii,
  330. allow_nan=not self.strict) + '\n'
  331. class JSONPainter(object):
  332. def paint(self, documents):
  333. serializer = DocumentSerializer(documents, many=True)
  334. data = []
  335. for d in serializer.data:
  336. d['meta'] = json.loads(d['meta'])
  337. for a in d['annotations']:
  338. a.pop('id')
  339. a.pop('prob')
  340. a.pop('document')
  341. data.append(d)
  342. return data
  343. @staticmethod
  344. def paint_labels(documents, labels):
  345. serializer_labels = LabelSerializer(labels, many=True)
  346. serializer = DocumentSerializer(documents, many=True)
  347. data = []
  348. for d in serializer.data:
  349. labels = []
  350. for a in d['annotations']:
  351. label_obj = [x for x in serializer_labels.data if x['id'] == a['label']][0]
  352. label_text = label_obj['text']
  353. label_start = a['start_offset']
  354. label_end = a['end_offset']
  355. labels.append([label_start, label_end, label_text])
  356. d.pop('annotations')
  357. d['labels'] = labels
  358. d['meta'] = json.loads(d['meta'])
  359. data.append(d)
  360. return data
  361. class CSVPainter(JSONPainter):
  362. def paint(self, documents):
  363. data = super().paint(documents)
  364. res = []
  365. for d in data:
  366. annotations = d.pop('annotations')
  367. for a in annotations:
  368. res.append({**d, **a})
  369. return res
  370. def iterable_to_io(iterable, buffer_size=io.DEFAULT_BUFFER_SIZE):
  371. """See https://stackoverflow.com/a/20260030/3817588."""
  372. class IterStream(io.RawIOBase):
  373. def __init__(self):
  374. self.leftover = None
  375. def readable(self):
  376. return True
  377. def readinto(self, b):
  378. try:
  379. l = len(b) # We're supposed to return at most this much
  380. chunk = self.leftover or next(iterable)
  381. output, self.leftover = chunk[:l], chunk[l:]
  382. b[:len(output)] = output
  383. return len(output)
  384. except StopIteration:
  385. return 0 # indicate EOF
  386. return io.BufferedReader(IterStream(), buffer_size=buffer_size)
  387. class EncodedIO(io.RawIOBase):
  388. def __init__(self, fobj, buffer_size=io.DEFAULT_BUFFER_SIZE, default_encoding='utf-8'):
  389. buffer = b''
  390. detector = UniversalDetector()
  391. while True:
  392. read = fobj.read(buffer_size)
  393. detector.feed(read)
  394. buffer += read
  395. if detector.done or len(read) < buffer_size:
  396. break
  397. if detector.done:
  398. self.encoding = detector.result['encoding']
  399. else:
  400. self.encoding = default_encoding
  401. self._fobj = fobj
  402. self._buffer = buffer
  403. def readable(self):
  404. return self._fobj.readable()
  405. def readinto(self, b):
  406. l = len(b)
  407. chunk = self._buffer or self._fobj.read(l)
  408. output, self._buffer = chunk[:l], chunk[l:]
  409. b[:len(output)] = output
  410. return len(output)