"""Persistent isolated CPU layout helper; no Surya dependency in the VLM process.""" import base64,io,json,os,pathlib,select,subprocess,time ROOT=pathlib.Path(__file__).resolve().parent class LayoutClient: def __init__(self):self.process=None;self.log=None def __call__(self,image): if self.process is None: python=pathlib.Path(os.environ.get('BINA_LAYOUT_PYTHON',str(ROOT/'.rizeh-runtime/layout/bin/python'))) if not python.exists():raise RuntimeError('Run python setup_table_runtime.py --with-layout before table-v3 OCR') runtime=ROOT/'.rizeh-runtime';runtime.mkdir(exist_ok=True);self.log=(runtime/'layout-worker.log').open('a') env=os.environ.copy();env.pop('PYTHONPATH',None);env['CUDA_VISIBLE_DEVICES']='' self.process=subprocess.Popen([str(python),'-u',str(ROOT/'rizeh_table/layout_worker.py')],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=self.log,text=True,env=env) stream=io.BytesIO();image.save(stream,format='PNG');self.process.stdin.write(json.dumps(dict(image=base64.b64encode(stream.getvalue()).decode()))+'\n');self.process.stdin.flush();tick=time.monotonic() while not select.select([self.process.stdout],[],[],.5)[0]: if time.monotonic()-tick>300:self.close();raise TimeoutError('Layout worker exceeded 300 seconds') line=self.process.stdout.readline() if not line:raise RuntimeError('Layout worker exited; inspect .rizeh-runtime/layout-worker.log') reply=json.loads(line) if not reply['ok']:raise RuntimeError(reply['error']) return reply['result'] def close(self): if self.process is not None: try:self.process.stdin.close();self.process.wait(timeout=15) except (subprocess.TimeoutExpired,BrokenPipeError): self.process.terminate() try:self.process.wait(timeout=10) except subprocess.TimeoutExpired:self.process.kill();self.process.wait() self.process=None if self.log:self.log.close();self.log=None