gliner-node-wrapper
Version:
Node.js wrapper around Python-based GlinER NER library
60 lines (48 loc) • 1.65 kB
JavaScript
const { spawn } = require('child_process');
const path = require('path');
function extractEntities(text, labels, timeoutMs = 30000) {
return new Promise((resolve, reject) => {
if (typeof text !== 'string' || !Array.isArray(labels)) {
return reject(new Error('Invalid input: "text" must be a string and "labels" an array.'));
}
const scriptPath = path.join(__dirname, 'gliner_wrapper.py');
const pythonProcess = spawn('python3', [scriptPath], {
stdio: ['pipe', 'pipe', 'pipe']
});
const payload = JSON.stringify({ text, labels });
let stdout = '';
let stderr = '';
let timer = setTimeout(() => {
pythonProcess.kill('SIGKILL');
reject(new Error('Python script timed out'));
}, timeoutMs);
pythonProcess.stdout.on('data', (data) => {
stdout += data.toString();
});
pythonProcess.stderr.on('data', (data) => {
stderr += data.toString();
});
pythonProcess.on('error', (err) => {
clearTimeout(timer);
reject(err);
});
pythonProcess.on('close', (code) => {
clearTimeout(timer);
if (code !== 0) {
return reject(new Error(stderr || `Python script exited with code ${code}`));
}
try {
const result = JSON.parse(stdout);
if (result.status === 'error') {
return reject(new Error(result.message));
}
resolve(result.entities);
} catch (err) {
reject(new Error('Failed to parse Python output: ' + err.message));
}
});
pythonProcess.stdin.write(payload);
pythonProcess.stdin.end();
});
}
module.exports = { extractEntities };