# Draws fig-threshold.html (1200 x 1000) from results.tsv and fig-frames.html (1200 x 560) from the three corner crops crop-<w>.png.
# usage: python3 figs.py results.tsv
import csv, sys, collections
rows = list(csv.DictReader(open(sys.argv[1]), delimiter='\t'))
def ok(r, k): return int(r[k]) == int(r['frames'])
def thr(by, k):
    ws = sorted(by)
    for i, w in enumerate(ws):
        if all(ok(r, k) for w2 in ws[i:] for r in by[w2]): return by[w][0]['px_per_module']
    return None
INK, DARK, LIGHT, RED = '#17211c', '#2f6b4f', '#a9c4b6', '#b3412c'
def page(h, w=1200): return f'<!doctype html><meta charset=utf-8><body style="margin:0;background:#fff;font-family:Arial,Helvetica,sans-serif"><div style="position:relative;width:{w}px;height:{h}px;background:#fff">'
def t(out, left, top, txt, size=28, color=INK, bold=False):
    out.append(f'<div style="position:absolute;white-space:nowrap;left:{left:.0f}px;top:{top:.0f}px;font-size:{size}px;line-height:{int(size*1.25)}px;color:{color};{"font-weight:700;" if bold else ""}">{txt}</div>')
def bar(out, left, top, w, color, h=34): out.append(f'<div style="position:absolute;left:{left:.0f}px;top:{top:.0f}px;width:{w:.0f}px;height:{h}px;background:{color}"></div>')

h = [page(1000)]
t(h, 40, 20, 'Pixels per module needed to read every frame', 34, bold=True)
t(h, 40, 68, 'Dark: OpenCV classic decoder. Light: jsQR. Both bitrates, 31 frames each.', 28, '#3d4a43')
X0, W, MAX = 330, 800.0, 9.0
x = lambda v: X0 + W * v / MAX
y = 150
for pre, nm in (('short-', 'short link'), ('long-', 'long link')):
    for e in 'LMQH':
        q = pre + e; by = collections.defaultdict(list)
        for r in rows:
            if r['qr'] == q: by[int(r['user_width_px'])].append(r)
        mod = by[60][0]['modules']
        t(h, 40, y + 14, f'{pre[:-1]} {e}, {mod}', 28)
        for k, col, dy in (('cv_classic', DARK, 0), ('jsqr', LIGHT, 40)):
            v = thr(by, k)
            if v is None:
                bar(h, X0, y + dy, x(7.35) - X0, '#e8e8e8'); t(h, x(7.35) + 12, y + dy + 1, 'none to 7.35', 28, RED, True)
            else:
                v = float(v); bar(h, X0, y + dy, x(v) - X0, col); t(h, x(v) + 12, y + dy + 1, f'{v:.2f}', 28, INK if col == DARK else '#3d4a43', True)
        y += 100
t(h, 40, 950, 'Label: link, error level, modules per side. Axis starts at 0 px per module.', 28, '#3d4a43')
h.append('</div>'); open('fig-threshold.html', 'w').write(''.join(h))

# frames figure: three crops of the same decoded frame region, 1.5 Mbps, short link, level M
cells = {}
for r in rows:
    if r['qr'] == 'short-M' and r['group'] == 'A-short' and r['bitrate'] == '1.5M': cells[int(r['user_width_px'])] = r
f = [page(560)]
t(f, 40, 16, 'The same code at three sizes after x264 at 1.5 Mbps', 34, bold=True)
for i, w in enumerate((60, 90, 180)):
    r = cells[w]; x0 = 40 + i * 384
    f.append(f'<img src="crop-{w}.png" style="position:absolute;left:{x0}px;top:70px;width:352px;height:352px;image-rendering:pixelated;border:2px solid #17211c">')
    t(f, x0, 440, f'{w} px, {float(r["px_per_module"]):.1f} per module', 28, bold=True)
    t(f, x0, 478, f'OpenCV {r["cv_classic"]} of 31', 28, '#3d4a43')
    t(f, x0, 514, f'jsQR {r["jsqr"]} of 31', 28, '#3d4a43')
f.append('</div>'); open('fig-frames.html', 'w').write(''.join(f))
