Add batch parallelism for LLM classification and refactor API
This commit is contained in:
+42
-28
@@ -1,15 +1,17 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import axios from 'axios';
|
||||
import { useState, useCallback } from "react";
|
||||
import axios from "axios";
|
||||
|
||||
const api = axios.create({
|
||||
baseURL: '/api',
|
||||
baseURL: "/api",
|
||||
timeout: 60000,
|
||||
});
|
||||
|
||||
// Global toast handler
|
||||
let toastHandler = null;
|
||||
export function setToastHandler(handler) { toastHandler = handler; }
|
||||
function toast(message, type = 'success') {
|
||||
export function setToastHandler(handler) {
|
||||
toastHandler = handler;
|
||||
}
|
||||
function toast(message, type = "success") {
|
||||
if (toastHandler) toastHandler(message, type);
|
||||
}
|
||||
|
||||
@@ -22,8 +24,8 @@ export function useApi() {
|
||||
const response = await api[method](url, data, config);
|
||||
return response.data;
|
||||
} catch (err) {
|
||||
const message = err.response?.data?.error || err.message || '请求失败';
|
||||
toast(message, 'error');
|
||||
const message = err.response?.data?.error || err.message || "请求失败";
|
||||
toast(message, "error");
|
||||
throw err;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
@@ -37,19 +39,19 @@ export function useApi() {
|
||||
|
||||
// Upload
|
||||
export async function uploadFile(formData, onProgress) {
|
||||
const res = await api.post('/upload', formData, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
const res = await api.post("/upload", formData, {
|
||||
headers: { "Content-Type": "multipart/form-data" },
|
||||
onUploadProgress: (e) => {
|
||||
if (onProgress && e.total) {
|
||||
onProgress(Math.round((e.loaded / e.total) * 100));
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function getSources() {
|
||||
const res = await api.get('/upload/sources');
|
||||
const res = await api.get("/upload/sources");
|
||||
return res.data;
|
||||
}
|
||||
|
||||
@@ -60,7 +62,7 @@ export async function deleteSource(id) {
|
||||
|
||||
// Transactions
|
||||
export async function getTransactions(params = {}) {
|
||||
const res = await api.get('/transactions', { params });
|
||||
const res = await api.get("/transactions", { params });
|
||||
return res.data;
|
||||
}
|
||||
|
||||
@@ -75,73 +77,85 @@ export async function updateTransaction(id, data) {
|
||||
}
|
||||
|
||||
export async function runReconciliation() {
|
||||
const res = await api.post('/transactions/reconcile');
|
||||
const res = await api.post("/transactions/reconcile");
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function classifyTransactions(ids) {
|
||||
const res = await api.post('/transactions/classify', { ids });
|
||||
const res = await api.post(
|
||||
"/transactions/classify",
|
||||
{ ids },
|
||||
{ timeout: 300000 },
|
||||
);
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function classifyAll() {
|
||||
const res = await api.post('/transactions/classify-all');
|
||||
const res = await api.post("/transactions/classify-all", null, {
|
||||
timeout: 600000,
|
||||
});
|
||||
return res.data;
|
||||
}
|
||||
|
||||
// Stats
|
||||
export async function getOverview(params = {}) {
|
||||
const res = await api.get('/stats/overview', { params });
|
||||
const res = await api.get("/stats/overview", { params });
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function getMonthly(months = 12) {
|
||||
const res = await api.get('/stats/monthly', { params: { months } });
|
||||
const res = await api.get("/stats/monthly", { params: { months } });
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function getDaily(days = 30) {
|
||||
const res = await api.get('/stats/daily', { params: { days } });
|
||||
const res = await api.get("/stats/daily", { params: { days } });
|
||||
return res.data;
|
||||
}
|
||||
|
||||
// Config
|
||||
export async function getConfig() {
|
||||
const res = await api.get('/config');
|
||||
const res = await api.get("/config");
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function updateConfig(data) {
|
||||
const res = await api.put('/config', data);
|
||||
const res = await api.put("/config", data);
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function testLLM() {
|
||||
const res = await api.post('/config/test-llm');
|
||||
const res = await api.post("/config/test-llm");
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function getCategories() {
|
||||
const res = await api.get('/config/categories');
|
||||
const res = await api.get("/config/categories");
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function createCategory(data) { const res = await api.post("/config/categories", data); return res.data; }
|
||||
export async function deleteCategory(id) { const res = await api.delete("/config/categories/" + id); return res.data; }
|
||||
export async function createCategory(data) {
|
||||
const res = await api.post("/config/categories", data);
|
||||
return res.data;
|
||||
}
|
||||
export async function deleteCategory(id) {
|
||||
const res = await api.delete("/config/categories/" + id);
|
||||
return res.data;
|
||||
}
|
||||
export async function updateCategory(id, data) {
|
||||
const res = await api.put(`/config/categories/${id}`, data);
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export function formatAmount(amount) {
|
||||
if (amount === null || amount === undefined) return '--';
|
||||
if (amount === null || amount === undefined) return "--";
|
||||
const n = Number(amount);
|
||||
const prefix = n >= 0 ? '+' : '';
|
||||
const prefix = n >= 0 ? "+" : "";
|
||||
return `${prefix}${n.toFixed(2)}`;
|
||||
}
|
||||
|
||||
export function formatDate(dateStr) {
|
||||
if (!dateStr) return '--';
|
||||
if (!dateStr) return "--";
|
||||
return dateStr.substring(0, 10);
|
||||
}
|
||||
|
||||
@@ -149,5 +163,5 @@ export const SOURCE_TYPE_MAP = {
|
||||
alipay: "支付宝",
|
||||
wechat: "微信支付",
|
||||
bank_debit: "浦发银行",
|
||||
abc: "农业银行"
|
||||
abc: "农业银行",
|
||||
};
|
||||
|
||||
@@ -292,11 +292,28 @@ export default function Transactions() {
|
||||
"classifyTask",
|
||||
JSON.stringify({ total, progress: 0, ts: Date.now() }),
|
||||
);
|
||||
const B = 50;
|
||||
let done = 0;
|
||||
// 分批并行处理(每批30条,最多2批同时进行)
|
||||
const B = 30;
|
||||
const CONCURRENCY = 4;
|
||||
const batches = [];
|
||||
for (let i = 0; i < ids.length; i += B) {
|
||||
await classifyTransactions(ids.slice(i, i + B));
|
||||
done += Math.min(B, ids.length - i);
|
||||
batches.push(ids.slice(i, i + B));
|
||||
}
|
||||
|
||||
let done = 0;
|
||||
let llmCount = 0;
|
||||
let rulesCount = 0;
|
||||
|
||||
for (let i = 0; i < batches.length; i += CONCURRENCY) {
|
||||
const chunk = batches.slice(i, i + CONCURRENCY);
|
||||
const results = await Promise.all(
|
||||
chunk.map((batch) => classifyTransactions(batch)),
|
||||
);
|
||||
for (const r of results) {
|
||||
done += r.classified || 0;
|
||||
if (r.source === "llm") llmCount += r.classified || 0;
|
||||
else rulesCount += r.classified || 0;
|
||||
}
|
||||
const pct = Math.round((done / total) * 100);
|
||||
setClassifyProgress(pct);
|
||||
sessionStorage.setItem(
|
||||
@@ -304,8 +321,13 @@ export default function Transactions() {
|
||||
JSON.stringify({ total, progress: pct, ts: Date.now() }),
|
||||
);
|
||||
}
|
||||
|
||||
sessionStorage.removeItem("classifyTask");
|
||||
showToast("分类完成!共重分类 " + total + " 笔", "success");
|
||||
const detail =
|
||||
llmCount > 0
|
||||
? `(LLM: ${llmCount},规则: ${rulesCount})`
|
||||
: `(规则匹配: ${rulesCount})`;
|
||||
showToast(`分类完成!共处理 ${total} 笔 ${detail}`, "success");
|
||||
loadTransactions();
|
||||
} catch (e) {
|
||||
sessionStorage.removeItem("classifyTask");
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
const express = require('express');
|
||||
const { classifyTransactions } = require('../services/llm');
|
||||
const express = require("express");
|
||||
const { classifyDeals } = require("../services/llm");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// POST /api/classify - 对指定交易进行分类
|
||||
router.post('/', async (req, res) => {
|
||||
router.post("/", async (req, res) => {
|
||||
const { ids } = req.body;
|
||||
|
||||
if (!ids || !Array.isArray(ids) || ids.length === 0) {
|
||||
return res.status(400).json({ error: '请提供交易ID列表' });
|
||||
return res.status(400).json({ error: "请提供交易ID列表" });
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await classifyTransactions(ids);
|
||||
const result = await classifyDeals(ids);
|
||||
res.json({ success: true, ...result });
|
||||
} catch (err) {
|
||||
console.error('[Reco] 分类失败:', err);
|
||||
console.error("[Reco] 分类失败:", err);
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
const express = require("express");
|
||||
const { getDB } = require("../db");
|
||||
const { runAutoReconciliation } = require("../services/matcher");
|
||||
const { classifyDeals } = require("../services/llm");
|
||||
const { classifyDeals, classifyAllDeals } = require("../services/llm");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -135,6 +135,9 @@ router.get("/needs-classify", (req, res) => {
|
||||
`SELECT id FROM deals WHERE category IS NULL OR category NOT IN (${ph})`,
|
||||
)
|
||||
.all(...cats);
|
||||
console.log(
|
||||
`[Reco] GET /transactions/needs-classify — 返回 ${stale.length} 个待分类 deal`,
|
||||
);
|
||||
res.json({ ids: stale.map((r) => r.id), total: stale.length });
|
||||
});
|
||||
|
||||
@@ -205,29 +208,40 @@ router.post("/reconcile", (req, res) => {
|
||||
});
|
||||
});
|
||||
|
||||
// POST /api/transactions/classify-all — 重分类 deals
|
||||
router.post("/classify-all", async (req, res) => {
|
||||
const db = getDB();
|
||||
const cats = db
|
||||
.prepare("SELECT name FROM categories")
|
||||
.all()
|
||||
.map((r) => r.name);
|
||||
if (!cats.length) return res.json({ classified: 0 });
|
||||
const ph = cats.map(() => "?").join(",");
|
||||
const stale = db
|
||||
.prepare(
|
||||
`SELECT id FROM deals WHERE category IS NULL OR category NOT IN (${ph})`,
|
||||
)
|
||||
.all(...cats);
|
||||
if (!stale.length) return res.json({ classified: 0, total: 0 });
|
||||
const ids = stale.map((r) => r.id),
|
||||
B = 50;
|
||||
let n = 0;
|
||||
for (let i = 0; i < ids.length; i += B) {
|
||||
const r = await classifyDeals(ids.slice(i, i + B));
|
||||
n += r.classified;
|
||||
// POST /api/transactions/classify — 对指定 deal 批量分类
|
||||
router.post("/classify", async (req, res) => {
|
||||
const { ids } = req.body;
|
||||
console.log(
|
||||
`[Reco] POST /transactions/classify — 收到 ${ids ? ids.length : 0} 个ID`,
|
||||
);
|
||||
if (!ids || !Array.isArray(ids) || ids.length === 0) {
|
||||
return res.status(400).json({ error: "请提供交易ID列表" });
|
||||
}
|
||||
try {
|
||||
const result = await classifyDeals(ids);
|
||||
console.log(
|
||||
`[Reco] POST /transactions/classify — 完成, classified: ${result.classified}, source: ${result.source}`,
|
||||
);
|
||||
res.json({ success: true, ...result });
|
||||
} catch (err) {
|
||||
console.error("[Reco] 分类失败:", err);
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/transactions/classify-all — AI分类全部(并行)
|
||||
router.post("/classify-all", async (req, res) => {
|
||||
console.log(`[Reco] POST /transactions/classify-all — 开始`);
|
||||
try {
|
||||
const result = await classifyAllDeals();
|
||||
console.log(
|
||||
`[Reco] POST /transactions/classify-all — 完成, classified: ${result.classified}, total: ${result.total}, source: ${result.source}`,
|
||||
);
|
||||
res.json({ success: true, ...result });
|
||||
} catch (err) {
|
||||
console.error("[Reco] 分类全部失败:", err);
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
res.json({ success: true, classified: n, total: ids.length });
|
||||
});
|
||||
|
||||
// GET /api/transactions/stats/summary - 获取汇总统计
|
||||
|
||||
+315
-46
@@ -1,97 +1,366 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const CONFIG_PATH = path.join(__dirname, "..", "..", "data", "llm_config.json");
|
||||
const BATCH_SIZE = 30; // 每批发送给 LLM 的 deal 数量
|
||||
const CONCURRENCY = 5; // 并行调用 LLM 的最大并发数
|
||||
|
||||
const CONFIG_PATH = path.join(__dirname, '..', '..', 'data', 'llm_config.json');
|
||||
let openaiClient = null;
|
||||
|
||||
/* ============================== 配置管理 ============================== */
|
||||
function loadConfig() {
|
||||
try { if (fs.existsSync(CONFIG_PATH)) return JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8')); } catch (e) {}
|
||||
try {
|
||||
if (fs.existsSync(CONFIG_PATH))
|
||||
return JSON.parse(fs.readFileSync(CONFIG_PATH, "utf-8"));
|
||||
} catch (e) {}
|
||||
return {};
|
||||
}
|
||||
function saveConfig(cfg) {
|
||||
const dir = path.dirname(CONFIG_PATH);
|
||||
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2), 'utf-8');
|
||||
fs.writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2), "utf-8");
|
||||
}
|
||||
function resetClient() {
|
||||
openaiClient = null;
|
||||
}
|
||||
function resetClient() { openaiClient = null; }
|
||||
|
||||
function getOpenAIClient() {
|
||||
if (openaiClient) return openaiClient;
|
||||
const cfg = loadConfig();
|
||||
if (!cfg.llm_api_key) return null;
|
||||
const { OpenAI } = require('openai');
|
||||
openaiClient = new OpenAI({ apiKey: cfg.llm_api_key, baseURL: cfg.llm_base_url || 'https://api.openai.com/v1' });
|
||||
openaiClient._model = cfg.llm_model || 'gpt-4o-mini';
|
||||
if (!cfg.llm_api_key) {
|
||||
console.log("[Reco] LLM 未配置 API Key");
|
||||
return null;
|
||||
}
|
||||
const { OpenAI } = require("openai");
|
||||
openaiClient = new OpenAI({
|
||||
apiKey: cfg.llm_api_key,
|
||||
baseURL: cfg.llm_base_url || "https://api.openai.com/v1",
|
||||
});
|
||||
openaiClient._model = cfg.llm_model || "gpt-4o-mini";
|
||||
console.log(
|
||||
`[Reco] LLM 客户端已初始化 — 模型: ${openaiClient._model}, BaseURL: ${cfg.llm_base_url || "默认"}`,
|
||||
);
|
||||
return openaiClient;
|
||||
}
|
||||
|
||||
/* ============================== Prompt 构建 ============================== */
|
||||
function buildPrompt(deals) {
|
||||
const { getDB } = require('../db');
|
||||
const { getDB } = require("../db");
|
||||
const db = getDB();
|
||||
const cats = db.prepare('SELECT id, name, keywords FROM categories').all();
|
||||
const catList = cats.map(c => c.name + '(' + JSON.parse(c.keywords || '[]').join('、') + ')').join('\n');
|
||||
|
||||
const dealList = deals.map((d, i) =>
|
||||
`[${i + 1}] 日期:${d.deal_date} | 金额:${d.amount.toFixed(2)}元 | 对方:${d.counterparty || '未知'} | 描述:${d.description || '无'}`
|
||||
).join('\n');
|
||||
const cats = db.prepare("SELECT id, name, keywords FROM categories").all();
|
||||
const catList = cats
|
||||
.map(
|
||||
(c) => c.name + "(" + JSON.parse(c.keywords || "[]").join("、") + ")",
|
||||
)
|
||||
.join("\n");
|
||||
|
||||
return `你是一个专业的财务分析助手。请对以下交易(Deal)进行分类和描述。\n\n## 可用分类:\n${catList}\n\n## 交易记录:\n${dealList}\n\n## 要求:\n为每笔返回JSON数组,每项含:\n- index: 序号\n- category: 分类名称\n- description: 简洁中文描述(10-30字)\n- confidence: 置信度0-1\n\n仅返回JSON数组。`;
|
||||
let txTotal = 0;
|
||||
const dealList = deals
|
||||
.map((d, i) => {
|
||||
// 获取关联的原始交易记录,提供给 LLM 更丰富的上下文
|
||||
const txs = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT t.description, t.counterparty, t.source_type, t.notes
|
||||
FROM deal_transactions dt
|
||||
JOIN transactions t ON t.id = dt.transaction_id
|
||||
WHERE dt.deal_id = ?
|
||||
`,
|
||||
)
|
||||
.all(d.id);
|
||||
|
||||
let extra = "";
|
||||
if (txs.length > 0) {
|
||||
txTotal += txs.length;
|
||||
const uniq = [];
|
||||
const seen = new Set();
|
||||
for (const tx of txs) {
|
||||
const key = (tx.description || "") + "|" + (tx.counterparty || "");
|
||||
if (!seen.has(key)) {
|
||||
seen.add(key);
|
||||
uniq.push(tx);
|
||||
}
|
||||
}
|
||||
if (uniq.length > 0) {
|
||||
extra =
|
||||
" | 原始明细: " +
|
||||
uniq
|
||||
.map(
|
||||
(t) =>
|
||||
`[${t.source_type || "未知"}] ${t.description || "无描述"}(${t.counterparty || "未知对方"})`,
|
||||
)
|
||||
.join("; ");
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
`[${i + 1}] 日期:${d.deal_date} | 金额:${d.amount.toFixed(2)}元` +
|
||||
` | 对方:${d.counterparty || "未知"} | 描述:${d.description || "无"}${extra}`
|
||||
);
|
||||
})
|
||||
.join("\n");
|
||||
|
||||
console.log(
|
||||
`[Reco] buildPrompt — ${deals.length} 条 deal, 关联 ${txTotal} 条原始交易`,
|
||||
);
|
||||
|
||||
return `你是一个专业的财务分析助手。请对以下交易(Deal)进行分类和描述。
|
||||
|
||||
## 可用分类:
|
||||
${catList}
|
||||
|
||||
## 交易记录:
|
||||
${dealList}
|
||||
|
||||
## 要求:
|
||||
为每笔返回JSON数组,每项含:
|
||||
- index: 序号(整数)
|
||||
- category: 分类名称(必须从可用分类中选择)
|
||||
- description: 简洁中文描述(10-30字)
|
||||
- confidence: 置信度0-1
|
||||
|
||||
仅返回JSON数组,不要任何其他文字。`;
|
||||
}
|
||||
|
||||
/* ============================== JSON 提取 ============================== */
|
||||
function extractJsonArray(text) {
|
||||
if (!text) return null;
|
||||
// 先尝试直接解析
|
||||
try {
|
||||
const r = JSON.parse(text);
|
||||
if (Array.isArray(r)) return r;
|
||||
} catch (e) {}
|
||||
// 找到第一个 [ 和最后一个 ]
|
||||
const start = text.indexOf("[");
|
||||
const end = text.lastIndexOf("]");
|
||||
if (start === -1 || end === -1 || start >= end) return null;
|
||||
try {
|
||||
return JSON.parse(text.substring(start, end + 1));
|
||||
} catch (e) {}
|
||||
return null;
|
||||
}
|
||||
|
||||
/* ============================== 单批 LLM 分类 ============================== */
|
||||
async function classifyDeals(dealIds) {
|
||||
const { getDB } = require('../db');
|
||||
const { getDB } = require("../db");
|
||||
const db = getDB();
|
||||
const ids = Array.isArray(dealIds) ? dealIds : [dealIds];
|
||||
const deals = db.prepare(`SELECT * FROM deals WHERE id IN (${ids.map(() => '?').join(',')})`).all(...ids);
|
||||
if (ids.length === 0) return { classified: 0 };
|
||||
|
||||
console.log(`[Reco] classifyDeals 开始 — 请求 ${ids.length} 个ID`);
|
||||
|
||||
const deals = db
|
||||
.prepare(
|
||||
`SELECT * FROM deals WHERE id IN (${ids.map(() => "?").join(",")})`,
|
||||
)
|
||||
.all(...ids);
|
||||
console.log(`[Reco] classifyDeals — 实际查到 ${deals.length} 条 deal`);
|
||||
if (!deals.length) return { classified: 0 };
|
||||
|
||||
const client = getOpenAIClient();
|
||||
if (client) {
|
||||
console.log(`[Reco] classifyDeals — 使用模型: ${client._model}`);
|
||||
try {
|
||||
const prompt = buildPrompt(deals);
|
||||
console.log(`[Reco] classifyDeals — Prompt 长度: ${prompt.length} 字符`);
|
||||
const t0 = Date.now();
|
||||
const response = await client.chat.completions.create({
|
||||
model: client._model,
|
||||
messages: [
|
||||
{ role: 'system', content: '你是财务分析助手。只返回要求的JSON格式。' },
|
||||
{ role: 'user', content: buildPrompt(deals) }
|
||||
{
|
||||
role: "system",
|
||||
content:
|
||||
"你是财务分析助手。只返回要求的JSON数组,不要任何额外文字。",
|
||||
},
|
||||
{ role: "user", content: prompt },
|
||||
],
|
||||
temperature: 0.3, max_tokens: 2000,
|
||||
temperature: 0.3,
|
||||
max_tokens: 4000,
|
||||
});
|
||||
const json = response.choices[0].message.content.match(/\[[\s\S]*\]/);
|
||||
if (json) {
|
||||
const results = JSON.parse(json[0]);
|
||||
const upd = db.prepare('UPDATE deals SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?');
|
||||
const elapsed = Date.now() - t0;
|
||||
console.log(
|
||||
`[Reco] classifyDeals — LLM 响应耗时: ${elapsed}ms (${(elapsed / 1000).toFixed(1)}s)`,
|
||||
);
|
||||
|
||||
const rawContent = response.choices[0]?.message?.content || "";
|
||||
console.log(
|
||||
`[Reco] classifyDeals — LLM 返回长度: ${rawContent.length} 字符`,
|
||||
);
|
||||
|
||||
const results = extractJsonArray(rawContent);
|
||||
console.log(
|
||||
`[Reco] classifyDeals — 解析出 ${results ? results.length : 0} 条结果`,
|
||||
);
|
||||
|
||||
if (results && results.length > 0) {
|
||||
const upd = db.prepare(
|
||||
"UPDATE deals SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
|
||||
);
|
||||
const t1 = Date.now();
|
||||
db.transaction(() => {
|
||||
for (const item of results) {
|
||||
const d = deals[item.index - 1];
|
||||
if (d) upd.run(item.category, item.description, item.confidence, item.category, d.id);
|
||||
if (d && item.category) {
|
||||
upd.run(
|
||||
item.category,
|
||||
item.description || "",
|
||||
item.confidence || 0.8,
|
||||
item.category,
|
||||
d.id,
|
||||
);
|
||||
}
|
||||
}
|
||||
})();
|
||||
return { classified: results.length, source: 'llm' };
|
||||
console.log(
|
||||
`[Reco] classifyDeals — DB 写入耗时: ${Date.now() - t1}ms, 来源: llm ✅`,
|
||||
);
|
||||
return { classified: results.length, source: "llm" };
|
||||
}
|
||||
} catch (e) { console.error('[Reco] LLM分类失败:', e.message); }
|
||||
console.log(`[Reco] classifyDeals — JSON解析为空,降级到规则匹配 ⚠️`);
|
||||
} catch (e) {
|
||||
console.error(`[Reco] classifyDeals — LLM调用失败:`, e.message);
|
||||
}
|
||||
} else {
|
||||
console.log(`[Reco] classifyDeals — 未配置LLM,使用规则匹配`);
|
||||
}
|
||||
// LLM 不可用或失败 → 降级为规则匹配
|
||||
return classifyDealsByRules(deals);
|
||||
}
|
||||
|
||||
/* ============================== 规则兜底分类 ============================== */
|
||||
function classifyDealsByRules(deals) {
|
||||
const { getDB } = require('../db');
|
||||
console.log(`[Reco] classifyDealsByRules 开始 — ${deals.length} 条 deal`);
|
||||
const { getDB } = require("../db");
|
||||
const db = getDB();
|
||||
const cats = db.prepare('SELECT id, name, keywords FROM categories').all();
|
||||
const upd = db.prepare('UPDATE deals SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?');
|
||||
let n = 0;
|
||||
for (const d of deals) {
|
||||
const text = (d.description + ' ' + d.counterparty).toLowerCase();
|
||||
let best = '其他杂项', score = 0;
|
||||
for (const c of cats) {
|
||||
let s = 0;
|
||||
for (const kw of JSON.parse(c.keywords || '[]')) { if (text.includes(kw.toLowerCase())) s++; }
|
||||
if (s > score) { score = s; best = c.name; }
|
||||
const cats = db.prepare("SELECT id, name, keywords FROM categories").all();
|
||||
console.log(`[Reco] classifyDealsByRules — ${cats.length} 个分类可用`);
|
||||
const upd = db.prepare(
|
||||
"UPDATE deals SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
|
||||
);
|
||||
|
||||
const t0 = Date.now();
|
||||
// 包裹在事务中批量更新
|
||||
db.transaction(() => {
|
||||
for (const d of deals) {
|
||||
const text = (d.description + " " + d.counterparty).toLowerCase();
|
||||
let best = "其他杂项",
|
||||
score = 0;
|
||||
for (const c of cats) {
|
||||
let s = 0;
|
||||
for (const kw of JSON.parse(c.keywords || "[]")) {
|
||||
if (kw && text.includes(kw.toLowerCase())) s++;
|
||||
}
|
||||
if (s > score) {
|
||||
score = s;
|
||||
best = c.name;
|
||||
}
|
||||
}
|
||||
const directionText = parseFloat(d.amount) >= 0 ? "收到" : "向";
|
||||
const actionText = parseFloat(d.amount) >= 0 ? "" : "支付";
|
||||
const desc =
|
||||
directionText +
|
||||
(d.counterparty || "对方") +
|
||||
actionText +
|
||||
Math.abs(d.amount).toFixed(2) +
|
||||
"元";
|
||||
upd.run(best, desc.substring(0, 100), score > 0 ? 0.7 : 0.3, best, d.id);
|
||||
}
|
||||
const desc = (parseFloat(d.amount) >= 0 ? '收到' : '向') + (d.counterparty || '对方') + (parseFloat(d.amount) >= 0 ? '' : '支付') + Math.abs(d.amount).toFixed(2) + '元';
|
||||
upd.run(best, desc.substring(0, 100), score > 0 ? 0.7 : 0.3, best, d.id);
|
||||
n++;
|
||||
}
|
||||
return { classified: n, source: 'rules' };
|
||||
})();
|
||||
console.log(
|
||||
`[Reco] classifyDealsByRules — 完成, 耗时: ${Date.now() - t0}ms, 来源: rules ✅`,
|
||||
);
|
||||
return { classified: deals.length, source: "rules" };
|
||||
}
|
||||
|
||||
module.exports = { classifyDeals, getOpenAIClient, loadConfig, saveConfig, resetClient };
|
||||
/* ============================== AI分类全部(并行) ============================== */
|
||||
async function classifyAllDeals() {
|
||||
const { getDB } = require("../db");
|
||||
const db = getDB();
|
||||
|
||||
console.log(`[Reco] ===== classifyAllDeals 开始 =====`);
|
||||
|
||||
// 1. 取出全部未分类或分类已过时的 deal
|
||||
const cats = db
|
||||
.prepare("SELECT name FROM categories")
|
||||
.all()
|
||||
.map((r) => r.name);
|
||||
console.log(
|
||||
`[Reco] classifyAllDeals — 当前 ${cats.length} 个分类: ${cats.join(", ")}`,
|
||||
);
|
||||
|
||||
if (!cats.length) {
|
||||
console.log(`[Reco] classifyAllDeals — 无分类,退出`);
|
||||
return { classified: 0, total: 0, source: "none" };
|
||||
}
|
||||
|
||||
const ph = cats.map(() => "?").join(",");
|
||||
const stale = db
|
||||
.prepare(
|
||||
`SELECT id FROM deals WHERE category IS NULL OR category NOT IN (${ph})`,
|
||||
)
|
||||
.all(...cats);
|
||||
|
||||
console.log(`[Reco] classifyAllDeals — 待分类 deal: ${stale.length} 条`);
|
||||
|
||||
if (!stale.length) {
|
||||
console.log(`[Reco] classifyAllDeals — 无待分类 deal,退出`);
|
||||
return { classified: 0, total: 0, source: "none" };
|
||||
}
|
||||
|
||||
const ids = stale.map((r) => r.id);
|
||||
|
||||
// 2. 分批
|
||||
const batches = [];
|
||||
for (let i = 0; i < ids.length; i += BATCH_SIZE) {
|
||||
batches.push(ids.slice(i, i + BATCH_SIZE));
|
||||
}
|
||||
console.log(
|
||||
`[Reco] classifyAllDeals — 共 ${batches.length} 批 (每批≤${BATCH_SIZE}条), 最大并发 ${CONCURRENCY}`,
|
||||
);
|
||||
|
||||
// 3. 并行处理(带并发限制)
|
||||
let totalClassified = 0;
|
||||
let source = "rules";
|
||||
const tStart = Date.now();
|
||||
let round = 0;
|
||||
|
||||
for (let i = 0; i < batches.length; i += CONCURRENCY) {
|
||||
round++;
|
||||
const chunk = batches.slice(i, i + CONCURRENCY);
|
||||
const from = i + 1;
|
||||
const to = Math.min(i + CONCURRENCY, batches.length);
|
||||
console.log(
|
||||
`[Reco] classifyAllDeals — 第 ${round} 轮: 并行处理第 ${from}-${to} 批 (共 ${chunk.length} 批)`,
|
||||
);
|
||||
|
||||
const tRound = Date.now();
|
||||
const results = await Promise.all(chunk.map((b) => classifyDeals(b)));
|
||||
const roundElapsed = Date.now() - tRound;
|
||||
|
||||
for (const r of results) {
|
||||
totalClassified += r.classified;
|
||||
if (r.source === "llm") source = "llm";
|
||||
}
|
||||
console.log(
|
||||
`[Reco] classifyAllDeals — 第 ${round} 轮完成, 耗时: ${roundElapsed}ms, 累计: ${totalClassified}/${ids.length}`,
|
||||
);
|
||||
}
|
||||
|
||||
const totalElapsed = Date.now() - tStart;
|
||||
console.log(
|
||||
`[Reco] classifyAllDeals — 全部完成! ${totalClassified}/${ids.length} 条, 来源: ${source}, 总耗时: ${(totalElapsed / 1000).toFixed(1)}s`,
|
||||
);
|
||||
console.log(`[Reco] ===== classifyAllDeals 结束 =====`);
|
||||
|
||||
return { classified: totalClassified, total: ids.length, source };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
classifyDeals,
|
||||
classifyAllDeals,
|
||||
getOpenAIClient,
|
||||
loadConfig,
|
||||
saveConfig,
|
||||
resetClient,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user