wihaha commited on
Commit
faf94ce
·
1 Parent(s): 123019b

feat: generate cached score analyses in worker

Browse files
scripts/worldcup/generate-score-analyses.mjs ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import crypto from 'node:crypto';
2
+ import { loadLocalEnv } from '../gaokao/lib/env.mjs';
3
+ import { withDb } from '../gaokao/lib/db.mjs';
4
+
5
+ loadLocalEnv();
6
+
7
+ const modelName = process.env.REASONING_MODEL || 'gemini-3.5-flash';
8
+ const maxMatches = Number(process.env.SCORE_ANALYSIS_MAX_MATCHES || 8);
9
+
10
+ function stableHash(value) {
11
+ return crypto.createHash('sha256').update(JSON.stringify(value)).digest('hex').slice(0, 24);
12
+ }
13
+
14
+ function extractJson(text) {
15
+ const fenced = text.match(/```json\s*([\s\S]*?)```/i);
16
+ const raw = fenced?.[1] || text;
17
+ const start = raw.indexOf('{');
18
+ const end = raw.lastIndexOf('}');
19
+ if (start < 0 || end < start) throw new Error('Gemini response did not include JSON');
20
+ return JSON.parse(raw.slice(start, end + 1));
21
+ }
22
+
23
+ async function ensureTable(pool) {
24
+ await pool.query(`
25
+ create table if not exists worldcup_score_analyses (
26
+ match_id text primary key references worldcup_matches(id),
27
+ status text not null,
28
+ model text,
29
+ predicted_score text,
30
+ score_probabilities jsonb not null default '[]'::jsonb,
31
+ summary_zh text,
32
+ reasoning_md text,
33
+ basis jsonb not null default '{}'::jsonb,
34
+ input_fingerprint text,
35
+ error_message text,
36
+ created_at timestamptz not null default now(),
37
+ updated_at timestamptz not null default now()
38
+ )
39
+ `);
40
+ }
41
+
42
+ async function callGemini(systemPrompt, userPrompt) {
43
+ const apiKey = process.env.VECTORENGINE_GEMINI_KEY || process.env.VECTORENGINE_API_KEY;
44
+ if (!apiKey) throw new Error('VECTORENGINE_GEMINI_KEY is not configured');
45
+
46
+ const apiBase = (process.env.VECTORENGINE_API_BASE || 'https://api.vectorengine.cn/v1').replace(/\/$/, '');
47
+ const response = await fetch(`${apiBase}/chat/completions`, {
48
+ method: 'POST',
49
+ headers: {
50
+ Authorization: `Bearer ${apiKey}`,
51
+ 'Content-Type': 'application/json',
52
+ },
53
+ body: JSON.stringify({
54
+ model: modelName,
55
+ temperature: Number(process.env.SCORE_ANALYSIS_TEMPERATURE || 0.35),
56
+ messages: [
57
+ { role: 'system', content: systemPrompt },
58
+ { role: 'user', content: userPrompt },
59
+ ],
60
+ }),
61
+ signal: AbortSignal.timeout(Number(process.env.SCORE_ANALYSIS_TIMEOUT_MS || 90000)),
62
+ });
63
+
64
+ if (!response.ok) {
65
+ const raw = await response.text().catch(() => '');
66
+ throw new Error(raw || `Gemini request failed: ${response.status}`);
67
+ }
68
+
69
+ const data = await response.json();
70
+ return data?.choices?.[0]?.message?.content || '';
71
+ }
72
+
73
+ async function getEligibleMatches(pool) {
74
+ const result = await pool.query(`
75
+ select
76
+ m.id,
77
+ m.kickoff_utc,
78
+ ht.name_zh as home_name_zh,
79
+ at.name_zh as away_name_zh,
80
+ count(distinct o.id) as odds_count,
81
+ count(distinct w.id) as weather_count
82
+ from worldcup_matches m
83
+ join worldcup_teams ht on ht.id = m.home_team_id
84
+ join worldcup_teams at on at.id = m.away_team_id
85
+ join worldcup_weather_snapshots w on w.match_id = m.id
86
+ join worldcup_market_odds_snapshots o on o.match_id = m.id
87
+ and o.market_key = 'h2h'
88
+ and o.home_odds is not null
89
+ and o.draw_odds is not null
90
+ and o.away_odds is not null
91
+ left join worldcup_score_analyses a on a.match_id = m.id and a.status = 'success'
92
+ where m.status in ('scheduled', 'active')
93
+ and a.match_id is null
94
+ group by m.id, m.kickoff_utc, ht.name_zh, at.name_zh
95
+ order by m.kickoff_utc
96
+ limit $1
97
+ `, [maxMatches]);
98
+ return result.rows;
99
+ }
100
+
101
+ async function getContext(pool, matchId) {
102
+ const matchRes = await pool.query(`
103
+ select
104
+ m.id,
105
+ m.stage,
106
+ m.round,
107
+ m.kickoff_utc,
108
+ m.home_team_id,
109
+ m.away_team_id,
110
+ ht.name_zh as home_name_zh,
111
+ ht.name_en as home_name_en,
112
+ at.name_zh as away_name_zh,
113
+ at.name_en as away_name_en,
114
+ v.name as venue_name,
115
+ v.city as venue_city,
116
+ v.country as venue_country
117
+ from worldcup_matches m
118
+ left join worldcup_teams ht on ht.id = m.home_team_id
119
+ left join worldcup_teams at on at.id = m.away_team_id
120
+ left join worldcup_venues v on v.id = m.venue_id
121
+ where m.id = $1
122
+ `, [matchId]);
123
+
124
+ if (!matchRes.rows[0]) throw new Error(`Match not found: ${matchId}`);
125
+ const match = matchRes.rows[0];
126
+
127
+ const rankingsRes = await pool.query(`
128
+ with ranked as (
129
+ select team_id, ranking_type, rank, rating,
130
+ row_number() over (partition by team_id, ranking_type order by ranking_date desc) rn
131
+ from worldcup_team_rankings
132
+ where team_id in ($1, $2)
133
+ )
134
+ select team_id, ranking_type, rank, rating
135
+ from ranked
136
+ where rn = 1
137
+ `, [match.home_team_id, match.away_team_id]);
138
+
139
+ const formRes = await pool.query(`
140
+ with ranked as (
141
+ select team_id, match_date, opponent_name_raw, competition, result, goals_for, goals_against, opponent_elo,
142
+ row_number() over (partition by team_id order by match_date desc) rn
143
+ from worldcup_team_form
144
+ where team_id in ($1, $2)
145
+ )
146
+ select *
147
+ from ranked
148
+ where rn <= 10
149
+ order by team_id, match_date desc
150
+ `, [match.home_team_id, match.away_team_id]);
151
+
152
+ const weatherRes = await pool.query(`
153
+ select forecast_time, temperature_c, apparent_temperature_c, humidity_pct,
154
+ precipitation_probability_pct, precipitation_mm, wind_speed_kmh, wind_gusts_kmh, weather_code
155
+ from worldcup_weather_snapshots
156
+ where match_id = $1
157
+ order by snapshot_time desc
158
+ limit 1
159
+ `, [matchId]);
160
+
161
+ const oddsRes = await pool.query(`
162
+ with ranked as (
163
+ select bookmaker_key, bookmaker_title, market_key, market_title,
164
+ home_odds, draw_odds, away_odds, last_update,
165
+ row_number() over (
166
+ partition by bookmaker_key, market_key
167
+ order by coalesce(last_update, snapshot_time) desc, snapshot_time desc
168
+ ) rn
169
+ from worldcup_market_odds_snapshots
170
+ where match_id = $1
171
+ and market_key = 'h2h'
172
+ and home_odds is not null
173
+ and draw_odds is not null
174
+ and away_odds is not null
175
+ )
176
+ select *
177
+ from ranked
178
+ where rn = 1
179
+ order by bookmaker_title
180
+ `, [matchId]);
181
+
182
+ return {
183
+ match,
184
+ rankings: rankingsRes.rows,
185
+ recent_form: formRes.rows,
186
+ weather: weatherRes.rows[0] || null,
187
+ odds: oddsRes.rows,
188
+ };
189
+ }
190
+
191
+ async function saveAnalysis(pool, matchId, payload) {
192
+ await pool.query(`
193
+ insert into worldcup_score_analyses (
194
+ match_id, status, model, predicted_score, score_probabilities,
195
+ summary_zh, reasoning_md, basis, input_fingerprint, error_message, updated_at
196
+ ) values ($1,$2,$3,$4,$5::jsonb,$6,$7,$8::jsonb,$9,$10,now())
197
+ on conflict (match_id) do update set
198
+ status = excluded.status,
199
+ model = excluded.model,
200
+ predicted_score = excluded.predicted_score,
201
+ score_probabilities = excluded.score_probabilities,
202
+ summary_zh = excluded.summary_zh,
203
+ reasoning_md = excluded.reasoning_md,
204
+ basis = excluded.basis,
205
+ input_fingerprint = excluded.input_fingerprint,
206
+ error_message = excluded.error_message,
207
+ updated_at = now()
208
+ `, [
209
+ matchId,
210
+ payload.status,
211
+ payload.model || null,
212
+ payload.predicted_score || null,
213
+ JSON.stringify(payload.score_probabilities || []),
214
+ payload.summary_zh || null,
215
+ payload.reasoning_md || null,
216
+ JSON.stringify(payload.basis || {}),
217
+ payload.input_fingerprint || null,
218
+ payload.error_message || null,
219
+ ]);
220
+ }
221
+
222
+ function buildPrompt(context) {
223
+ const systemPrompt = `你是世界杯预测分析师。你必须基于给定的结构化数据,输出比分概率,而不是泛泛聊天。
224
+ 要求:
225
+ - 使用中文。
226
+ - 结合 Elo/FIFA 排名、近 10 场状态、天气、赔率盘口。
227
+ - 不要声称掌握未提供的首发或伤病。
228
+ - 给出 5 个最可能比分及概率,概率总和不必为 100%,但每个概率必须合理。
229
+ - 输出必须是一个 JSON 对象,不要 markdown,不要额外文字。
230
+ JSON schema:
231
+ {
232
+ "predicted_score": "2-1",
233
+ "score_probabilities": [
234
+ {"score": "2-1", "probability": 0.14, "label_zh": "主队小胜"}
235
+ ],
236
+ "summary_zh": "一句话结论",
237
+ "reasoning_md": "Markdown 格式的推理依据,包含:模型基础、盘口信号、天气影响、风险因素",
238
+ "basis": {
239
+ "main_factors": ["Elo优势", "市场赔率", "天气"],
240
+ "data_quality": "complete"
241
+ }
242
+ }`;
243
+
244
+ return {
245
+ systemPrompt,
246
+ userPrompt: JSON.stringify(context, null, 2),
247
+ };
248
+ }
249
+
250
+ async function main() {
251
+ const apiKey = process.env.VECTORENGINE_GEMINI_KEY || process.env.VECTORENGINE_API_KEY;
252
+ if (!apiKey) {
253
+ console.log('[score-analysis] VECTORENGINE_GEMINI_KEY is not configured; skipping score analysis');
254
+ return;
255
+ }
256
+
257
+ await withDb(async (pool) => {
258
+ await ensureTable(pool);
259
+ const matches = await getEligibleMatches(pool);
260
+ console.log(`[score-analysis] eligible=${matches.length} max=${maxMatches}`);
261
+
262
+ let success = 0;
263
+ let failed = 0;
264
+
265
+ for (const match of matches) {
266
+ try {
267
+ const context = await getContext(pool, match.id);
268
+ if (!context.weather || !context.odds.length) {
269
+ console.log(`[score-analysis] skip ${match.id} missing complete weather/odds`);
270
+ continue;
271
+ }
272
+
273
+ const fingerprint = stableHash(context);
274
+ const { systemPrompt, userPrompt } = buildPrompt(context);
275
+ const raw = await callGemini(systemPrompt, userPrompt);
276
+ const parsed = extractJson(raw);
277
+
278
+ await saveAnalysis(pool, match.id, {
279
+ status: 'success',
280
+ model: modelName,
281
+ predicted_score: parsed.predicted_score,
282
+ score_probabilities: parsed.score_probabilities || [],
283
+ summary_zh: parsed.summary_zh || '',
284
+ reasoning_md: parsed.reasoning_md || '',
285
+ basis: parsed.basis || {},
286
+ input_fingerprint: fingerprint,
287
+ });
288
+
289
+ success += 1;
290
+ console.log(`[score-analysis] ${match.id} ${match.home_name_zh} vs ${match.away_name_zh} predicted=${parsed.predicted_score}`);
291
+ } catch (error) {
292
+ failed += 1;
293
+ await saveAnalysis(pool, match.id, {
294
+ status: 'failed',
295
+ model: modelName,
296
+ error_message: error.message || String(error),
297
+ }).catch(() => {});
298
+ console.warn(`[score-analysis] ${match.id} failed: ${error.message || error}`);
299
+ }
300
+ }
301
+
302
+ console.log(`[score-analysis] complete success=${success} failed=${failed}`);
303
+ });
304
+ }
305
+
306
+ await main();
scripts/worldcup/sync-worldcup-data.mjs CHANGED
@@ -752,6 +752,23 @@ async function main() {
752
  console.warn(`[odds] skipped error=${serialized.message}`);
753
  }
754
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
755
  await finishRun(pool, runId, 'success', payload);
756
  });
757
 
 
752
  console.warn(`[odds] skipped error=${serialized.message}`);
753
  }
754
 
755
+ try {
756
+ const scoreResult = await execFileAsync(process.execPath, ['scripts/worldcup/generate-score-analyses.mjs'], {
757
+ cwd: process.cwd(),
758
+ maxBuffer: 1024 * 1024 * 20,
759
+ });
760
+ payload.recordsFetched.score_analysis = null;
761
+ payload.recordsUpserted.score_analysis = { status: 'completed' };
762
+ payload.logText += `\n[score analysis]\n${scoreResult.stdout || ''}`;
763
+ if (scoreResult.stdout) process.stdout.write(scoreResult.stdout);
764
+ if (scoreResult.stderr) process.stderr.write(scoreResult.stderr);
765
+ } catch (error) {
766
+ const serialized = serializeError(error);
767
+ payload.recordsUpserted.score_analysis = { status: 'skipped', error: serialized.message, cause: serialized.cause };
768
+ payload.logText += `\n[score analysis warning]\n${error.stack || serialized.message}`;
769
+ console.warn(`[score-analysis] skipped error=${serialized.message}`);
770
+ }
771
+
772
  await finishRun(pool, runId, 'success', payload);
773
  });
774