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.

468 lines
14 KiB

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