# Reads results.tsv, prints the tables used on the page. Every number on the page comes from this output.
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 cell(r): return f"{r['cv_classic']}/{r['cv_aruco']}/{r['jsqr']}"
print('cell format: OpenCV classic / OpenCV Aruco / jsQR frames decoded out of', rows[0]['frames'])
for g in ['A-short', 'B-long']:
    print(f'\n== {g}: rows = error correction + user width px, columns = bitrate')
    print('qr\tmodules\twidth_px\tpx_per_module\t1.5M\t6M')
    key = collections.OrderedDict()
    for r in rows:
        if r['group'] == g: key.setdefault((r['qr'], r['user_width_px']), {})[r['bitrate']] = r
    for (q, w), d in key.items():
        r = d['1.5M']; print(f"{q}\t{r['modules']}\t{w}\t{r['px_per_module']}\t{cell(d['1.5M'])}\t{cell(d['6M'])}")
print('\n== threshold: smallest width such that the decoder read all 31 frames at BOTH bitrates at that width and at every larger width tested (px_per_module in brackets; none = not reached by 360 px)')
KEYS = [('classic', 'cv_classic'), ('aruco', 'cv_aruco'), ('jsqr', 'jsqr')]
def thr(by, ks):
    ws = sorted(by)
    for i, w in enumerate(ws):
        if all(ok(r, k) for w2 in ws[i:] for r in by[w2] for k in ks): return w
    return None
for g in ['A-short', 'B-long']:
    for e in 'LMQH':
        q = ('short-' if g == 'A-short' else 'long-') + e
        by = collections.defaultdict(list)
        for r in rows:
            if r['qr'] == q: by[int(r['user_width_px'])].append(r)
        out = []
        for name, ks in [(n, [k]) for n, k in KEYS] + [('all3', [k for _, k in KEYS])]:
            w = thr(by, ks)
            out.append(f"{name} {w}px ({by[w][0]['px_per_module']})" if w else f"{name} none")
        print(f"{q}: modules {by[60][0]['modules']}; " + '; '.join(out))
def lum(h):
    c = [int(h[i:i+2], 16) / 255 for i in (1, 3, 5)]
    c = [x / 12.92 if x <= 0.03928 else ((x + 0.055) / 1.055) ** 2.4 for x in c]
    return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]
def ratio(a, b):
    x, y = sorted([lum(a), lum(b)], reverse=True); return f'{(x + 0.05) / (y + 0.05):.2f}:1'
CONTRAST = {n: ratio(d, l) for n, (d, l) in {'c-dkgray': ('#444444', '#ffffff'), 'c-midgray': ('#888888', '#ffffff'), 'c-ltgray': ('#bbbbbb', '#ffffff'), 'c-blue': ('#1a3cff', '#ffffff'), 'c-yellow': ('#ffd400', '#ffffff'), 'c-inverted': ('#ffffff', '#000000'), 'short-M': ('#000000', '#ffffff')}.items()}
print('\n== C-colors (width 180 px = 4.86 px/module, short link, ECC M; columns: name, contrast ratio of the two colors (WCAG formula), bitrate, OpenCV classic/Aruco/jsQR)')
for r in rows:
    if r['group'] == 'C-colors': print(f"{r['qr']}\t{CONTRAST.get(r['qr'], '')}\t{r['bitrate']}\t{cell(r)}")
print('\n== D-margin (short link, ECC M, margin 0 modules vs tool default 4)')
for r in rows:
    if r['group'] == 'D-margin': print(f"{r['qr']}\t{r['user_width_px']}\t{r['bitrate']}\t{r['px_per_module']}\t{cell(r)}")
print('\n== X control (no overlay): expect 0/0/0')
for r in rows:
    if r['group'].startswith('X'): print(r['bitrate'], cell(r), 'bytes', r['bytes'])
print('\n== file sizes of A-short-M at 240 px', [(r['bitrate'], r['bytes']) for r in rows if r['qr'] == 'short-M' and r['user_width_px'] == '240' and r['group'] == 'A-short'])
