#!/usr/bin/env python3

import os
import sys
import json
import base64

def save_image(data_url, fn):
    pref = "data:image/jpeg;base64,"
    if data_url.startswith(pref):
        b = base64.b64decode(data_url[len(pref):])
        ext = 'jpg'
    pref = "data:image/png;base64,"
    if data_url.startswith(pref):
        b = base64.b64decode(data_url[len(pref):])
        ext = 'png'
    fn = f'{fn}.{ext}'
    with open(fn, 'wb') as fd:
        fd.write(b)
    return fn

for r, ds, fs in os.walk('raw/camera-frame'):
    for f in fs:
        fn = os.path.join(r, f)
        with open(fn, 'r') as fd:
            data = json.load(fd)
            phone_model = data.get('phone_model', 'unknown')
            session_id = data.get('session_id', 'unknown')
            seq_num = data.get('seq_num', 'unknown')
            fn = os.path.join('data/frames', f'{phone_model}-{session_id}-{seq_num}')
            fn = save_image(data['image_data_url'], fn)
            print(fn)
