1 #! /usr/bin/env python3
10 from os.path import dirname
11 from subprocess import Popen, PIPE, STDOUT
12 from blessings import Terminal
14 class Heatmap(object):
18 [ 4, 0], [ 4, 2], [ 2, 0], [ 1, 0], [ 2, 2], [ 3, 0], [ 3, 2],
19 [ 3, 4], [ 3, 6], [ 2, 4], [ 1, 2], [ 2, 6], [ 4, 4], [ 4, 6],
23 [ 8, 0], [ 8, 2], [ 6, 0], [ 5, 0], [ 6, 2], [ 7, 0], [ 7, 2],
24 [ 7, 4], [ 7, 6], [ 6, 4], [ 5, 2], [ 6, 6], [ 8, 4], [ 8, 6],
28 [12, 0], [12, 2], [10, 0], [ 9, 0], [10, 2], [11, 0], [ ],
29 [ ], [11, 2], [10, 4], [ 9, 2], [10, 6], [12, 4], [12, 6],
33 [17, 0], [17, 2], [15, 0], [14, 0], [15, 2], [16, 0], [13, 0],
34 [13, 2], [16, 2], [15, 4], [14, 2], [15, 6], [17, 4], [17, 6],
38 [20, 0], [20, 2], [19, 0], [18, 0], [19, 2], [], [], [], [],
39 [19, 4], [18, 2], [19, 6], [20, 4], [20, 6], [], [], [], []
43 [ ], [23, 0], [22, 2], [22, 0], [22, 4], [21, 0], [21, 2],
44 [24, 0], [24, 2], [25, 0], [25, 4], [25, 2], [26, 0], [ ],
48 def set_attr_at(self, block, n, attr, fn, val):
49 blk = self.heatmap[block][n]
51 blk[attr] = fn(blk[attr], val)
53 blk[attr] = fn(None, val)
55 def coord(self, col, row):
56 return self.coords[row][col]
59 def set_attr(orig, new):
62 def set_bg(self, coords, color):
64 self.set_attr_at(block, n, "c", self.set_attr, color)
65 #self.set_attr_at(block, n, "g", self.set_attr, False)
67 def set_tap_info(self, coords, count, cap):
69 def _set_tap_info(o, _count, _cap):
70 ns = 4 - o.count ("\n")
71 return o + "\n" * ns + "%.02f%%" % (float(_count) / float(_cap) * 100)
75 self.heatmap[block][n + 1] = _set_tap_info (self.heatmap[block][n + 1], count, cap)
78 def heatmap_color (v):
79 colors = [ [0.3, 0.3, 1], [0.3, 1, 0.3], [1, 1, 0.3], [1, 0.3, 0.3]]
84 idx1, idx2 = len(colors) - 1, len(colors) - 1
86 val = v * (len(colors) - 1)
87 idx1 = int(floor(val))
89 fb = val - float(idx1)
91 r = (colors[idx2][0] - colors[idx1][0]) * fb + colors[idx1][0]
92 g = (colors[idx2][1] - colors[idx1][1]) * fb + colors[idx1][1]
93 b = (colors[idx2][2] - colors[idx1][2]) * fb + colors[idx1][2]
95 r, g, b = [x * 255 for x in (r, g, b)]
96 return "#%02x%02x%02x" % (int(r), int(g), int(b))
98 def __init__(self, layout):
104 def update_log(self, coords):
106 if not (c, r) in self.log:
108 self.log[(c, r)] = self.log[(c, r)] + 1
109 self.total = self.total + 1
110 if self.max_cnt < self.log[(c, r)]:
111 self.max_cnt = self.log[(c, r)]
113 def get_heatmap(self):
114 with open("%s/heatmap-layout.%s.json" % (dirname(sys.argv[0]), self.layout), "r") as f:
115 self.heatmap = json.load (f)
118 for row in self.coords:
121 self.set_bg (coord, "#d9dae0")
123 for (c, r) in self.log:
124 coords = self.coord(c, r)
129 v = float(self.log[(c, r)]) / cap
130 self.set_bg (coords, self.heatmap_color (v))
131 self.set_tap_info (coords, self.log[(c, r)], self.total)
141 finger_map = [0, 0, 1, 2, 3, 3, 3, 1, 1, 1, 2, 3, 4, 4]
142 for (c, r) in self.log:
143 if r == 5: # thumb cluster
144 if c <= 6: # left side
145 usage[0][4] = usage[0][4] + self.log[(c, r)]
147 usage[1][0] = usage[1][0] + self.log[(c, r)]
154 usage[hand][fm] = usage[hand][fm] + self.log[(c, r)]
157 hand_usage[0] = hand_usage[0] + f
159 hand_usage[1] = hand_usage[1] + f
168 "usage": round(float(hand_usage[0]) / total * 100, 2),
178 "usage": round(float(hand_usage[1]) / total * 100, 2),
190 hmap = ['left', 'right']
191 fmap = ['pinky', 'ring', 'middle', 'index', 'thumb',
192 'thumb', 'index', 'middle', 'ring', 'pinky']
193 for hand_idx in range(len(usage)):
194 hand = usage[hand_idx]
195 for finger_idx in range(len(hand)):
196 stats['hands'][hmap[hand_idx]]['fingers'][fmap[finger_idx + hand_idx * 5]] = round(float(hand[finger_idx]) / total * 100, 2)
199 def dump_all(out_dir, heatmaps):
203 sys.stdout.write("\x1b[2J\x1b[H")
205 print ('{t.underline}{outdir}{t.normal}\n'.format(t=t, outdir=out_dir))
207 keys = list(heatmaps.keys())
211 if len(heatmaps[layer].log) == 0:
214 with open ("%s/%s.json" % (out_dir, layer), "w") as f:
215 json.dump(heatmaps[layer].get_heatmap(), f)
216 stats[layer] = heatmaps[layer].get_stats()
218 left = stats[layer]['hands']['left']
219 right = stats[layer]['hands']['right']
221 print ('{t.bold}{layer}{t.normal} ({total:,} taps):'.format(t=t, layer=layer,
222 total=int(stats[layer]['total-keys'] / 2)))
223 print (('{t.underline} | ' + \
224 'left ({l[usage]:6.2f}%) | ' + \
225 'right ({r[usage]:6.2f}%) |{t.normal}').format(t=t, l=left, r=right))
226 print ((' {t.bright_magenta}pinky{t.white} | {left[pinky]:6.2f}% | {right[pinky]:6.2f}% |\n' + \
227 ' {t.bright_cyan}ring{t.white} | {left[ring]:6.2f}% | {right[ring]:6.2f}% |\n' + \
228 ' {t.bright_blue}middle{t.white} | {left[middle]:6.2f}% | {right[middle]:6.2f}% |\n' + \
229 ' {t.bright_green}index{t.white} | {left[index]:6.2f}% | {right[index]:6.2f}% |\n' + \
230 ' {t.bright_red}thumb{t.white} | {left[thumb]:6.2f}% | {right[thumb]:6.2f}% |\n' + \
231 '').format(left=left['fingers'], right=right['fingers'], t=t))
233 def process_line(line, heatmaps, opts, stamped_log = None):
234 m = re.search ('KL: col=(\d+), row=(\d+), pressed=(\d+), layer=(.*)', line)
237 if stamped_log is not None:
238 if line.startswith("KL:"):
239 print ("%10.10f %s" % (time.time(), line),
240 file = stamped_log, end = '')
243 file = stamped_log, end = '')
246 (c, r, l) = (int(m.group (2)), int(m.group (1)), m.group (4))
247 if (c, r) not in opts.allowed_keys:
250 heatmaps[l].update_log ((c, r))
254 def setup_allowed_keys(opts):
255 if len(opts.only_key):
257 for v in opts.only_key:
258 m = re.search ('(\d+),(\d+)', v)
261 (c, r) = (int(m.group(1)), int(m.group(2)))
262 incmap[(c, r)] = True
265 for r in range(0, 6):
266 for c in range(0, 14):
267 incmap[(c, r)] = True
269 for v in opts.ignore_key:
270 m = re.search ('(\d+),(\d+)', v)
273 (c, r) = (int(m.group(1)), int(m.group(2)))
279 heatmaps = {"Dvorak": Heatmap("Dvorak"),
280 "ADORE": Heatmap("ADORE")
283 out_dir = opts.outdir
285 if not os.path.exists(out_dir):
288 opts.allowed_keys = setup_allowed_keys(opts)
290 if not opts.one_shot:
293 with open("%s/stamped-log" % out_dir, "r") as f:
298 if not process_line(line, heatmaps, opts):
303 stamped_log = open ("%s/stamped-log" % (out_dir), "a+")
308 line = sys.stdin.readline()
311 if not process_line(line, heatmaps, opts, stamped_log):
316 if opts.dump_interval != -1 and cnt >= opts.dump_interval and not opts.one_shot:
318 dump_all(out_dir, heatmaps)
320 dump_all (out_dir, heatmaps)
322 if __name__ == "__main__":
323 parser = argparse.ArgumentParser (description = "keylog to heatmap processor")
324 parser.add_argument ('outdir', action = 'store',
325 help = 'Output directory')
326 parser.add_argument ('--dump-interval', dest = 'dump_interval', action = 'store', type = int,
327 default = 100, help = 'Dump stats and heatmap at every Nth event, -1 for dumping at EOF only')
328 parser.add_argument ('--ignore-key', dest = 'ignore_key', action = 'append', type = str,
329 default = [], help = 'Ignore the key at position (x, y)')
330 parser.add_argument ('--only-key', dest = 'only_key', action = 'append', type = str,
331 default = [], help = 'Only include key at position (x, y)')
332 parser.add_argument ('--one-shot', dest = 'one_shot', action = 'store_true',
333 help = 'Do not load previous data, and do not update it, either.')
334 args = parser.parse_args()
335 if len(args.ignore_key) and len(args.only_key):
336 print ("--ignore-key and --only-key are mutually exclusive, please only use one of them!",