import { spawn, ChildProcess } from 'child_process'; import readline from 'readline'; export class LayaVisionService { private static instance: LayaVisionService; private process: ChildProcess | null = null; private rl: readline.Interface | null = null; private isReady: boolean = false; private isInitializing: boolean = false; private initError: string | null = null; private threads: number = 1; private pendingRequests: Array<{ resolve: (val: any) => void; reject: (err: any) => void }> = []; private constructor() {} public static getInstance(): LayaVisionService { if (!LayaVisionService.instance) { LayaVisionService.instance = new LayaVisionService(); } return LayaVisionService.instance; } public async initialize(): Promise { if (this.isInitializing || this.isReady) { return; } this.isInitializing = true; this.initError = null; return new Promise((resolve, reject) => { this.threads = Number.parseInt(process.env.LAYA_VISION_THREADS ?? '1', 10); if (isNaN(this.threads) || this.threads < 1) { this.threads = 1; } console.log(`Spawning Laya Vision Python worker with ${this.threads} CPU thread(s)...`); this.process = spawn('python3', ['vision_worker.py'], { stdio: ['pipe', 'pipe', 'pipe'], env: { ...process.env, LAYA_VISION_THREADS: String(this.threads) } }); this.process.stderr?.on('data', (data) => { const msg = data.toString().trim(); console.log(`[LAYA-VISION-PYTHON-STDERR] ${msg}`); }); this.rl = readline.createInterface({ input: this.process.stdout!, terminal: false }); let initResolved = false; this.rl.on('line', (line) => { const trimmed = line.trim(); if (!trimmed) return; if (trimmed === 'READY' && !initResolved) { initResolved = true; this.isReady = true; this.isInitializing = false; console.log('Laya Vision Python worker initialized successfully and reported READY'); resolve(); return; } try { const parsed = JSON.parse(trimmed); const req = this.pendingRequests.shift(); if (req) { if (parsed.error) { req.reject(new Error(parsed.error)); } else { req.resolve(parsed); } } } catch (e) { console.error('Failed to parse Python worker line:', trimmed, e); } }); this.process.on('error', (err) => { console.error('Failed to start Laya Vision Python process:', err); this.isReady = false; this.isInitializing = false; this.initError = err.message; if (!initResolved) { initResolved = true; reject(err); } }); this.process.on('exit', (code, signal) => { console.error(`Laya Vision Python worker exited with code ${code}, signal ${signal}`); this.isReady = false; this.isInitializing = false; this.initError = `Exited with code ${code}`; // Reject all pending requests while (this.pendingRequests.length > 0) { const req = this.pendingRequests.shift(); req?.reject(new Error(`Worker exited with code ${code}`)); } }); }); } public async systemOne( state: Record, questions: Record, imageBuffer?: Buffer ): Promise<{ model: string; answers: Record; inferenceMs: number }> { if (!this.isReady || !this.process || !this.process.stdin) { throw new Error(`Laya Vision model is not ready: ${this.initError || 'Worker not running'}`); } const payload = { state, questions, image_base64: imageBuffer ? imageBuffer.toString('base64') : null }; return new Promise((resolve, reject) => { this.pendingRequests.push({ resolve, reject }); this.process!.stdin!.write(JSON.stringify(payload) + '\n'); }); } public isModelReady(): boolean { return this.isReady; } public isPlaceholder(): boolean { return false; } public getInitError(): string | null { return this.initError; } public getThreads(): number { return this.threads; } public async shutdown(): Promise { if (this.process) { this.process.kill(); this.process = null; this.isReady = false; } } }