27 lines
1.3 KiB
Python
27 lines
1.3 KiB
Python
"""One persistent KNP GPU detector process. Serialized by server admission lock."""
|
|
from pathlib import Path
|
|
import subprocess,threading,queue,time,atexit
|
|
R=Path.home()/'run/pets-knp';B=Path.home()/'KNP/build/bin'
|
|
class DetectorWorker:
|
|
def __init__(self):self.process=None;self.queue=None;atexit.register(self.close)
|
|
def close(self):
|
|
p=self.process;self.process=None
|
|
if p is not None:
|
|
p.terminate()
|
|
try:p.wait(timeout=3)
|
|
except subprocess.TimeoutExpired:p.kill();p.wait()
|
|
def start(self):
|
|
self.close();self.queue=queue.Queue();p=subprocess.Popen([str(R/'pets_worker'),str(R/'detectors'),str(B/'libknp-altai-cuda-backend.so')],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,bufsize=1);self.process=p;q=self.queue
|
|
def read():
|
|
with (R/'worker.log').open('a') as log:
|
|
for line in p.stdout:
|
|
log.write(line);log.flush()
|
|
if line.startswith('RESULT '):q.put(line.strip()[7:])
|
|
q.put(None)
|
|
threading.Thread(target=read,daemon=True).start()
|
|
def infer(self,image,prefix):
|
|
if self.process is None or self.process.poll() is not None:self.start()
|
|
try:
|
|
self.process.stdin.write(str(image)+' '+str(prefix)+'\n');self.process.stdin.flush();received=self.queue.get(timeout=25)
|
|
if received!=str(prefix):raise RuntimeError('KNP worker stopped or response mismatch')
|
|
except Exception:self.close();raise
|