"""Port of portable_preview frontend Jy/$y/XE display, using its original assets. Raw wire order reverses columns; palm rows 13/21 interpolate neighboring rows. No recalibration or filtering is applied. Default frontend color range: ADC 0..40. """ from pathlib import Path from functools import lru_cache import json import math import colorsys import cv2 import numpy as np from PIL import Image ASSETS=Path(__file__).resolve().parent/'assets' @lru_cache(None) def particles(side,channels): assert channels in (1125,1132) data=json.loads((ASSETS/f'layout_{side}_20260728.json').read_text()) regions={r['id']:r for r in data['regions']} visible=list(data['visiblePoints']) if channels==1132:visible[49:49]=[True]*7 groups=[('thumb_top',8 if channels==1132 else 7,7),('thumb_bottom',4,7)] for finger in ['little','ring','middle','index']: groups.extend([(finger+'_top',8,7),(finger+'_middle',4,7),(finger+'_bottom',4,7)]) groups.append(('palm',30,20));base=0;result=[] for name,rows,cols in groups: pieces=[('palm_top5',5,0),('palm_main',25,5)] if name=='palm' else [(name,rows,0)] for region_id,count,start in pieces: r=regions[region_id];a=math.radians(r['angle']) cx=r['x']+r['width']/2;cy=r['y']+r['height']/2 for row in range(count): for col in range(cols): absolute_row=row+start;idx=base+absolute_row*cols+col if not visible[idx]:continue x=(col+.5)*r['width']/cols-r['width']/2 y=(row+.5)*r['height']/count-r['height']/2 indices=[base+absolute_row*cols+cols-1-col] if name=='palm' and absolute_row in (13,21): indices=[base+(absolute_row-1)*cols+cols-1-col,base+(absolute_row+1)*cols+cols-1-col] px=cx+math.cos(a)*x-math.sin(a)*y;py=cy+math.sin(a)*x+math.cos(a)*y radius=min(r['width']/cols,r['height']/count)*.38 names={'thumb':'Thumb','little':'Little finger','ring':'Ring finger','middle':'Middle finger','index':'Index finger'} if name=='palm':label='Palm' else: finger,section=name.split('_') label=names[finger]+' ยท '+{'top':'Distal','middle':'Middle','bottom':'Proximal'}[section] result.append(dict(x=px,y=py,r=radius,region=label,row=absolute_row+1,col=col+1, pixel_x=round(px*600),pixel_y=round(py*600), pixel_radius=max(1,round(radius*600)),channels=indices)) base+=rows*cols assert base==channels assert len(result)==(944 if channels==1132 else 937) return result @lru_cache(None) def points(side,channels): return [(p['x'],p['y'],p['r'],p['channels']) for p in particles(side,channels)] @lru_cache(None) def background(side): hand=np.array(Image.open(ASSETS/f'{side}hand.png').convert('RGBA').resize((600,600))).astype(float) alpha=hand[:,:,3:4]/255*.28 return (hand[:,:,:3]*alpha+np.array([0,0,0])*(1-alpha)).astype(np.uint8) def render(side,values,low=0,high=40): canvas=background(side).copy() for x,y,r,indices in points(side,len(values)): value=math.floor(sum(float(values[j]) for j in indices)/len(indices)+.5) fraction=max(0,min(1,(value-low)/max(1,high-low))) color=tuple(round(c*255) for c in colorsys.hls_to_rgb((210-210*fraction)/360,.40+.14*fraction,.85)) if value>0 else (38,55,71) cv2.circle(canvas,(round(x*600),round(y*600)),max(1,round(r*600)),color,-1,cv2.LINE_AA) return canvas class CurrentFrameRenderer: """Same dot colors/geometry, with precomputed mapping and unchanged-image reuse.""" def __init__(self, side, channels): pts = particles(side, channels) self.first = np.array([p['channels'][0] for p in pts]) self.last = np.array([p['channels'][-1] for p in pts]) self.circles = [(p['pixel_x'], p['pixel_y'], p['pixel_radius']) for p in pts] self.background = background(side) self.palette = [(38,55,71)] + [tuple(round(c*255) for c in colorsys.hls_to_rgb( (210-210*(value/40))/360, .40+.14*(value/40), .85)) for value in range(1,41)] self.previous = None self.image = None def render(self, values): values = np.asarray(values, dtype=float) colors = np.clip(np.floor((values[self.first]+values[self.last])*.5+.5),0,40).astype(np.int32) if self.previous is not None and np.array_equal(colors, self.previous): return self.image, False canvas = self.background.copy() for (x,y,radius), value in zip(self.circles, colors): cv2.circle(canvas,(x,y),radius,self.palette[value],-1,cv2.LINE_AA) self.image = canvas self.previous = colors return canvas, True