Coverage for 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
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
1import numpy
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 ]
34 def highlight(self, activation, text):
35 activation = activation.detach().cpu().numpy()
37 step_size = (max(activation) - min(activation)) / len(self.color_map)
39 lookup = numpy.array(
40 list(numpy.arange(min(activation), max(activation), step_size))
41 )
43 colors = []
45 for i, act in enumerate(activation):
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)
52 str_ = "<br><br>"
54 for i, (char, color) in enumerate(zip(list(text), colors)):
55 str_ += self._render(char, color)
57 if i % 100 == 0 and i > 0:
58 str_ += "<br>"
60 return str_
62 def highlight_selection(
63 self, activations, text, file_="resources/data/highlight.html", n=10
64 ):
66 ix = numpy.random.choice(activations.shape[1], size=n)
68 rendered = ""
70 for i in ix:
72 rendered += self.highlight(activations[:, i], text)
74 with open(file_, "w") as f:
75 f.write(rendered)
77 @staticmethod
78 def _render(char, color):
79 return '<span style="background-color: {}">{}</span>'.format(color, char)