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.

445 lines
13 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. data = []
  287. for i, line in enumerate(file, start=1):
  288. if len(data) >= IMPORT_BATCH_SIZE:
  289. yield data
  290. data = []
  291. try:
  292. j = json.loads(line)
  293. j['meta'] = json.dumps(j.get('meta', {}))
  294. data.append(j)
  295. except json.decoder.JSONDecodeError:
  296. raise FileParseException(line_num=i, line=line)
  297. if data:
  298. yield data
  299. class JSONLRenderer(JSONRenderer):
  300. def render(self, data, accepted_media_type=None, renderer_context=None):
  301. """
  302. Render `data` into JSON, returning a bytestring.
  303. """
  304. if data is None:
  305. return bytes()
  306. if not isinstance(data, list):
  307. data = [data]
  308. for d in data:
  309. yield json.dumps(d,
  310. cls=self.encoder_class,
  311. ensure_ascii=self.ensure_ascii,
  312. allow_nan=not self.strict) + '\n'
  313. class JSONPainter(object):
  314. def paint(self, documents):
  315. serializer = DocumentSerializer(documents, many=True)
  316. data = []
  317. for d in serializer.data:
  318. d['meta'] = json.loads(d['meta'])
  319. for a in d['annotations']:
  320. a.pop('id')
  321. a.pop('prob')
  322. a.pop('document')
  323. data.append(d)
  324. return data
  325. class CSVPainter(JSONPainter):
  326. def paint(self, documents):
  327. data = super().paint(documents)
  328. res = []
  329. for d in data:
  330. annotations = d.pop('annotations')
  331. for a in annotations:
  332. res.append({**d, **a})
  333. return res
  334. class Color:
  335. def __init__(self, red, green, blue):
  336. self.red = red
  337. self.green = green
  338. self.blue = blue
  339. @property
  340. def contrast_color(self):
  341. """Generate black or white color.
  342. Ensure that text and background color combinations provide
  343. sufficient contrast when viewed by someone having color deficits or
  344. when viewed on a black and white screen.
  345. Algorithm from w3c:
  346. * https://www.w3.org/TR/AERT/#color-contrast
  347. """
  348. return Color.white() if self.brightness < 128 else Color.black()
  349. @property
  350. def brightness(self):
  351. return ((self.red * 299) + (self.green * 587) + (self.blue * 114)) / 1000
  352. @property
  353. def hex(self):
  354. return '#{:02x}{:02x}{:02x}'.format(self.red, self.green, self.blue)
  355. @classmethod
  356. def white(cls):
  357. return cls(red=255, green=255, blue=255)
  358. @classmethod
  359. def black(cls):
  360. return cls(red=0, green=0, blue=0)
  361. @classmethod
  362. def random(cls, seed=None):
  363. rgb = Random(seed).choices(range(256), k=3)
  364. return cls(*rgb)