Coverage for /home/ubuntu/Documents/Research/mut_p1/flair/flair/visual/activations.py: 100%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

30 statements  

1import numpy 

2 

3 

4class Highlighter(object): 

5 def __init__(self): 

6 self.color_map = [ 

7 "#ff0000", 

8 "#ff4000", 

9 "#ff8000", 

10 "#ffbf00", 

11 "#ffff00", 

12 "#bfff00", 

13 "#80ff00", 

14 "#40ff00", 

15 "#00ff00", 

16 "#00ff40", 

17 "#00ff80", 

18 "#00ffbf", 

19 "#00ffff", 

20 "#00bfff", 

21 "#0080ff", 

22 "#0040ff", 

23 "#0000ff", 

24 "#4000ff", 

25 "#8000ff", 

26 "#bf00ff", 

27 "#ff00ff", 

28 "#ff00bf", 

29 "#ff0080", 

30 "#ff0040", 

31 "#ff0000", 

32 ] 

33 

34 def highlight(self, activation, text): 

35 activation = activation.detach().cpu().numpy() 

36 

37 step_size = (max(activation) - min(activation)) / len(self.color_map) 

38 

39 lookup = numpy.array( 

40 list(numpy.arange(min(activation), max(activation), step_size)) 

41 ) 

42 

43 colors = [] 

44 

45 for i, act in enumerate(activation): 

46 

47 try: 

48 colors.append(self.color_map[numpy.where(act > lookup)[0][-1]]) 

49 except IndexError: 

50 colors.append(len(self.color_map) - 1) 

51 

52 str_ = "<br><br>" 

53 

54 for i, (char, color) in enumerate(zip(list(text), colors)): 

55 str_ += self._render(char, color) 

56 

57 if i % 100 == 0 and i > 0: 

58 str_ += "<br>" 

59 

60 return str_ 

61 

62 def highlight_selection( 

63 self, activations, text, file_="resources/data/highlight.html", n=10 

64 ): 

65 

66 ix = numpy.random.choice(activations.shape[1], size=n) 

67 

68 rendered = "" 

69 

70 for i in ix: 

71 

72 rendered += self.highlight(activations[:, i], text) 

73 

74 with open(file_, "w") as f: 

75 f.write(rendered) 

76 

77 @staticmethod 

78 def _render(char, color): 

79 return '<span style="background-color: {}">{}</span>'.format(color, char)