#!/usr/bin/env python3 """Generate device compatibility outputs from peacock-ports status.toml files. Outputs: - public/devices/status.json machine-readable; src/pages/devices.astro renders the brand-grouped cards from it at build time - wiki `devices` index page: brand-grouped links - wiki `devices/` one page PER device with the detailed matrix in a marked block; author prose/photos around it are preserved Device images: public/devices/img/.{webp,png,jpg} (git). Both site and wiki reference the same file. Drop one in per device. Source of truth + design: peacock-ports/device/STATUS.md """ import os, json, glob, re, datetime, urllib.request, subprocess, shutil PORTS = os.environ.get('PEACOCK_PORTS', os.path.expanduser('~/Documents/bro/PeacockProject/peacock-ports')) ROOT = os.environ.get('PEACOCK_SITE', os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) DATA = os.path.join(ROOT, 'public') # Astro copies this directory to the build as-is SITE_URL = os.environ.get('SITE_URL', 'https://peacockos.org') WIKI = os.environ.get('WIKI_URL', 'https://wiki.peacockos.org') try: import tomllib except ModuleNotFoundError: import tomli as tomllib GROUPS = [ ('basics', 'Basics', ['flashing', 'recovery', 'screen', 'touch', 'battery', 'usb_net']), ('multimedia', 'Multimedia', ['accel_3d', 'audio', 'camera_rear', 'camera_front', 'camera_flash']), ('connectivity', 'Connectivity', ['wifi', 'bluetooth', 'gps']), ('modem', 'Modem', ['calls', 'sms', 'data']), ('misc', 'Miscellaneous', ['usb_otg', 'fingerprint', 'fde']), ('sensors', 'Sensors', ['accelerometer', 'ambient_light', 'proximity', 'gyroscope', 'haptics']), ] LABELS = {'recovery': 'Recovery (PRP)', 'usb_net': 'USB networking', 'accel_3d': '3D acceleration', 'camera_rear': 'Rear camera', 'camera_front': 'Front camera', 'camera_flash': 'Camera flash', 'gps': 'GPS', 'sms': 'SMS', 'data': 'Mobile data', 'usb_otg': 'USB OTG', 'fde': 'Full-disk encryption', 'ambient_light': 'Ambient light', 'fingerprint': 'Fingerprint'} EMOJI = {'works': 'โœ…', 'partial': '๐ŸŸก', 'broken': 'โŒ', 'untested': 'โšช'} WORD = {'works': 'Works', 'partial': 'Partial', 'broken': 'Broken', 'untested': 'Untested'} MARK_START = '' MARK_END = '' VERIFIED_NOTE = ('Verified so far on each phone: the bootloader, PRP recovery (SSH + touch), ' 'and boot through to the XFCE desktop with working touch. Everything else is **untested**, not broken.') def label(k): return LABELS.get(k, k.replace('_', ' ').capitalize()) def codename(d): return d.get('device', {}).get('codename', d['_port']) def name(d): return d.get('device', {}).get('name', codename(d)) def platform(dev): soc = (dev.get('hardware', {}).get('chipset', '') or '').lower() if 'mediatek' in soc or soc.startswith('mt'): return ('MediaTek', 'MinKernel') if 'qualcomm' in soc or 'snapdragon' in soc or 'msm' in soc or 'apq' in soc: return ('Qualcomm', 'lk2nd') if 'qemu' in soc or dev.get('device', {}).get('type') == 'vm': return ('Virtual', 'โ€”') return (dev.get('hardware', {}).get('architecture', 'โ€”'), 'โ€”') def load(): devs = [] for p in sorted(glob.glob(os.path.join(PORTS, 'device', '*', 'status.toml'))): with open(p, 'rb') as f: d = tomllib.load(f) d['_port'] = os.path.basename(os.path.dirname(p)) devs.append(d) return devs def by_brand(devs): brands = {} for d in devs: brands.setdefault(d.get('device', {}).get('manufacturer', 'Other'), []).append(d) order = sorted(brands, key=lambda b: (b.lower() == 'qemu', b.lower())) # QEMU last return [(b, sorted(brands[b], key=lambda d: name(d))) for b in order] def support_items(dev): sup = dev.get('support', {}) for gkey, glabel, keys in GROUPS: g = sup.get(gkey, {}) rows = [(k, label(k), g[k], g.get(k + '_note')) for k in keys if k in g] if rows: yield glabel, rows def build_images(devs): """Convert each device package's image.* (peacock-ports/device//) into an optimized webp at public/devices/img/.webp. Devs drop the source photo in the port; CI does the conversion.""" os.makedirs(os.path.join(DATA, 'devices', 'img'), exist_ok=True) magick = shutil.which('magick') or shutil.which('convert') cwebp = shutil.which('cwebp') for d in devs: src = next((p for ext in ('png', 'jpg', 'jpeg', 'webp', 'avif') for p in [os.path.join(PORTS, 'device', d['_port'], f'image.{ext}')] if os.path.exists(p)), None) if not src: continue code = codename(d) out = os.path.join(DATA, 'devices', 'img', f'{code}.webp') if magick: subprocess.run([magick, src, '-resize', '800x800>', '-strip', '-quality', '82', out], check=True) elif cwebp: subprocess.run([cwebp, '-quiet', '-q', '82', '-resize', '800', '0', src, '-o', out], check=True) else: shutil.copy(src, os.path.join(DATA, 'devices', 'img', f"{code}.{src.rsplit('.', 1)[1]}")) print(f' image {code}: no webp tool, copied source as-is'); continue print(f' image {code}: {os.path.relpath(src, PORTS)} -> {code}.webp') # ---------------------------------------------------------------- wiki def matrix_md(dev): dd, hw, sw = dev['device'], dev.get('hardware', {}), dev.get('software', {}) lines = ['| | |', '|---|---|'] specs = [('Codename', codename(dev)), ('Chipset', hw.get('chipset')), ('Architecture', hw.get('architecture')), ('Display', hw.get('display')), ('Memory', hw.get('memory')), ('Storage', hw.get('storage')), ('Released', dd.get('released')), ('Ships with', sw.get('original_android')), ('Kernel', sw.get('kernel')), ('Maturity', sw.get('maturity'))] for k, v in specs: if v and str(v) not in ('TODO', 'n/a', '0'): lines.append(f'| **{k}** | {v} |') lines += ['', '| Feature | Status |', '|---|---|'] for glabel, rows in support_items(dev): lines.append(f'| **{glabel}** | |') for k, lab, status, note in rows: cell = f"{EMOJI.get(status, '')} {WORD.get(status, status)}" if note: cell += f" โ€” {note}" lines.append(f'| {lab} | {cell} |') return '\n'.join(lines) def device_stub(dev, block): n, code = name(dev), codename(dev) return (f"# {n}\n\n" f"_Add an overview, install notes and quirks for the {n} here. " f"Device photo: drop `image.png` (or .jpg) into this device's package in " f"`peacock-ports/device/{dev['_port']}/` โ€” CI converts it to webp automatically. " f"The compatibility block below is generated โ€” edit around it, not between the markers._\n\n" f"{MARK_START}\n{block}\n{MARK_END}\n") def replace_marked(content, block): if MARK_START in content and MARK_END in content: pre = content.split(MARK_START)[0] post = content.split(MARK_END, 1)[1] return f"{pre}{MARK_START}\n{block}\n{MARK_END}{post}" return f"{content.rstrip()}\n\n{MARK_START}\n{block}\n{MARK_END}\n" def index_md(devs): lines = ['# Supported devices', '', f'> {VERIFIED_NOTE}', '', 'Each device has its own page with the full compatibility breakdown.', ''] for brand, ds in by_brand(devs): lines.append(f'## {brand}') for d in ds: plat, boot = platform(d) lines.append(f"- [{name(d)}](/devices/{codename(d)}) โ€” `{codename(d)}` ยท {plat} ยท " f"{boot} ยท {d.get('software',{}).get('maturity','')}") lines.append('') return '\n'.join(lines) def token(): t = os.environ.get('WIKI_API_TOKEN') if not t: sf = os.path.expanduser('~/Documents/bro/PeacockProject/infra/peacock-community/SECRETS.api-tokens.txt') if os.path.exists(sf): m = re.search(r'## Wiki\.js.*?TOKEN=(\S+)', open(sf).read(), re.DOTALL) t = m and m.group(1) return t def gql(tok, query, variables=None): req = urllib.request.Request(WIKI + '/graphql', data=json.dumps({'query': query, 'variables': variables or {}}).encode(), headers={'Authorization': 'Bearer ' + tok, 'Content-Type': 'application/json'}) return json.loads(urllib.request.urlopen(req).read().decode()) def wiki_save(tok, pid, path, title, content, desc): common = (f'content:$content,description:$description,editor:"markdown",isPrivate:false,' f'isPublished:true,locale:"en",path:$path,tags:[],title:$title') if pid: q = (f'mutation($content:String!,$description:String!,$path:String!,$title:String!)' f'{{pages{{update(id:{pid},{common}){{responseResult{{succeeded message}}}}}}}}') else: q = (f'mutation($content:String!,$description:String!,$path:String!,$title:String!)' f'{{pages{{create({common}){{responseResult{{succeeded message}} page{{id path}}}}}}}}') r = gql(tok, q, {'content': content, 'description': desc, 'path': path, 'title': title}) node = r['data']['pages']['update' if pid else 'create'] return node['responseResult'], node.get('page') def sync_wiki(devs): tok = token() if not tok: print(' (no WIKI_API_TOKEN โ€” skipping wiki)'); return pages = gql(tok, '{ pages { list { id path } } }')['data']['pages']['list'] pmap = {p['path']: p['id'] for p in pages} rr, _ = wiki_save(tok, pmap.get('devices'), 'devices', 'Supported devices', index_md(devs), 'Devices that run PeacockOS, by brand.') print(' wiki devices (index):', rr['succeeded']) for d in devs: path = f'devices/{codename(d)}'; block = matrix_md(d) if path in pmap: cur = gql(tok, f'{{ pages {{ single(id:{pmap[path]}) {{ content }} }} }}')['data']['pages']['single']['content'] content = replace_marked(cur, block) else: content = device_stub(d, block) rr, _ = wiki_save(tok, pmap.get(path), path, name(d), content, f'{name(d)} on PeacockOS.') print(f' wiki {path}:', rr['succeeded'], '' if rr['succeeded'] else rr.get('message')) def main(): devs = load() print('loaded %d devices: %s' % (len(devs), ', '.join(codename(d) for d in devs))) payload = {'generated': datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'), 'devices': [{k: v for k, v in d.items() if not k.startswith('_')} | {'port': d['_port']} for d in devs]} os.makedirs(os.path.join(DATA, 'devices', 'img'), exist_ok=True) open(os.path.join(DATA, 'devices', 'status.json'), 'w').write(json.dumps(payload, indent=1)) print(' wrote devices/status.json') build_images(devs) sync_wiki(devs) if __name__ == '__main__': main()