SillyTavern/src/endpoints/classify.js

59 lines
1.7 KiB
JavaScript
Raw Normal View History

const express = require('express');
const { jsonParser } = require('../express-common');
2023-09-14 23:12:33 +03:00
const TASK = 'text-classification';
const router = express.Router();
2024-04-23 16:15:54 +03:00
/**
* @type {Map<string, object>} Cache for classification results
*/
const cacheObject = new Map();
2023-09-14 23:12:33 +03:00
router.post('/labels', jsonParser, async (req, res) => {
try {
const module = await import('../transformers.mjs');
const pipe = await module.default.getPipeline(TASK);
const result = Object.keys(pipe.model.config.label2id);
return res.json({ labels: result });
} catch (error) {
console.error(error);
return res.sendStatus(500);
}
});
2023-09-14 23:12:33 +03:00
router.post('/', jsonParser, async (req, res) => {
try {
const { text } = req.body;
2024-04-23 16:15:54 +03:00
/**
* Get classification result for a given text
* @param {string} text Text to classify
* @returns {Promise<object>} Classification result
*/
async function getResult(text) {
2024-04-23 16:15:54 +03:00
if (cacheObject.has(text)) {
return cacheObject.get(text);
} else {
const module = await import('../transformers.mjs');
const pipe = await module.default.getPipeline(TASK);
const result = await pipe(text, { topk: 5 });
result.sort((a, b) => b.score - a.score);
2024-04-23 16:15:54 +03:00
cacheObject.set(text, result);
return result;
}
2023-09-14 23:12:33 +03:00
}
console.log('Classify input:', text);
const result = await getResult(text);
console.log('Classify output:', result);
return res.json({ classification: result });
} catch (error) {
console.error(error);
return res.sendStatus(500);
}
});
module.exports = { router };