| 6 |
| This tool retains the existing quantization and dithering exactly. It does not |
| 7 | run a new lossy quantizer. --textures optionally validates the original ZIP IDs. |
| 8 | """ |
| 9 | import argparse, hashlib, heapq, io, json, multiprocessing, struct, time, zipfile, zlib |
| 10 | from pathlib import Path |
| 11 | from collections import Counter |
| 12 | from concurrent.futures import ProcessPoolExecutor |
| 13 | import numpy as np |
| 14 | from scipy.spatial import cKDTree |
| 15 | from PIL import Image, features as pil_features |
| 16 | NONE = 65535 |
| 17 |
| 18 | def png_read(b): |
| 19 | im=Image.open(io.BytesIO(b));a=np.array(im.convert('RGBA')) |
| 20 | if im.mode=='P': |
| 21 | idx=np.array(im);n=int(idx.max())+1;pal=np.zeros((n,4),np.uint8);pal[:,:3]=np.array(im.getpalette()[:n*3]).reshape(n,3);pal[:,3]=255 |
| 22 | tr=im.info.get('transparency',b'') |
| 23 | if isinstance(tr,int):pal[tr,3]=0 |
| 24 | else:pal[:len(tr),3]=np.frombuffer(tr,dtype=np.uint8) |
| 25 | elif im.mode=='L': |
| 26 | idx=np.array(im);pal=np.arange(256,dtype=np.uint8)[:,None].repeat(4,axis=1);pal[:,3]=255 |
| 27 | else: |
| 28 | pal,inv=np.unique(a.reshape(-1,4),axis=0,return_inverse=True);assert len(pal)<=256;idx=inv.reshape(64,64).astype(np.uint8) |
| 29 | assert np.array_equal(pal[idx],a) |
| 30 | return {'rgba':a,'idx':idx,'pal':pal,'png':b,'mode':im.mode} |
| 31 |
| 32 |
| 33 | def read_reference(path, textures=None): |
| 34 | data = Path(path).read_bytes() |
| 35 | def take(pos, count): |
| 36 | if pos < 0 or count < 0 or pos + count > len(data): |
| 37 | raise ValueError("Truncated reference pack") |
| 38 | return data[pos:pos + count] |
| 39 | n = struct.unpack('<I', take(0, 4))[0] |
| 40 | if n % 12: raise ValueError("Invalid reference emoji table") |
| 41 | n //= 12 |
| 42 | em = [struct.unpack('<HHII', take(4 + i * 12, 12)) for i in range(n)] |
| 43 | pos = 4 + n * 12 |
| 44 | m = struct.unpack('<I', take(pos, 4))[0] |
| 45 | if m % 10: raise ValueError("Invalid reference mask table") |
| 46 | m //= 10 |
| 47 | masks = [struct.unpack('<HII', take(pos + 4 + i * 10, 10)) for i in range(m)] |
| 48 | records = [] |
| 49 | for eid, mid, off, length in sorted(em): |
| 50 | d = png_read(take(off, length)) |
| 51 | d.update(id=eid, mask=mid, kind='emoji') |
| 52 | records.append(d) |
| 53 | for mid, off, length in sorted(masks): |
| 54 | d = png_read(take(off, length)) |
| 55 | d.update(id=mid, mask=NONE, kind='mask') |
| 56 | records.append(d) |
| 57 | if not records or len(records) >= NONE: |
| 58 | raise ValueError("Invalid record count") |
| 59 | for d in records: |
| 60 | if d['rgba'].shape != (64, 64, 4): |
| 61 | raise ValueError("This format requires 64x64 textures") |
| 62 | if len({d['id'] for d in records[:n]}) != n or len({d['id'] for d in records[n:]}) != m: |
| 63 | raise ValueError("Duplicate IDs") |
| 64 | lookup = {d['id']: n + i for i, d in enumerate(records[n:])} |
| 65 | for d in records[:n]: |
| 66 | if d['mask'] != NONE and d['mask'] not in lookup: |
| 67 | raise ValueError("Unknown mask ID") |
| 68 | if textures: |
| 69 | with zipfile.ZipFile(textures) as archive: |
| 70 | for d in records[:n]: |
| 71 | name = f"{d['id'] // 4096}_{d['id'] % 4096}.png" |
| 72 | with Image.open(archive.open(name)) as image: |
| 73 | if image.size != (64, 64): raise ValueError(name) |
| 74 | pngs = [x for x in archive.namelist() if x.lower().endswith('.png')] |
| 75 | if len(pngs) != n: raise ValueError("ZIP/reference emoji count mismatch") |
| 76 | return records, n, lookup, len(data) |
| 77 |
| 78 |
| 79 | def baseline(d): |
| 80 | b = io.BytesIO() |
| 81 | Image.fromarray(d['rgba']).save(b, format='WEBP', lossless=True, |
| 82 | quality=100, method=6, exact=True) |
| 83 | return {'webp': b.getvalue()} |
| 84 | def candidates(): |
| 85 | # Coarse luma/alpha features and nearest exact silhouettes, plus local variant sequences. |
| 86 | fs=[] |
| 87 | for d in R: |
| 88 | a=d['rgba'].astype(np.float32);al=a[:,:,3:]/255 |
| 89 | if d['kind']=='emoji' and d['mask']!=65535:al=R[MASK_LOOKUP[d['mask']]]['rgba'][:,:,:1]/255 |
| 90 | c=a[:,:,:3]*al |
| 91 | gray=c.mean(axis=2);gray=gray/(gray.std()+10) |
| 92 | feat=np.concatenate([gray.reshape(16,4,16,4).mean(axis=(1,3)).ravel(),al.reshape(16,4,16,4).mean(axis=(1,3)).ravel()*2]) |
| 93 | fs.append(feat) |
| 94 | tree=cKDTree(np.array(fs));near=tree.query(fs,k=25)[1] |
| 95 | out=[] |
| 96 | for i,d in enumerate(R): |
| 97 | ids=set(near[i]);ids.update(range(max(0,i-6),min(N,i+7)));ids.discard(i) |
| 98 | out.append(sorted(j for j in ids if R[j]['kind']==d['kind'])) |
| 99 | return out |
| 100 |
| 101 | def encode_delta(i): |
| 102 | a=IDX[i];d=R[i];ch=4 if np.any(d['pal'][:,3]!=255) else 3;pal=len(d['pal'])*ch if d['kind']=='emoji' else 0 |
| 103 | raw=a.tobytes();best={'cost':len(zlib.compress(raw,9))+pal,'parent':-1,'mode':0,'data':zlib.compress(raw,9),'lut':b''} |
| 104 | options=[] |
| 105 | for j in C[i]: |
| 106 | base=IDX[j];nb=len(R[j]['pal']) |
| 107 | cnt=np.bincount((base.astype(np.int32)*256+a).ravel(),minlength=65536).reshape(256,256) |
| 108 | lut=cnt.argmax(axis=1).astype(np.uint8)[:nb] |
| 109 | pred=lut[base] |
| 110 | # One data stream: LUT + mapped-palette residual. Original indices always restored exactly. |
| 111 | for mode,delta in [(1,np.bitwise_xor(a,pred)),(2,a-pred)]: |
| 112 | zz=zlib.compress(lut.tobytes()+delta.tobytes(),9);cost=len(zz)+pal+2 |
| 113 | options.append((cost,j,mode,zz,lut.tobytes())) |
| 114 | options.sort(key=lambda x:x[0]);best3=options[:3] |
| 115 | if best3 and best3[0][0]<best['cost']: |
| 116 | co,j,mo,zz,lut=best3[0];best={'cost':co,'parent':j,'mode':mo,'data':zz,'lut':lut} |
| 117 | return best,best3 |
| 118 | def webp(a): |
| 119 | b=io.BytesIO();Image.fromarray(a).save(b,format='WEBP',lossless=True,quality=100,method=6,exact=True);return b.getvalue() |
| 120 | def encode_delta_webp(i): |
| 121 | d=R[i];res=[];pal=len(d['pal'])*(4 if np.any(d['pal'][:,3]!=255) else 3) if d['kind']=='emoji' else 0 |
| 122 | direct=webp(d['idx']) |
| 123 | for co,j,mo,zz,lut in D[i][1]: |
| 124 | data=zlib.decompress(zz);a=np.frombuffer(data[len(lut):],np.uint8).reshape(64,64);b=webp(a) |
| 125 | res.append((len(b)+len(lut)+pal+2,j,mo,b,lut)) |
| 126 | return direct,sorted(res,key=lambda x:x[0]) |
| 127 |
| 128 | def half_candidates(): |
| 129 | features=[] |
| 130 | for side in range(2): |
| 131 | f=[] |
| 132 | for d in R: |
| 133 | a=d['rgba'].astype(np.float32)[:,side*32:(side+1)*32];al=a[:,:,3:]/255 |
| 134 | if d['kind']=='emoji' and d['mask']!=65535:al=R[MASK_LOOKUP[d['mask']]]['idx'][:,side*32:(side+1)*32,None]/255 |
| 135 | g=(a[:,:,:3]*al).mean(axis=2);g=g/(g.std()+10) |
| 136 | f.append(np.concatenate([g.reshape(16,4,8,4).mean(axis=(1,3)).ravel(),al.reshape(16,4,8,4).mean(axis=(1,3)).ravel()*2])) |
| 137 | features.append(cKDTree(f).query(f,k=13)[1]) |
| 138 | return features |
| 139 |
| 140 | def encode_half(i): |
| 141 | if R[i]['kind']=='mask':return [] |
| 142 | opts=[] |
| 143 | for side in range(2): |
| 144 | candidates=set(int(j) for j in features[side][i] if j!=i and j<NE) |
| 145 | candidates.update(x[1] for x in D[i][1] if x[1]<NE) |
| 146 | a=I[i,:,side*32:(side+1)*32];out=[] |
| 147 | for j in candidates: |
| 148 | base=I[j,:,side*32:(side+1)*32];cnt=np.bincount((base.astype(np.int32)*256+a).ravel(),minlength=65536).reshape(256,256);lut=cnt.argmax(axis=1).astype(np.uint8)[:len(R[j]['pal'])];p=lut[base];delta=a-p |
| 149 | zz=zlib.compress(lut.tobytes()+delta.tobytes(),9) |
| 150 | out.append((len(zz),j,lut,delta)) |
| 151 | out.sort(key=lambda x:x[0]);opts.append(out[:3]) |
| 152 | candidates=[] |
| 153 | for a in opts[0]: |
| 154 | for b in opts[1]: |
| 155 | lut=a[2].tobytes()+b[2].tobytes();delta=np.concatenate([a[3],b[3]],axis=1) |
| 156 | zz=zlib.compress(lut+delta.tobytes(),9);wb=io.BytesIO();Image.fromarray(delta).save(wb,format='WEBP',lossless=True,quality=100,method=6,exact=True);wb=wb.getvalue() |
| 157 | codec,data=(0,zz) if len(zz)<=len(lut)+len(wb) else (1,lut+wb) |
| 158 | candidates.append((len(data)+4,a[1],b[1],codec,data)) |
| 159 | return sorted(candidates)[:4] |
| 160 | def palette(d): |
| 161 | if d['kind']=='mask': |
| 162 | if len(d['pal'])==256 and np.array_equal(d['pal'][:,0],np.arange(256,dtype=np.uint8)): |
| 163 | return 0,b'' # implicit grayscale 0..255 |
| 164 | return 1,d['pal'][:,0].tobytes() |
| 165 | c=4 if np.any(d['pal'][:,3]!=255) else 3 |
| 166 | return c,d['pal'][:,:c].tobytes() |
| 167 |
| 168 | def strip_webp(b): |
| 169 | assert b[:4]==b'RIFF' and b[8:16]==b'WEBPVP8L' |
| 170 | n=struct.unpack_from('<I',b,16)[0] |
| 171 | assert len(b)==20+n+(n&1) |
| 172 | return b[20:20+n] |
| 173 |
| 174 | def wrap_webp(b): |
| 175 | return b'RIFF'+struct.pack('<I',12+len(b)+(len(b)&1))+b'WEBPVP8L'+struct.pack('<I',len(b))+b+(b'\0' if len(b)&1 else b'') |
| 176 |
| 177 | def pack7(b): |
| 178 | acc=0;bits=0;out=bytearray() |
| 179 | for v in b: |
| 180 | acc|=(v>>1)<<bits;bits+=7 |
| 181 | while bits>=8:out.append(acc&255);acc>>=8;bits-=8 |
| 182 | if bits:out.append(acc) |
| 183 | return bytes(out) |
| 184 |
| 185 | def option(i,codec,pred,parents,data): |
| 186 | ch,pal=palette(R[i]);pcount=len(R[i]['pal']) if ch else 256 |
| 187 | flags=0 |
| 188 | if pal and all(v==((v>>1)*2+(v>>7)) for v in pal):pal=pack7(pal);flags=1 |
| 189 | if codec>=2:pal=b'';ch=0;pcount=0;flags=0 |
| 190 | if codec==1: |
| 191 | ln=sum(len(R[p]['pal']) for p in parents);data=data[:ln]+strip_webp(data[ln:]) |
| 192 | elif codec==2:data=strip_webp(data) |
| 193 | return dict(i=i,codec=codec,pred=pred,parents=parents,data=pal+data,colors=pcount,channels=ch,flags=flags,paletteLength=len(pal),cost=len(pal)+len(data)) |
| 194 |
| 195 | def prepare(): |
| 196 | roots=[];ind=[];edges=[] |
| 197 | for i in range(N): |
| 198 | r=R[i];raw=zlib.compress(r['idx'].tobytes(),9)[2:-4] |
| 199 | root=min([option(i,0,0,(),raw),option(i,1,0,(),W[i][0])],key=lambda x:x['cost']);roots.append(root) |
| 200 | full=[option(i,2,0,(),B[i]['webp']),option(i,3,0,(),r['png'])] |
| 201 | ind.append(min(full+[root],key=lambda x:x['cost'])) |
| 202 | oo=[] |
| 203 | for _,j,mode,zz,lut in D[i][1]:oo.append(option(i,0,mode,(j,),zz[2:-4])) |
| 204 | for _,j,mode,wb,lut in W[i][1]:oo.append(option(i,1,mode,(j,),lut+wb)) |
| 205 | edges.append(sorted(oo,key=lambda x:x['cost'])) |
| 206 | return roots,ind,edges |
| 207 |
| 208 | def select(roots,ind,edges,allow_half=True): |
| 209 | if allow_half: |
| 210 | for i,oo in enumerate(H): |
| 211 | for _,a,b,codec,data in oo: |
| 212 | if codec==0:data=data[2:-4] |
| 213 | edges[i].append(option(i,codec,3,(a,b),data)) |
| 214 | incoming=[[] for _ in range(N)] |
| 215 | for i,oo in enumerate(edges): |
| 216 | for o in oo: |
| 217 | for j in set(o['parents']):incoming[j].append(o) |
| 218 | costs=[o['cost'] for o in ind];choice=ind.copy();opened=set();heap=[] |
| 219 | def gain(j): |
| 220 | if j in opened:return -1e9 |
| 221 | changes={} |
| 222 | for o in incoming[j]: |
| 223 | i=o['i'] |
| 224 | if i in opened or i==j:continue |
| 225 | if all(p==j or p in opened for p in o['parents']):changes[i]=min(changes.get(i,costs[i]),o['cost']) |
| 226 | return sum(costs[i]-c for i,c in changes.items())-(roots[j]['cost']-costs[j]) |
| 227 | for j in range(N):heapq.heappush(heap,(-gain(j),j)) |
| 228 | while heap: |
| 229 | ng,j=heapq.heappop(heap) |
| 230 | if j in opened:continue |
| 231 | g=gain(j) |
| 232 | if heap and g < -heap[0][0]-.01: |
| 233 | heapq.heappush(heap,(-g,j));continue |
| 234 | if g<=0:break |
| 235 | opened.add(j);costs[j]=roots[j]['cost'];choice[j]=roots[j] |
| 236 | for o in incoming[j]: |
| 237 | i=o['i'] |
| 238 | if i not in opened and all(p in opened for p in o['parents']) and o['cost']<costs[i]:costs[i]=o['cost'];choice[i]=o |
| 239 | # Half options become available as soon as one of the two roots is open. |
| 240 | for o in incoming[j]: |
| 241 | for p in o['parents']: |
| 242 | if p not in opened:heapq.heappush(heap,(-gain(p),p)) |
| 243 | # Prune facilities no longer used by anyone. |
| 244 | used={p for o in choice for p in o['parents']} |
| 245 | for j in opened-used:choice[j]=ind[j] |
| 246 | return choice |
| 247 |
| 248 | def pack(choice,path): |
| 249 | hsize=32;esize=20;off=hsize+N*esize;entries=[];payload=[] |
| 250 | for i,o in enumerate(choice): |
| 251 | r=R[i];p=o['parents'];data=o['data'];assert len(data)<65536 |
| 252 | entries.append(struct.pack('<HHIHHHHBBBB',r['id'],r['mask'],off,len(data),p[0] if p else NONE,p[1] if len(p)>1 else NONE,o['colors'],o['codec'],o['pred'],o['channels'],o['flags']));payload.append(data);off+=len(data) |
| 253 | header=struct.pack('<4sHHIIIIII',b'EPK3',1,esize,64,64,N,NE,off,0) |
| 254 | b=header+b''.join(entries)+b''.join(payload);assert len(b)==off;path.write_bytes(b) |
| 255 | return b |
| 256 |
| 257 | def verify(choice): |
| 258 | roots={} |
| 259 | def idx(i): |
| 260 | o=choice[i];data=o['data'];n=o['paletteLength'];data=data[n:];ps=o['parents'];maps=[idx(p) for p in ps] |
| 261 | ls=[choice[p]['colors'] for p in ps];ln=sum(ls) |
| 262 | if o['codec']==0: |
| 263 | raw=zlib.decompress(data,-15);lut=raw[:ln];a=np.frombuffer(raw[ln:],np.uint8).copy().reshape(64,64) |
| 264 | elif o['codec']==1: |
| 265 | lut=data[:ln];a=np.array(Image.open(io.BytesIO(wrap_webp(data[ln:]))).convert('L')) |
| 266 | else:raise ValueError('not indexed') |
| 267 | if ps: |
| 268 | if o['pred']==3: |
| 269 | l=np.frombuffer(lut[:ls[0]],np.uint8)[maps[0]][:,:32];r=np.frombuffer(lut[ls[0]:],np.uint8)[maps[1]][:,32:];p=np.concatenate([l,r],axis=1) |
| 270 | else:p=np.frombuffer(lut,np.uint8)[maps[0]] |
| 271 | a=(a^p) if o['pred']==1 else (a+p).astype(np.uint8) |
| 272 | assert np.array_equal(a,R[i]['idx']),(i,'indices') |
| 273 | return a |
| 274 | for i,o in enumerate(choice): |
| 275 | if o['codec']>=2:a=np.array(Image.open(io.BytesIO(wrap_webp(o['data']) if o['codec']==2 else o['data'])).convert('RGBA')) |
| 276 | else: |
| 277 | ix=idx(i);a=R[i]['pal'][ix] |
| 278 | assert np.array_equal(a,R[i]['rgba']),(i,'rgba') |
| 279 | print('verified all',len(choice),'images and masks exactly',flush=True) |
| 280 |
| 281 |
| 282 | def map_jobs(fn, jobs, workers, label): |
| 283 | start = time.monotonic() |
| 284 | out = [] |
| 285 | # Workers inherit read-only arrays. Explicit fork avoids Python 3.14's |
| 286 | # changed default; this build tool targets Linux/macOS, not Android. |
| 287 | ctx = multiprocessing.get_context('fork') |
| 288 | with ProcessPoolExecutor(max_workers=workers, mp_context=ctx) as pool: |
| 289 | for i, result in enumerate(pool.map(fn, jobs, chunksize=8)): |
| 290 | out.append(result) |
| 291 | if (i + 1) % 500 == 0: |
| 292 | print(f'{label}: {i + 1}; {time.monotonic() - start:.1f}s', flush=True) |
| 293 | return out |
| 294 |
| 295 |