"""Read P2 raster pages after cropping/rectifying the 384x224 active picture. For a camera image use --quad xTL,yTL,xTR,yTR,xBR,yBR,xBL,yBL. Coordinates describe the active picture, excluding monitor bezel. CRC failures are erasures. No numerical result is guessed from neighbouring rows or an emulator. """ import argparse, json, sys from pathlib import Path import numpy as np from PIL import Image from readout_font import tile from codec import parse_rows, decode, format_row HEX='0123456789ABCDEF' def raster(ss): assert len(ss)==0x10000 pixels=np.zeros((224,384),dtype=np.uint8) for row in range(28): for col in range(48): at=row*256+col*4;word=int.from_bytes(ss[at:at+4],'big') tile=((word>>16)&255)|((word&1)<<8) for y in range(8): for pair in range(4): off=0x8000+tile*64+1+2*(y*4+pair) if off>=len(ss):continue v=ss[off] pixels[row*8+y,col*8+pair*2]=255 if (v&15)==1 else 0 pixels[row*8+y,col*8+pair*2+1]=255 if (v>>4)==1 else 0 return Image.fromarray(pixels) def templates(): a=[] for ch in HEX: raw=tile(ch);p=np.zeros((8,8),dtype=float) for y in range(8): for x in range(8):p[y,x]=1 if ((raw[y*4+x//2]>>(4*(x%2)))&15)==1 else 0 a.append(p) return np.array(a) TEMPLATES=templates() def rectify(image,quad=None): if quad is None:return image.convert('L').resize((384,224),Image.Resampling.LANCZOS) q=np.array(quad,dtype=float).reshape(4,2) dst=np.array([[0,0],[384,0],[384,224],[0,224]],dtype=float) matrix=[];rhs=[] for (x,y),(u,v) in zip(dst,q): matrix.extend([[x,y,1,0,0,0,-u*x,-u*y],[0,0,0,x,y,1,-v*x,-v*y]]) rhs.extend([u,v]) coeff=np.linalg.solve(np.array(matrix),np.array(rhs)) return image.convert('L').transform((384,224),Image.Transform.PERSPECTIVE,coeff,Image.Resampling.BICUBIC) def ocr(image): a=np.asarray(image.convert('L'),dtype=float)/255 assert a.shape==(224,384) lines=[] for row in range(18): chars=[] for col in range(42): if col in (4,37):chars.append(' ');continue cell=a[(row+5)*8:(row+6)*8,(col+2)*8:(col+3)*8] lo=np.percentile(cell,10);hi=np.percentile(cell,95) if hi-lo<0.15:chars.append('?');continue norm=np.clip((cell-lo)/(hi-lo),0,1) scores=((TEMPLATES-norm)**2).mean(axis=(1,2)) order=np.argsort(scores) # An uncertain glyph erases its row. A checksum never licenses an # exhaustive numerical search through ambiguous replacements. chars.append(HEX[order[0]] if scores[order[0]]<0.22 and scores[order[1]]-scores[order[0]]>0.006 else '?') lines.append(''.join(chars)) return lines def frames(file,step=.5,start=0,end=None): if file.suffix.lower() in ('.png','.jpg','.jpeg','.bmp','.tif','.tiff'): with Image.open(file) as im:yield im.copy() return # PyAV is only required for video; still-image and text recovery work without # it. No subprocess, installation, network access or external FFmpeg needed. try:import av except ImportError as exc:raise RuntimeError('Video decoding requires PyAV (av). Still images require only Pillow/numpy; text recovery uses codec.py and the standard library.') from exc with av.open(str(file)) as movie: stream=movie.streams.video[0];next_time=start rate=float(stream.average_rate or 30) for i,frame in enumerate(movie.decode(stream)): t=float(frame.time) if frame.time is not None else i/rate if end is not None and t>end:break if t+1e-6 0, --start >= 0, and --end >= --start.') quad=[float(x) for x in a.quad.split(',')] if a.quad else None if quad is not None and len(quad)!=8:p.error('--quad requires eight coordinates: TL, TR, BR, BL.') a.out.mkdir(parents=True,exist_ok=False) samples={};rejected=[];all_text=[];files=[];sampled=0;erased=0 for path in a.images: files+=sorted(p for p in path.iterdir() if p.suffix.lower() in ('.png','.jpg','.jpeg','.bmp')) if path.is_dir() else [path] try: for file in files: for frame in frames(file,a.step,a.start,a.end): image=rectify(frame,quad);lines=ocr(image);all_text+=lines;sampled+=1 rows,bad=parse_rows('\n'.join(lines));rejected.extend(bad);erased+=len(lines)-len(rows) for i,d in rows.items(): if i in samples and samples[i]!=d:raise ValueError(f'conflicting CRC-valid row {i:04X} in {file}') samples[i]=d data,report=decode(samples) except (ValueError, RuntimeError, OSError, IndexError) as exc: data=None report=dict(complete=False,error=str(exc),action='Inspect the input and retained OCR/validated rows. Keep each boot separate; resolve conflicts before merging.') report.update(input_files=len(files),sampled_frames=sampled,crc_rejected_rows=len(rejected),erased_rows=erased) (a.out/'ocr.txt').write_text('\n'.join(all_text)+'\n') (a.out/'validated_rows.txt').write_text('\n'.join(format_row(i,d) for i,d in sorted(samples.items()))+'\n') (a.out/'report.json').write_text(json.dumps(report,indent=2)) if data is not None:(a.out/'capture.bin').write_bytes(data) print(json.dumps(report,indent=2)) return 1 if 'error' in report else 0 if data is not None else 2 if __name__=='__main__':sys.exit(main())