144 lines
6.9 KiB
TypeScript
144 lines
6.9 KiB
TypeScript
/**
|
|
* 난이도 계산 (docs/07 난이도 분류): popularity score 0~100 from what we have, then 10 levels by rank share,
|
|
* for the whole catalog ('all') and inside each big genre / decade (docs/12 Q7 기준별 단계).
|
|
* Admin-set levels are never overwritten (Catalog.autoLevel).
|
|
*
|
|
* Score = 40 차트 + 20 노라보세 단계 + 15 노래방 + 15 퀴즈 출현 + 10 가수 히트곡 수.
|
|
* (유튜브 조회수 is not collected: the norabose level — a human-made popularity grade — takes that share.)
|
|
*/
|
|
import type { Database } from 'bun:sqlite';
|
|
import { Catalog, Job } from './catalog';
|
|
|
|
/** Cumulative share (%) that ends each level: 1 = top 3%, 2 = next 5%, … (docs/07 점수 → 10단계). */
|
|
export const LEVEL_CUTS = [3, 8, 18, 30, 45, 60, 72, 84, 95, 100];
|
|
/** A genre or decade needs this many songs to get its own levels. */
|
|
export const MIN_SCOPE_SONGS = 150;
|
|
|
|
export interface SongSignals {
|
|
yearBest: number | null;
|
|
chartYears: number;
|
|
realtimeBest: number | null;
|
|
norabosePeak: number | null;
|
|
noraboseLevel: number | null;
|
|
tjBest: number | null;
|
|
quizSources: string[];
|
|
artistHits: number;
|
|
}
|
|
|
|
const rankScore = (r: number | null, depth: number) => (r === null ? 0 : Math.max(0, 1 - (r - 1) / depth));
|
|
|
|
export function popularity(s: SongSignals): number {
|
|
const chart = Math.max(
|
|
Math.min(1, rankScore(s.yearBest, 100) + 0.08 * Math.max(0, s.chartYears - 1)),
|
|
0.9 * rankScore(s.norabosePeak, 50),
|
|
0.6 * rankScore(s.realtimeBest, 100),
|
|
);
|
|
const prior = s.noraboseLevel === null ? 0 : [1, 0.75, 0.5, 0.25, 0.05][s.noraboseLevel - 1] ?? 0;
|
|
const karaoke = rankScore(s.tjBest, 100);
|
|
const quiz = Math.min(1, (s.quizSources.includes('sta') ? 0.7 : 0) + (s.quizSources.includes('norabose') ? 0.3 : 0) + (s.quizSources.includes('machugi') ? 0.3 : 0));
|
|
const artist = Math.min(1, s.artistHits / 10);
|
|
return Math.round((40 * chart + 20 * prior + 15 * karaoke + 15 * quiz + 10 * artist) * 10) / 10;
|
|
}
|
|
|
|
/** Scores → level per song by rank share. Ties keep the same level. */
|
|
export function levelsByShare(scores: Map<number, number>): Map<number, number> {
|
|
const sorted = [...scores].sort((a, b) => b[1] - a[1] || a[0] - b[0]);
|
|
const out = new Map<number, number>();
|
|
const n = sorted.length;
|
|
let prevScore: number | null = null;
|
|
let prevLevel = 1;
|
|
sorted.forEach(([id, score], i) => {
|
|
const share = ((i + 1) / n) * 100;
|
|
let level = LEVEL_CUTS.findIndex((c) => share <= c) + 1;
|
|
if (prevScore !== null && score === prevScore) level = prevLevel;
|
|
out.set(id, level);
|
|
prevScore = score;
|
|
prevLevel = level;
|
|
});
|
|
return out;
|
|
}
|
|
|
|
export function loadSignals(db: Database): Map<number, SongSignals> {
|
|
const songs = db.query<{ id: number }, []>('SELECT id FROM songs WHERE deleted_at IS NULL').all();
|
|
const map = new Map<number, SongSignals>(songs.map((s) => [s.id, { yearBest: null, chartYears: 0, realtimeBest: null, norabosePeak: null, noraboseLevel: null, tjBest: null, quizSources: [], artistHits: 0 }]));
|
|
for (const r of db
|
|
.query<{ song_id: number; best: number; years: number }, []>("SELECT song_id, MIN(rank) best, COUNT(DISTINCT period) years FROM chart_entries WHERE chart LIKE 'year%' AND source IN ('melon','genie') AND song_id IS NOT NULL GROUP BY song_id")
|
|
.all()) {
|
|
const s = map.get(r.song_id);
|
|
if (s) ((s.yearBest = r.best), (s.chartYears = r.years));
|
|
}
|
|
for (const r of db.query<{ song_id: number; best: number }, []>("SELECT song_id, MIN(rank) best FROM chart_entries WHERE chart = 'realtime' AND song_id IS NOT NULL GROUP BY song_id").all()) {
|
|
const s = map.get(r.song_id);
|
|
if (s) s.realtimeBest = r.best;
|
|
}
|
|
for (const r of db.query<{ song_id: number; best: number }, []>("SELECT song_id, MIN(rank) best FROM chart_entries WHERE source = 'tj' AND song_id IS NOT NULL GROUP BY song_id").all()) {
|
|
const s = map.get(r.song_id);
|
|
if (s) s.tjBest = r.best;
|
|
}
|
|
for (const r of db.query<{ song_id: number; kind: string; value: number }, []>("SELECT song_id, kind, value FROM signals WHERE kind IN ('norabose_peak','norabose_level_mask')").all()) {
|
|
const s = map.get(r.song_id);
|
|
if (!s) continue;
|
|
if (r.kind === 'norabose_peak') s.norabosePeak = r.value;
|
|
else for (let l = 1; l <= 5; l++) if (r.value & (1 << (l - 1))) ((s.noraboseLevel = l), (l = 6));
|
|
}
|
|
for (const r of db.query<{ song_id: number; srcs: string }, []>("SELECT song_id, group_concat(DISTINCT source) srcs FROM song_sources GROUP BY song_id").all()) {
|
|
const s = map.get(r.song_id);
|
|
if (s) s.quizSources = r.srcs.split(',');
|
|
}
|
|
// 가수 인지도: distinct charted songs of the song's main artist
|
|
const hits = new Map(
|
|
db
|
|
.query<{ artist_id: number; n: number }, []>(
|
|
"SELECT sa.artist_id, COUNT(DISTINCT ce.song_id) n FROM chart_entries ce JOIN song_artists sa ON sa.song_id = ce.song_id WHERE ce.chart LIKE 'year%' GROUP BY sa.artist_id",
|
|
)
|
|
.all()
|
|
.map((r) => [r.artist_id, r.n]),
|
|
);
|
|
for (const r of db.query<{ song_id: number; a: number }, []>("SELECT song_id, MIN(artist_id) a FROM song_artists WHERE role = 'main' GROUP BY song_id").all()) {
|
|
const s = map.get(r.song_id);
|
|
if (s) s.artistHits = hits.get(r.a) ?? 0;
|
|
}
|
|
return map;
|
|
}
|
|
|
|
/** Recompute every automatic level. Returns the level distribution of the 'all' scope. */
|
|
export function computeLevels(db: Database): { all: Record<number, number>; scopes: number } {
|
|
const job = new Job(db, 'levels', 0);
|
|
const cat = new Catalog(db);
|
|
const signals = loadSignals(db);
|
|
const scores = new Map<number, number>();
|
|
for (const [id, s] of signals) scores.set(id, popularity(s));
|
|
const scopes = new Map<string, number[]>([['all', [...scores.keys()]]]);
|
|
for (const r of db.query<{ song_id: number; genre_id: string }, []>('SELECT song_id, genre_id FROM song_genres').all()) {
|
|
if (!scores.has(r.song_id)) continue;
|
|
const k = `genre:${r.genre_id}`;
|
|
if (!scopes.has(k)) scopes.set(k, []);
|
|
scopes.get(k)!.push(r.song_id);
|
|
}
|
|
for (const r of db.query<{ id: number; year: number | null }, []>('SELECT id, year FROM songs WHERE deleted_at IS NULL AND year IS NOT NULL').all()) {
|
|
const k = `decade:${Math.floor(r.year! / 10) * 10}`;
|
|
if (!scopes.has(k)) scopes.set(k, []);
|
|
scopes.get(k)!.push(r.id);
|
|
}
|
|
const all: Record<number, number> = {};
|
|
let used = 0;
|
|
db.transaction(() => {
|
|
for (const [id, score] of scores) cat.signal(id, 'popularity', score);
|
|
for (const [scope, ids] of scopes) {
|
|
if (scope !== 'all' && ids.length < MIN_SCOPE_SONGS) {
|
|
db.query("DELETE FROM song_levels WHERE scope = ? AND source = 'auto'").run(scope);
|
|
continue;
|
|
}
|
|
used++;
|
|
const lv = levelsByShare(new Map(ids.map((id) => [id, scores.get(id)!])));
|
|
for (const [id, level] of lv) {
|
|
cat.autoLevel(id, scope, level);
|
|
if (scope === 'all') all[level] = (all[level] ?? 0) + 1;
|
|
}
|
|
}
|
|
})();
|
|
job.log(`levels: ${scores.size} songs, ${used} scopes, all = ${JSON.stringify(all)}`);
|
|
job.finish('done');
|
|
return { all, scopes: used };
|
|
}
|