diff --git a/apps/server/src/collector/charts.test.ts b/apps/server/src/collector/charts.test.ts new file mode 100644 index 0000000..c37d40c --- /dev/null +++ b/apps/server/src/collector/charts.test.ts @@ -0,0 +1,113 @@ +/** 9단계 수집 확장: chart parsers on saved pages, chart saving, Melon details, heatmap highlights, level calculation. */ +import { describe, expect, test } from 'bun:test'; +import { join } from 'node:path'; +import { openDb } from '../db'; +import { tempDbPath } from '../test-utils'; +import { Catalog } from './catalog'; +import { parseBugs, parseGenie, parseMelon, parseMelonDetail, parseTj, saveChart } from './charts'; +import { collectHeatmaps, parseHeatmap, pickHighlight } from './heatmap'; +import { computeLevels, levelsByShare, LEVEL_CUTS, popularity } from './levels'; + +const fx = (f: string) => Bun.file(join(import.meta.dir, 'fixtures', f)).text(); + +describe('chart parsers (saved pages, 2026-10-18)', () => { + test('멜론 연도별: song id, rank, title, artists with Melon artist ids', async () => { + const rows = parseMelon(await fx('melon-chart.html')); + expect(rows.length).toBe(3); + expect(rows[0]).toEqual({ rank: 1, ref: '711627', title: '죄와벌', artists: [{ ref: '108363', name: 'SG 워너비' }] }); + expect(rows[1]).toMatchObject({ rank: 2, title: '겁쟁이', artists: [{ name: '버즈' }] }); + }); + test('지니 연도별 / 벅스 실시간 / TJ', async () => { + expect(parseGenie(await fx('genie-chart.html'))[0]).toEqual({ rank: 1, ref: '16188070', title: '죄와 벌 (罪와 罰)', artists: [{ name: 'SG워너비' }] }); + expect(parseBugs(await fx('bugs-chart.html'))[0]).toMatchObject({ rank: 1, ref: '6511885', title: 'NEON', artists: [{ name: 'A2O' }] }); + expect(parseTj({ resultData: { items: [{ rank: '1', pro: 86291, indexTitle: 'HAPPY', indexSong: '데이식스' }] } })).toEqual([{ rank: 1, ref: '86291', title: 'HAPPY', artists: [{ name: '데이식스' }] }]); + }); + test('멜론 곡 상세: release date, genre mapping, lyrics with line breaks', async () => { + expect(parseMelonDetail(await fx('melon-song.html'))).toEqual({ releaseDate: '2005-03-03', genres: ['rock'], lyrics: '첫째 줄 가사\n둘째 줄 & 가사\n\n셋째 줄' }); + }); +}); + +describe('saving charts', () => { + test('Melon rows create songs with Melon ids; Genie rows only link existing songs (same song, other spelling)', () => { + const db = openDb(tempDbPath()); + const melon = [ + { rank: 1, ref: '711627', title: '죄와벌', artists: [{ ref: '108363', name: 'SG 워너비' }] }, + { rank: 2, ref: '732512', title: '겁쟁이', artists: [{ ref: '160091', name: '버즈' }] }, + ]; + expect(saveChart(db, { source: 'melon', chart: 'year-kpop', period: '2005', create: 'kpop', year: 2005 }, melon)).toEqual({ created: 2, linked: 2, rows: 2 }); + const s = db.query<{ id: number; melon_id: number; year: number }, []>("SELECT id, melon_id, year FROM songs WHERE title = '죄와벌'").get()!; + expect(s).toMatchObject({ melon_id: 711627, year: 2005 }); + const genie = [ + { rank: 1, ref: '16188070', title: '죄와 벌 (罪와 罰)', artists: [{ name: 'SG워너비' }] }, + { rank: 2, ref: '1', title: '모르는곡', artists: [{ name: '누군가' }] }, + ]; + expect(saveChart(db, { source: 'genie', chart: 'year', period: '2005', year: 2005 }, genie)).toEqual({ created: 0, linked: 1, rows: 2 }); + expect(db.query<{ song_id: number | null }, []>("SELECT song_id FROM chart_entries WHERE source = 'genie' ORDER BY rank").all().map((r) => r.song_id)).toEqual([s.id, null]); + // saving again replaces rows, never duplicates songs + saveChart(db, { source: 'melon', chart: 'year-kpop', period: '2005', create: 'kpop', year: 2005 }, melon); + expect(db.query<{ n: number }, []>('SELECT COUNT(*) n FROM songs').get()!.n).toBe(2); + expect(db.query<{ n: number }, []>('SELECT COUNT(*) n FROM chart_entries').get()!.n).toBe(4); + }); +}); + +describe('heatmap highlight', () => { + test('real page markers → 광 (狂) peak around the chorus, the opening spike is ignored', async () => { + const m = parseHeatmap(await fx('youtube-heatmap.txt')); + expect(m.length).toBe(100); + const sec = pickHighlight(m)!; + expect(sec).toBeGreaterThan(65); + expect(sec).toBeLessThan(80); + }); + test('sets heatmap highlights, never touches an admin one, remembers tries', async () => { + const db = openDb(tempDbPath()); + const c = new Catalog(db); + const ids = ['a', 'b'].map((t) => c.upsert({ title: t, artists: [{ name: 'x' }], source: 't', ref: t })[0]); + db.query("UPDATE songs SET youtube_status = 'matched', youtube_id = 'VO88htcm09E'").run(); + db.query("UPDATE songs SET highlight_sec = 12, highlight_source = 'admin' WHERE id = ?").run(ids[1]!); + const page = await fx('youtube-heatmap.txt'); + const r = await collectHeatmaps(db, { delayMs: 0, fetchPage: async () => page }); + expect(r).toEqual({ set: 1, none: 0, failed: 0 }); + expect(db.query<{ highlight_sec: number; highlight_source: string }, []>('SELECT highlight_sec, highlight_source FROM songs ORDER BY id').all()).toEqual([ + { highlight_sec: pickHighlight(parseHeatmap(page))!, highlight_source: 'heatmap' }, + { highlight_sec: 12, highlight_source: 'admin' }, + ]); + expect((await collectHeatmaps(db, { delayMs: 0, fetchPage: async () => page })).set).toBe(0); + }); +}); + +describe('level calculation (docs/07 난이도 분류)', () => { + const base = { yearBest: null, chartYears: 0, realtimeBest: null, norabosePeak: null, noraboseLevel: null, tjBest: null, quizSources: [] as string[], artistHits: 0 }; + test('a yearly #1 karaoke hit beats a song that only charted low', () => { + const hit = popularity({ ...base, yearBest: 1, chartYears: 2, tjBest: 3, noraboseLevel: 1, quizSources: ['sta', 'norabose'], artistHits: 12 }); + const low = popularity({ ...base, yearBest: 90, noraboseLevel: 4 }); + expect(hit).toBeGreaterThan(90); + expect(low).toBeLessThan(25); + expect(popularity(base)).toBe(0); + }); + test('levels by share: top 3% = 1 … last 5% = 10, equal scores share a level', () => { + const scores = new Map(Array.from({ length: 200 }, (_, i) => [i + 1, 200 - i] as [number, number])); + const lv = levelsByShare(scores); + const count = (l: number) => [...lv.values()].filter((x) => x === l).length; + expect(LEVEL_CUTS.map((_, i) => count(i + 1))).toEqual([6, 10, 20, 24, 30, 30, 24, 24, 22, 10]); + const tied = levelsByShare(new Map([[1, 5], [2, 5], [3, 5], [4, 1]])); + expect(new Set([tied.get(1), tied.get(2), tied.get(3)]).size).toBe(1); + }); + test('computeLevels writes all + big genre scopes, keeps admin levels', () => { + const db = openDb(tempDbPath()); + const c = new Catalog(db); + for (let i = 0; i < 160; i++) { + const [id] = c.upsert({ title: `곡${i}`, artists: [{ name: `가수${i % 40}` }], year: 1995 + (i % 10), genres: ['ballad'], source: 't', ref: String(i) }); + db.query("INSERT INTO chart_entries (source, chart, period, rank, raw_title, raw_artist, song_id, fetched_at) VALUES ('melon', 'year-kpop', '2000', ?, 'x', 'y', ?, 0)").run(i + 1, id!); + } + const first = db.query<{ id: number }, []>("SELECT id FROM songs WHERE title = '곡0'").get()!.id; + db.query("INSERT INTO song_levels (song_id, scope, level, source) VALUES (?, 'all', 9, 'admin')").run(first); + const r = computeLevels(db); + expect(Object.values(r.all).reduce((a, b) => a + b, 0)).toBe(160); + expect(db.query<{ level: number; source: string }, [number]>("SELECT level, source FROM song_levels WHERE song_id = ? AND scope = 'all'").get(first)).toEqual({ level: 9, source: 'admin' }); + // ballad has 160 ≥ 150 songs → own scope; decades have 80 each → none + expect(db.query<{ n: number }, []>("SELECT COUNT(*) n FROM song_levels WHERE scope = 'genre:ballad'").get()!.n).toBe(160); + expect(db.query<{ n: number }, []>("SELECT COUNT(*) n FROM song_levels WHERE scope LIKE 'decade:%'").get()!.n).toBe(0); + const best = db.query<{ level: number }, []>("SELECT l.level FROM song_levels l JOIN songs s ON s.id = l.song_id WHERE s.title = '곡1' AND scope = 'all'").get()!.level; + expect(best).toBe(1); + }); +}); diff --git a/apps/server/src/collector/charts.ts b/apps/server/src/collector/charts.ts new file mode 100644 index 0000000..e77a513 --- /dev/null +++ b/apps/server/src/collector/charts.ts @@ -0,0 +1,324 @@ +/** + * Chart collectors (docs/07 수집 출처, 9단계): 멜론 연도별(가요·팝)/실시간, 지니 연도별, 벅스 실시간, TJ 노래방 연간. + * Raw rows go to chart_entries (re-classifying never re-fetches). Melon charts (song ids) also add new songs; + * the others only attach to songs we already have. 2.5s between requests, a source stops at the first block signal. + */ +import type { Database } from 'bun:sqlite'; +import { songMatchKey } from '@mq/shared'; +import { Catalog, Job, sleep } from './catalog'; + +export const BROWSER_UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0 Safari/537.36'; + +export interface ChartRow { + rank: number; + title: string; + artists: { name: string; ref?: string }[]; + /** Melon song id / Genie song id / Bugs track id / TJ song number. */ + ref: string; +} + +const decode = (s: string) => + s + .replace(/<[^>]+>/g, '') + .replace(/ /g, ' ') + .replace(/&/g, '&') + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/"/g, '"') + .replace(/'|'/g, "'") + .replace(/(\d+);/g, (_, n: string) => String.fromCodePoint(Number(n))) + .replace(/\s+/g, ' ') + .trim(); + +/** 멜론 차트 표 (연도별·실시간 같은 모양). */ +export function parseMelon(html: string): ChartRow[] { + const out: ChartRow[] = []; + for (const block of html.split(/
]*>\s*]*>([\s\S]*?)<\/a>/.exec(block)?.[1];
+ const artist = / [\s\S]*?]*>([\s\S]*?)<\/a>/.exec(block)?.[1];
+ if (!ref || !rank || !title || !artist) continue;
+ out.push({ rank, ref, title: decode(title), artists: [{ name: decode(artist) }] });
+ }
+ return out;
+}
+
+/** TJ 노래방 TOP100 (JSON API). Titles carry extras like `천상연(웹툰 '선녀외전' X 이창섭)`: matching tries the bare title too. */
+export function parseTj(json: unknown): ChartRow[] {
+ const items = ((json as { resultData?: { items?: { rank: string; pro: number; indexTitle: string; indexSong: string }[] } })?.resultData?.items ?? []) as {
+ rank: string;
+ pro: number;
+ indexTitle: string;
+ indexSong: string;
+ }[];
+ return items.map((i) => ({ rank: Number(i.rank), ref: String(i.pro), title: i.indexTitle.trim(), artists: [{ name: i.indexSong.trim() }] }));
+}
+
+export interface ChartSpec {
+ source: 'melon' | 'genie' | 'bugs' | 'tj';
+ chart: string;
+ period: string;
+ /** Adds unknown songs (with this region genre). */
+ create?: 'kpop' | 'pop';
+ year?: number;
+ fetch: () => Promise 0변동없음
+NEON
+ 0변동없음
+머무르
+([\s\S]*?)<\/dl>/.exec(html)?.[1] ?? '';
+ const field = (name: string) => decode(new RegExp(`
/gi, '\n').replace(/\n/g, '\u0000')).replace(/\u0000\s*/g, '\n').trim() : null;
+ return { releaseDate: date ? `${date[1]}-${date[2]}-${date[3]}` : null, genres, lyrics: lyrics || null };
+}
+
+/** Fill release date, genres and lyrics from the Melon song page for songs that have a Melon id and were never filled. */
+export async function fillMelonDetails(db: Database, opts: { limit?: number; delayMs?: number } = {}) {
+ const rows = db
+ .query<{ id: number; melon_id: number; genres_source: string | null }, [number]>(
+ `SELECT s.id, s.melon_id, s.genres_source FROM songs s WHERE s.deleted_at IS NULL AND s.melon_id IS NOT NULL
+ AND NOT EXISTS (SELECT 1 FROM signals g WHERE g.song_id = s.id AND g.kind = 'melon_detail')
+ ORDER BY (s.youtube_status = 'matched') DESC, s.id LIMIT ?`,
+ )
+ .all(opts.limit ?? 500);
+ const job = new Job(db, 'melon-detail', rows.length);
+ const cat = new Catalog(db);
+ const stats = { filled: 0, lyrics: 0, failed: 0 };
+ try {
+ for (const [i, s] of rows.entries()) {
+ try {
+ const d = parseMelonDetail(await get(`https://www.melon.com/song/detail.htm?songId=${s.melon_id}`));
+ db.transaction(() => {
+ if (d.releaseDate) db.query('UPDATE songs SET release_date = ?, year = ? WHERE id = ?').run(d.releaseDate, Number(d.releaseDate.slice(0, 4)), s.id);
+ if (s.genres_source !== 'admin') for (const g of d.genres) db.query("INSERT OR IGNORE INTO song_genres (song_id, genre_id, source) VALUES (?, ?, 'melon')").run(s.id, g);
+ if (d.lyrics && db.query("INSERT OR IGNORE INTO lyrics (song_id, text, source, fetched_at) VALUES (?, ?, 'melon', ?)").run(s.id, d.lyrics, Date.now()).changes) stats.lyrics++;
+ cat.signal(s.id, 'melon_detail', 1);
+ })();
+ stats.filled++;
+ } catch (e) {
+ stats.failed++;
+ if (e instanceof Blocked) {
+ job.log(`melon blocked: ${(e as Error).message}`);
+ break;
+ }
+ job.log(`song ${s.melon_id} failed: ${(e as Error).message}`);
+ }
+ job.progress(i + 1);
+ if ((i + 1) % 50 === 0) job.log(`melon detail ${i + 1}/${rows.length}: lyrics ${stats.lyrics}`);
+ await sleep(opts.delayMs ?? 2500);
+ }
+ job.log(`melon detail done: ${stats.filled} filled, ${stats.lyrics} lyrics, ${stats.failed} failed`);
+ job.finish('done');
+ } catch (e) {
+ job.log(`stopped: ${(e as Error).message}`);
+ job.finish('failed');
+ throw e;
+ }
+ return stats;
+}
diff --git a/apps/server/src/collector/cli.ts b/apps/server/src/collector/cli.ts
index a9dba49..6c7468e 100644
--- a/apps/server/src/collector/cli.ts
+++ b/apps/server/src/collector/cli.ts
@@ -3,6 +3,10 @@
* bun apps/server/src/collector/cli.ts import-norabose [--limit N]
* bun apps/server/src/collector/cli.ts import-sta
* bun apps/server/src/collector/cli.ts match-youtube [--limit N] [--delay ms] [--require-cookie] (default pace: 2s apart; cron caps a day at 3000)
+ * bun apps/server/src/collector/cli.ts charts [--from YYYY] [--to YYYY] [--sources melon-ye,genie-ye,tj-ye,melon-rt,bugs-rt] [--refetch]
+ * bun apps/server/src/collector/cli.ts melon-detail [--limit N]
+ * bun apps/server/src/collector/cli.ts heatmap [--limit N]
+ * bun apps/server/src/collector/cli.ts levels
* bun apps/server/src/collector/cli.ts stats
* In the container: docker exec music_quiz-app-1 bun apps/server/src/collector/cli.ts …
*/
@@ -14,6 +18,9 @@ import { matchYoutube } from './match-youtube';
import { pickSearcher } from './ytmusic';
import { catalogStats } from '../songs/store';
import { currentJob } from './catalog';
+import { collectCharts, fillMelonDetails } from './charts';
+import { collectHeatmaps } from './heatmap';
+import { computeLevels } from './levels';
const [cmd, ...rest] = process.argv.slice(2);
const flag = (name: string) => {
@@ -44,11 +51,25 @@ switch (cmd) {
console.log(await matchYoutube(db, searcher, { limit: flag('limit'), delayMs: flag('delay'), source: searcher.kind }));
break;
}
+ case 'charts': {
+ const i = rest.indexOf('--sources');
+ console.log(await collectCharts(db, { from: flag('from'), to: flag('to'), sources: i >= 0 ? rest[i + 1]!.split(',') : undefined, refetch: rest.includes('--refetch'), delayMs: flag('delay') }));
+ break;
+ }
+ case 'melon-detail':
+ console.log(await fillMelonDetails(db, { limit: flag('limit'), delayMs: flag('delay') }));
+ break;
+ case 'heatmap':
+ console.log(await collectHeatmaps(db, { limit: flag('limit'), delayMs: flag('delay') }));
+ break;
+ case 'levels':
+ console.log(computeLevels(db));
+ break;
case 'stats':
console.log(JSON.stringify(catalogStats(db), null, 1));
break;
default:
- console.log('usage: cli.ts import-norabose|import-sta|match-youtube|stats');
+ console.log('usage: cli.ts import-norabose|import-sta|match-youtube|charts|melon-detail|heatmap|levels|stats');
process.exitCode = 1;
}
db.close();
diff --git a/apps/server/src/collector/control.ts b/apps/server/src/collector/control.ts
index 89e6e0b..471217d 100644
--- a/apps/server/src/collector/control.ts
+++ b/apps/server/src/collector/control.ts
@@ -7,7 +7,13 @@ import { join } from 'node:path';
import type { CollectControl } from '../http/admin-catalog';
import type { LogFn } from '../server';
-export const COLLECT_KINDS: CollectControl['kinds'] = [{ id: 'match-youtube', label: '유튜브 원곡 찾기', limit: true }];
+export const COLLECT_KINDS: CollectControl['kinds'] = [
+ { id: 'match-youtube', label: '유튜브 원곡 찾기', limit: true },
+ { id: 'charts', label: '차트 모으기 (멜론·지니 연도별, TJ 노래방, 멜론·벅스 실시간)' },
+ { id: 'melon-detail', label: '멜론 곡 정보 채우기 (발매일·장르·가사)', limit: true },
+ { id: 'heatmap', label: '하이라이트 찾기 (유튜브 많이 다시 본 구간)', limit: true },
+ { id: 'levels', label: '난이도 다시 계산' },
+];
const CLI = join(import.meta.dir, 'cli.ts');
@@ -48,5 +54,7 @@ export function collectorControl(db: Database, log: LogFn, kinds = COLLECT_KINDS
function defaultArgs(kind: string, limit?: number): string[] {
if (kind === 'match-youtube') return ['match-youtube', '--limit', String(limit ?? 300), '--require-cookie'];
+ if (kind === 'charts') return ['charts'];
+ if (kind === 'levels') return ['levels'];
return [kind, ...(limit ? ['--limit', String(limit)] : [])];
}
diff --git a/apps/server/src/collector/fixtures/bugs-chart.html b/apps/server/src/collector/fixtures/bugs-chart.html
new file mode 100644
index 0000000..3552ba1
--- /dev/null
+++ b/apps/server/src/collector/fixtures/bugs-chart.html
@@ -0,0 +1,168 @@
+
\ No newline at end of file
diff --git a/apps/server/src/collector/fixtures/genie-chart.html b/apps/server/src/collector/fixtures/genie-chart.html
new file mode 100644
index 0000000..b4c0cc3
--- /dev/null
+++ b/apps/server/src/collector/fixtures/genie-chart.html
@@ -0,0 +1,211 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+곡정보
+
+
+
+
+
+
+
+NEON
+
+
+듣기
+
+
+재생목록에 추가
+
+
+내 앨범에 담기
+
+
+flac 다운로드
+
+
+영상 재생
+
+
+기타 기능
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+곡정보
+
+
+
+
+
+
+
+꿈꾸던 어른이 되었나요?
+
+
+듣기
+
+
+재생목록에 추가
+
+
+내 앨범에 담기
+
+
+flac 다운로드
+
+
+영상 재생 불가
+
+
+기타 기능
+
+
\ No newline at end of file
diff --git a/apps/server/src/collector/fixtures/melon-chart.html b/apps/server/src/collector/fixtures/melon-chart.html
new file mode 100644
index 0000000..54ff42a
--- /dev/null
+++ b/apps/server/src/collector/fixtures/melon-chart.html
@@ -0,0 +1,163 @@
+
+
+
+
+ 1
+
+
+
+ 곡 제목 정보 페이지
+
+
+
+
+ TITLE
+
+
+
+
+
+
+ 죄와 벌 (罪와 罰)
+
+ SG워너비
+ |
+ 2집 살다가
+
+
+
+ 듣기
+ 재생목록에 추가
+
+
+
+
+
+
+ 다운로드
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 2
+
+
+
+ 곡 제목 정보 페이지
+
+
+
+
+ TITLE
+
+
+
+
+
+
+ 겁쟁이
+
+ 버즈 (Buzz)
+ |
+ Buzz Effect
+
+
+
+ 듣기
+ 재생목록에 추가
+
+
+
+
+
+
+ 다운로드
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 3
+
+
+
+ 곡 제목 정보 페이지
+
+
+
+
+ TITLE
+
+
+
+
+
+
+ 사랑했나봐
+
+ 윤도현
+ |
+ Difference
+
+
+
+ 듣기
+ 재생목록에 추가
+
+
+
+
+
+
+ 다운로드
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/apps/server/src/collector/fixtures/melon-song.html b/apps/server/src/collector/fixtures/melon-song.html
new file mode 100644
index 0000000..a52934d
--- /dev/null
+++ b/apps/server/src/collector/fixtures/melon-song.html
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
둘째 줄 & 가사
셋째 줄수집