|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+// 为雅思英语单词批量补充例句(写入 Words.ExampleSentence)
|
|
|
2
|
+// 策略:
|
|
|
3
|
+// 1) 复用:97% 的雅思词在现有词典(BookID=110, 47401词)或其它词书中已有例句,
|
|
|
4
|
+// 直接复用其 ExampleSentence,并按难度筛选为 2简单(A2)+2中等(B1/B2)+1难(C1)。
|
|
|
5
|
+// 2) 生成:仅对完全没例句的少量词,用本机 Ollama(qwen3) 本地生成,不依赖外网。
|
|
|
6
|
+// 输出格式对齐六级:{"word":..,"CEFR_Level":..,"Sentences":[{"Sentence":..,"Translate":..,"Level":..}]}
|
|
|
7
|
+//
|
|
|
8
|
+// 用法:
|
|
|
9
|
+// node generate_examples.js # 复用+本地生成
|
|
|
10
|
+// REUSE_ONLY=1 node generate_examples.js # 只做复用(跳过 Ollama),可先跑这步看覆盖
|
|
|
11
|
+// LIMIT=50 node generate_examples.js # 只处理前 N 个未生成词(验证)
|
|
|
12
|
+// OLLAMA_MODEL=qwen3.8:27b-mlx BATCH=8 node generate_examples.js
|
|
|
13
|
+
|
|
|
14
|
+import { query } from '../../../src/util/db.js';
|
|
|
15
|
+import axios from 'axios';
|
|
|
16
|
+import fs from 'fs';
|
|
|
17
|
+import path from 'path';
|
|
|
18
|
+import { fileURLToPath } from 'url';
|
|
|
19
|
+
|
|
|
20
|
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
|
21
|
+const PROGRESS_FILE = path.join(__dirname, '.ielts_examples_progress.json');
|
|
|
22
|
+
|
|
|
23
|
+const BOOK_IDS = [212, 213, 214, 215, 216, 217];
|
|
|
24
|
+const OLLAMA_URL = process.env.OLLAMA_URL || 'http://localhost:11434/api/generate';
|
|
|
25
|
+const OLLAMA_MODEL = process.env.OLLAMA_MODEL || 'qwen3.8:27b-mlx';
|
|
|
26
|
+const BATCH = Number(process.env.BATCH || 8); // Ollama 每批词数
|
|
|
27
|
+const LIMIT = Number(process.env.LIMIT || 0); // >0 只处理前 N 个
|
|
|
28
|
+const REUSE_ONLY = process.env.REUSE_ONLY === '1';
|
|
|
29
|
+
|
|
|
30
|
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
|
31
|
+
|
|
|
32
|
+// ---------- 难度筛选:2 A2 + 2 B1/B2 + 1 C1,不足则就近补 ----------
|
|
|
33
|
+function pickSentences(sentences) {
|
|
|
34
|
+ const valid = (sentences || []).filter((s) => s && s.Sentence);
|
|
|
35
|
+ const byLevel = {};
|
|
|
36
|
+ for (const s of valid) {
|
|
|
37
|
+ const l = (s.Level || 'B1').toUpperCase();
|
|
|
38
|
+ (byLevel[l] = byLevel[l] || []).push(s);
|
|
|
39
|
+ }
|
|
|
40
|
+ const chosen = [];
|
|
|
41
|
+ const take = (levels, n) => {
|
|
|
42
|
+ for (const lv of levels) {
|
|
|
43
|
+ while (n > 0 && byLevel[lv] && byLevel[lv].length) {
|
|
|
44
|
+ chosen.push(byLevel[lv].shift());
|
|
|
45
|
+ n--;
|
|
|
46
|
+ }
|
|
|
47
|
+ if (n <= 0) break;
|
|
|
48
|
+ }
|
|
|
49
|
+ return n;
|
|
|
50
|
+ };
|
|
|
51
|
+ take(['A2', 'A1'], 2); // 简单
|
|
|
52
|
+ take(['B1', 'B2'], 2); // 中等
|
|
|
53
|
+ take(['C1', 'C2'], 1); // 难
|
|
|
54
|
+ const order = ['A2', 'A1', 'B1', 'B2', 'C1', 'C2'];
|
|
|
55
|
+ const rem = [];
|
|
|
56
|
+ for (const lv of order) if (byLevel[lv]) rem.push(...byLevel[lv]);
|
|
|
57
|
+ while (chosen.length < 5 && rem.length) chosen.push(rem.shift());
|
|
|
58
|
+ return chosen.slice(0, 5).map((s) => ({
|
|
|
59
|
+ Sentence: s.Sentence,
|
|
|
60
|
+ Translate: s.Translate || '',
|
|
|
61
|
+ Level: (s.Level || 'B1').toUpperCase(),
|
|
|
62
|
+ }));
|
|
|
63
|
+}
|
|
|
64
|
+
|
|
|
65
|
+function buildExampleSentence(word, cefr, sentences) {
|
|
|
66
|
+ return JSON.stringify({
|
|
|
67
|
+ word,
|
|
|
68
|
+ CEFR_Level: (cefr || 'B1').toUpperCase(),
|
|
|
69
|
+ Sentences: sentences,
|
|
|
70
|
+ });
|
|
|
71
|
+}
|
|
|
72
|
+
|
|
|
73
|
+// ---------- 复用源:优先 BookID=110 大词典 ----------
|
|
|
74
|
+async function buildSourceMap() {
|
|
|
75
|
+ const rows = await query(
|
|
|
76
|
+ `select Word, ExampleSentence, BookID from kylx365_db.Words where ExampleSentence is not null and ExampleSentence!=''`
|
|
|
77
|
+ );
|
|
|
78
|
+ const map = new Map();
|
|
|
79
|
+ for (const r of rows) {
|
|
|
80
|
+ const key = r.Word.toLowerCase();
|
|
|
81
|
+ const cur = map.get(key);
|
|
|
82
|
+ if (!cur) map.set(key, r);
|
|
|
83
|
+ else if (cur.BookID !== 110 && r.BookID === 110) map.set(key, r); // 大词典优先
|
|
|
84
|
+ }
|
|
|
85
|
+ return map;
|
|
|
86
|
+}
|
|
|
87
|
+
|
|
|
88
|
+function parseSourceExample(raw) {
|
|
|
89
|
+ try {
|
|
|
90
|
+ const o = JSON.parse(raw);
|
|
|
91
|
+ const sents = o.Sentences || o.sentences || [];
|
|
|
92
|
+ if (!sents.length) return null;
|
|
|
93
|
+ return { cefr: o.CEFR_Level || o.cefr, sentences: sents };
|
|
|
94
|
+ } catch {
|
|
|
95
|
+ return null;
|
|
|
96
|
+ }
|
|
|
97
|
+}
|
|
|
98
|
+
|
|
|
99
|
+// ---------- 本地 Ollama 生成 ----------
|
|
|
100
|
+async function callOllama(userPrompt) {
|
|
|
101
|
+ const resp = await axios.post(
|
|
|
102
|
+ OLLAMA_URL,
|
|
|
103
|
+ { model: OLLAMA_MODEL, format: 'json', stream: false, think: false, prompt: userPrompt },
|
|
|
104
|
+ { timeout: 300000 }
|
|
|
105
|
+ );
|
|
|
106
|
+ const data = resp.data || {};
|
|
|
107
|
+ let text = data.response || '';
|
|
|
108
|
+ if (!text && data.thinking) text = data.thinking; // 思考模式兜底
|
|
|
109
|
+ text = (text || '').replace(/^```(?:json)?\s*\n/i, '').replace(/\n```\s*$/i, '');
|
|
|
110
|
+ return text;
|
|
|
111
|
+}
|
|
|
112
|
+
|
|
|
113
|
+function buildGenPrompt(words) {
|
|
|
114
|
+ const lines = words.map((w, i) => `${i + 1}. ${w.Word} | ${w.Translate || ''}`);
|
|
|
115
|
+ return `Generate example sentences for each English word (with Chinese meaning).
|
|
|
116
|
+Per word: exactly 5 sentences — 2 at CEFR A2 (simple), 2 at B1-B2 (medium), 1 at C1 (relatively hard).
|
|
|
117
|
+Each sentence must use the word naturally and correctly per its meaning. Add a concise Chinese translation. Also give the word's approximate CEFR level.
|
|
|
118
|
+Return JSON only: {"items":[{"word":"emperor","cefr":"B1","sentences":[{"sentence":"...","translate":"...","level":"A2"}, ...5]}]}
|
|
|
119
|
+The "word" field must exactly match the input word. Include every input word once.
|
|
|
120
|
+
|
|
|
121
|
+Input words (word | meaning):
|
|
|
122
|
+${lines.join('\n')}`;
|
|
|
123
|
+}
|
|
|
124
|
+
|
|
|
125
|
+function loadProgress() {
|
|
|
126
|
+ try {
|
|
|
127
|
+ return JSON.parse(fs.readFileSync(PROGRESS_FILE, 'utf8'));
|
|
|
128
|
+ } catch {
|
|
|
129
|
+ return { done: [] };
|
|
|
130
|
+ }
|
|
|
131
|
+}
|
|
|
132
|
+function saveProgress(p) {
|
|
|
133
|
+ fs.writeFileSync(PROGRESS_FILE, JSON.stringify(p));
|
|
|
134
|
+}
|
|
|
135
|
+
|
|
|
136
|
+async function main() {
|
|
|
137
|
+ let words = await query(
|
|
|
138
|
+ `select ID, Word, Translate from kylx365_db.Words where BookID in (${BOOK_IDS.join(',')}) and (ExampleSentence is null or ExampleSentence='') order by BookID, ID`
|
|
|
139
|
+ );
|
|
|
140
|
+ if (LIMIT > 0) words = words.slice(0, LIMIT);
|
|
|
141
|
+ console.log(`待处理雅思词行数: ${words.length}`);
|
|
|
142
|
+
|
|
|
143
|
+ const progress = loadProgress();
|
|
|
144
|
+ const doneIds = new Set(progress.done);
|
|
|
145
|
+ words = words.filter((w) => !doneIds.has(w.ID));
|
|
|
146
|
+ console.log(`本次新增处理: ${words.length}(已跳过 ${doneIds.size})`);
|
|
|
147
|
+
|
|
|
148
|
+ const srcMap = await buildSourceMap();
|
|
|
149
|
+ console.log(`复用源词条数: ${srcMap.size}`);
|
|
|
150
|
+
|
|
|
151
|
+ let reuseOk = 0,
|
|
|
152
|
+ genOk = 0,
|
|
|
153
|
+ fail = 0;
|
|
|
154
|
+ const genQueue = [];
|
|
|
155
|
+
|
|
|
156
|
+ // 第一步:尽量复用
|
|
|
157
|
+ for (const w of words) {
|
|
|
158
|
+ const src = srcMap.get(w.Word.toLowerCase());
|
|
|
159
|
+ const parsed = src ? parseSourceExample(src.ExampleSentence) : null;
|
|
|
160
|
+ if (parsed && parsed.sentences.length) {
|
|
|
161
|
+ const picked = pickSentences(parsed.sentences);
|
|
|
162
|
+ if (picked.length >= 1) {
|
|
|
163
|
+ const json = buildExampleSentence(w.Word, parsed.cefr, picked);
|
|
|
164
|
+ await query('update kylx365_db.Words set ExampleSentence=? where ID=?', [json, w.ID]);
|
|
|
165
|
+ reuseOk++;
|
|
|
166
|
+ progress.done.push(w.ID);
|
|
|
167
|
+ continue;
|
|
|
168
|
+ }
|
|
|
169
|
+ }
|
|
|
170
|
+ if (!REUSE_ONLY) genQueue.push(w);
|
|
|
171
|
+ else {
|
|
|
172
|
+ fail++;
|
|
|
173
|
+ console.warn(` ✗ 无复用源: ${w.Word}`);
|
|
|
174
|
+ }
|
|
|
175
|
+ }
|
|
|
176
|
+ saveProgress(progress);
|
|
|
177
|
+ console.log(`复用完成: ${reuseOk},待生成: ${genQueue.length}`);
|
|
|
178
|
+
|
|
|
179
|
+ // 第二步:本地 Ollama 生成剩余
|
|
|
180
|
+ if (genQueue.length) {
|
|
|
181
|
+ const batches = [];
|
|
|
182
|
+ for (let i = 0; i < genQueue.length; i += BATCH) batches.push(genQueue.slice(i, i + BATCH));
|
|
|
183
|
+ console.log(`Ollama 生成批次数: ${batches.length}`);
|
|
|
184
|
+ for (let bi = 0; bi < batches.length; bi++) {
|
|
|
185
|
+ const b = batches[bi];
|
|
|
186
|
+ const label = `gen batch ${bi + 1}/${batches.length} (${b.map((w) => w.Word).join(',')})`;
|
|
|
187
|
+ let ok = false;
|
|
|
188
|
+ for (let attempt = 1; attempt <= 3 && !ok; attempt++) {
|
|
|
189
|
+ try {
|
|
|
190
|
+ const raw = await callOllama(buildGenPrompt(b));
|
|
|
191
|
+ let parsed = JSON.parse(raw);
|
|
|
192
|
+ const items = parsed.items || parsed;
|
|
|
193
|
+ const m = new Map();
|
|
|
194
|
+ for (const it of items) if (it && it.word) m.set(it.word.toLowerCase(), it);
|
|
|
195
|
+ for (const w of b) {
|
|
|
196
|
+ const it = m.get(w.Word.toLowerCase());
|
|
|
197
|
+ if (it && it.sentences && it.sentences.length >= 5) {
|
|
|
198
|
+ const sents = it.sentences.slice(0, 5).map((s) => ({
|
|
|
199
|
+ Sentence: s.sentence,
|
|
|
200
|
+ Translate: s.translate || '',
|
|
|
201
|
+ Level: (s.level || 'B1').toUpperCase(),
|
|
|
202
|
+ }));
|
|
|
203
|
+ const json = buildExampleSentence(w.Word, it.cefr, sents);
|
|
|
204
|
+ await query('update kylx365_db.Words set ExampleSentence=? where ID=?', [json, w.ID]);
|
|
|
205
|
+ progress.done.push(w.ID);
|
|
|
206
|
+ genOk++;
|
|
|
207
|
+ } else {
|
|
|
208
|
+ console.warn(` ✗ 生成缺句: ${w.Word} (got ${(it?.sentences || []).length})`);
|
|
|
209
|
+ }
|
|
|
210
|
+ }
|
|
|
211
|
+ saveProgress(progress);
|
|
|
212
|
+ ok = true;
|
|
|
213
|
+ console.log(`✓ ${label} (genOk=${genOk})`);
|
|
|
214
|
+ } catch (err) {
|
|
|
215
|
+ console.error(`✗ ${label} 尝试${attempt}失败: ${err?.message || err}`);
|
|
|
216
|
+ await sleep(3000 * attempt);
|
|
|
217
|
+ }
|
|
|
218
|
+ }
|
|
|
219
|
+ if (!ok) fail += b.length;
|
|
|
220
|
+ await sleep(500);
|
|
|
221
|
+ }
|
|
|
222
|
+ }
|
|
|
223
|
+
|
|
|
224
|
+ console.log(`\n完成。reuseOk=${reuseOk}, genOk=${genOk}, fail=${fail}, 累计已生成=${progress.done.length}`);
|
|
|
225
|
+}
|
|
|
226
|
+
|
|
|
227
|
+main()
|
|
|
228
|
+ .then(() => process.exit(0))
|
|
|
229
|
+ .catch((e) => {
|
|
|
230
|
+ console.error(e);
|
|
|
231
|
+ process.exit(1);
|
|
|
232
|
+ });
|