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.

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