From 46240ac699cfabb96a95a28870a1e6c1657476c5 Mon Sep 17 00:00:00 2001 From: EJClaw Date: Sun, 18 Oct 2026 22:34:08 +0900 Subject: [PATCH] =?UTF-8?q?9=EB=8B=A8=EA=B3=84=20=EC=88=98=EC=A7=91=20?= =?UTF-8?q?=ED=99=95=EC=9E=A5:=20=EB=A9=9C=EB=A1=A0=20=EC=97=B0=EB=8F=84?= =?UTF-8?q?=EB=B3=84=C2=B7=EC=8B=A4=EC=8B=9C=EA=B0=84,=20=EC=A7=80?= =?UTF-8?q?=EB=8B=88=20=EC=97=B0=EB=8F=84=EB=B3=84,=20=EB=B2=85=EC=8A=A4?= =?UTF-8?q?=20=EC=8B=A4=EC=8B=9C=EA=B0=84,=20TJ=20=EB=85=B8=EB=9E=98?= =?UTF-8?q?=EB=B0=A9=20=EC=97=B0=EA=B0=84=20=EC=B0=A8=ED=8A=B8(chart=5Fent?= =?UTF-8?q?ries)=20+=20=EB=A9=9C=EB=A1=A0=20=EA=B3=A1=20=EC=A0=95=EB=B3=B4?= =?UTF-8?q?(=EB=B0=9C=EB=A7=A4=EC=9D=BC=C2=B7=EC=9E=A5=EB=A5=B4=C2=B7?= =?UTF-8?q?=EA=B0=80=EC=82=AC)=20+=20=EC=9C=A0=ED=8A=9C=EB=B8=8C=20?= =?UTF-8?q?=EB=A7=8E=EC=9D=B4=20=EB=8B=A4=EC=8B=9C=20=EB=B3=B8=20=EA=B5=AC?= =?UTF-8?q?=EA=B0=84=20=ED=95=98=EC=9D=B4=EB=9D=BC=EC=9D=B4=ED=8A=B8=20+?= =?UTF-8?q?=20=EC=9D=B8=EA=B8=B0=EB=8F=84=20=EC=A0=90=EC=88=98=EB=A1=9C=20?= =?UTF-8?q?=EB=82=9C=EC=9D=B4=EB=8F=84=2010=EB=8B=A8=EA=B3=84(=EC=A0=84?= =?UTF-8?q?=EC=B2=B4=C2=B7=ED=81=B0=20=EC=9E=A5=EB=A5=B4=C2=B7=EC=97=B0?= =?UTF-8?q?=EB=8C=80=EB=B3=84),=20=EA=B4=80=EB=A6=AC=EC=9E=90=20=EC=88=98?= =?UTF-8?q?=EC=A7=91=20=ED=99=94=EB=A9=B4=EC=97=90=EC=84=9C=20=EC=8B=A4?= =?UTF-8?q?=ED=96=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/server/src/collector/charts.test.ts | 113 ++++++ apps/server/src/collector/charts.ts | 324 ++++++++++++++++++ apps/server/src/collector/cli.ts | 23 +- apps/server/src/collector/control.ts | 10 +- .../src/collector/fixtures/bugs-chart.html | 168 +++++++++ .../src/collector/fixtures/genie-chart.html | 211 ++++++++++++ .../src/collector/fixtures/melon-chart.html | 163 +++++++++ .../src/collector/fixtures/melon-song.html | 13 + .../collector/fixtures/youtube-heatmap.txt | 1 + apps/server/src/collector/heatmap.ts | 94 +++++ apps/server/src/collector/levels.ts | 143 ++++++++ apps/server/src/db/migrations/006_charts.sql | 15 + apps/web/src/pages/admin/AdminMore.tsx | 2 +- 13 files changed, 1277 insertions(+), 3 deletions(-) create mode 100644 apps/server/src/collector/charts.test.ts create mode 100644 apps/server/src/collector/charts.ts create mode 100644 apps/server/src/collector/fixtures/bugs-chart.html create mode 100644 apps/server/src/collector/fixtures/genie-chart.html create mode 100644 apps/server/src/collector/fixtures/melon-chart.html create mode 100644 apps/server/src/collector/fixtures/melon-song.html create mode 100644 apps/server/src/collector/fixtures/youtube-heatmap.txt create mode 100644 apps/server/src/collector/heatmap.ts create mode 100644 apps/server/src/collector/levels.ts create mode 100644 apps/server/src/db/migrations/006_charts.sql 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*(\d+)/.exec(block)?.[1]); + const title = /class="ellipsis rank01">[\s\S]*?]*>([\s\S]*?)<\/a>/.exec(block)?.[1]; + const artistPart = /class="ellipsis rank02">([\s\S]*?)]*>([\s\S]*?)<\/a>/g)].map((m) => ({ ref: m[1]!, name: decode(m[2]!) })); + if (!ref || !rank || !title || !artists.length) continue; + out.push({ rank, ref, title: decode(title), artists }); + } + return out; +} + +/** 지니 차트 표. */ +export function parseGenie(html: string): ChartRow[] { + const out: ChartRow[] = []; + for (const block of html.split(/\s*(\d+)/.exec(block)?.[1]); + const title = /class="title ellipsis"[^>]*>([\s\S]*?)<\/a>/.exec(block)?.[1]; + const artist = /class="artist ellipsis"[^>]*>([\s\S]*?)<\/a>/.exec(block)?.[1]; + if (!ref || !rank || !title || !artist) continue; + out.push({ rank, ref, title: decode(title.replace(/[\s\S]*?<\/span>/g, '')), artists: decode(artist).split(/\s*,\s*|\s*&\s*/).map((name) => ({ name })) }); + } + return out; +} + +/** 벅스 차트 표. */ +export function parseBugs(html: string): ChartRow[] { + const out: ChartRow[] = []; + for (const block of html.split(/]*rowType="track"/).slice(0)) { + const ref = /trackId="(\d+)"/.exec(block)?.[1] ?? /name="_isStream" value="(\d+)"/.exec(block)?.[1]; + const rank = Number(/
\s*(\d+)<\/strong>/.exec(block)?.[1]); + const title = /

]*>\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; +} + +export class Blocked extends Error {} + +async function get(url: string, init: RequestInit = {}): Promise { + const res = await fetch(url, { ...init, headers: { 'user-agent': BROWSER_UA, 'accept-language': 'ko-KR,ko;q=0.9', ...(init.headers ?? {}) }, signal: AbortSignal.timeout(20_000) }); + if (res.status === 429 || res.status === 403) throw new Blocked(`${url} → ${res.status}`); + if (!res.ok) throw new Error(`${url} → ${res.status}`); + const text = await res.text(); + if (/captcha|비정상적인 접근|자동입력 방지/i.test(text.slice(0, 20000)) && text.length < 30000) throw new Blocked(`${url} → bot check`); + return text; +} + +export function chartSpecs(opts: { from?: number; to?: number; sources?: string[] } = {}): ChartSpec[] { + const last = new Date().getFullYear() - 1; + const from = opts.from ?? 1984; + const to = Math.min(opts.to ?? last, last); + const want = (s: string) => !opts.sources?.length || opts.sources.includes(s); + const out: ChartSpec[] = []; + for (let y = from; y <= to; y++) { + for (const g of ['KPOP', 'POP'] as const) + if (want('melon-ye')) + out.push({ + source: 'melon', + chart: `year-${g.toLowerCase()}`, + period: String(y), + create: g === 'KPOP' ? 'kpop' : 'pop', + year: y, + fetch: async () => parseMelon(await get(`https://www.melon.com/chart/age/list.htm?idx=1&chartType=YE&chartGenre=${g}&chartDate=${y}&moved=Y`)), + }); + if (want('genie-ye') && y >= 1990) + out.push({ + source: 'genie', + chart: 'year', + period: String(y), + year: y, + fetch: async () => [ + ...parseGenie(await get(`https://www.genie.co.kr/chart/musicHistory?year=${y}&category=0&pg=1`)), + ...(await sleep(2500).then(async () => parseGenie(await get(`https://www.genie.co.kr/chart/musicHistory?year=${y}&category=0&pg=2`)))), + ], + }); + if (want('tj-ye') && y >= 2008) + out.push({ + source: 'tj', + chart: 'year', + period: String(y), + year: y, + fetch: async () => + parseTj( + JSON.parse( + await get('https://www.tjmedia.com/legacy/api/topAndHot100', { + method: 'POST', + headers: { 'content-type': 'application/x-www-form-urlencoded' }, + body: `chartType=TOP&searchStartDate=${y}-01-01&searchEndDate=${y}-12-31&strType=1`, + }), + ), + ), + }); + } + const today = new Date().toISOString().slice(0, 10); + if (want('melon-rt')) out.push({ source: 'melon', chart: 'realtime', period: today, create: 'kpop', fetch: async () => parseMelon(await get('https://www.melon.com/chart/index.htm')) }); + if (want('bugs-rt')) out.push({ source: 'bugs', chart: 'realtime', period: today, fetch: async () => parseBugs(await get('https://music.bugs.co.kr/chart')) }); + return out; +} + +/** Bare title for matching: `천상연(웹툰 '선녀외전' X 이창섭(LEE CHANGSUB))` → `천상연`. */ +const bareTitle = (t: string) => t.replace(/\s*[([(][\s\S]*$/, '').trim() || t; + +export function findSong(db: Database, source: ChartSpec['source'], row: ChartRow): number | null { + if (source === 'melon') { + const r = db.query<{ id: number }, [number]>('SELECT id FROM songs WHERE melon_id = ? AND deleted_at IS NULL').get(Number(row.ref)); + if (r) return r.id; + } + const artist = row.artists.map((a) => a.name).join(', '); + for (const t of [row.title, bareTitle(row.title)]) { + const r = db.query<{ id: number }, [string]>('SELECT id FROM songs WHERE match_key = ? AND deleted_at IS NULL ORDER BY id LIMIT 1').get(songMatchKey(t, artist)); + if (r) return r.id; + } + return null; +} + +/** Store one chart: entries + song links (+ new songs for Melon/Genie yearly). */ +export function saveChart(db: Database, spec: Pick, rows: ChartRow[], now = Date.now()) { + const cat = new Catalog(db); + let created = 0; + let linked = 0; + db.transaction(() => { + for (const row of rows) { + let songId = findSong(db, spec.source, row); + if (!songId && spec.create) { + const [id, isNew] = cat.upsert({ + melonId: spec.source === 'melon' ? Number(row.ref) : null, + title: row.title, + artists: row.artists.map((a) => ({ name: a.name, melonArtistId: spec.source === 'melon' && a.ref ? Number(a.ref) : null })), + genres: [spec.create], + source: `${spec.source}-chart`, + ref: `${spec.chart}:${spec.period}:${row.rank}`, + }); + songId = id; + if (isNew) created++; + } + if (songId) { + linked++; + db.query('INSERT OR IGNORE INTO song_sources (song_id, source, ref) VALUES (?, ?, ?)').run(songId, `${spec.source}-chart`, `${spec.chart}:${spec.period}`); + // Year: when nothing better is known, the first yearly chart it was on (docs/07 연도). + if (spec.year) db.query('UPDATE songs SET year = ? WHERE id = ? AND year IS NULL').run(spec.year, songId); + } + db.query( + `INSERT INTO chart_entries (source, chart, period, rank, raw_title, raw_artist, raw_ref, song_id, fetched_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(source, chart, period, rank) DO UPDATE SET raw_title = excluded.raw_title, raw_artist = excluded.raw_artist, raw_ref = excluded.raw_ref, + song_id = COALESCE(excluded.song_id, chart_entries.song_id), fetched_at = excluded.fetched_at`, + ).run(spec.source, spec.chart, spec.period, row.rank, row.title, row.artists.map((a) => a.name).join(', '), row.ref, songId, now); + } + })(); + return { created, linked, rows: rows.length }; +} + +/** Run the chart collectors. Already fetched yearly charts are skipped (realtime ones refresh daily). */ +export async function collectCharts(db: Database, opts: { from?: number; to?: number; sources?: string[]; delayMs?: number; refetch?: boolean } = {}) { + const specs = chartSpecs(opts).filter( + (s) => opts.refetch || s.chart === 'realtime' || !db.query('SELECT 1 FROM chart_entries WHERE source = ? AND chart = ? AND period = ? LIMIT 1').get(s.source, s.chart, s.period), + ); + const job = new Job(db, 'charts', specs.length); + const blocked = new Set(); + const total = { charts: 0, created: 0, linked: 0, rows: 0 }; + try { + for (const [i, s] of specs.entries()) { + if (blocked.has(s.source)) continue; + try { + const rows = await s.fetch(); + const r = saveChart(db, s, rows); + total.charts++; + total.created += r.created; + total.linked += r.linked; + total.rows += r.rows; + if (!rows.length) job.log(`${s.source} ${s.chart} ${s.period}: empty (page changed?)`); + } catch (e) { + if (e instanceof Blocked) { + blocked.add(s.source); + job.log(`${s.source} blocked, skipping the rest of it: ${(e as Error).message}`); + } else job.log(`${s.source} ${s.chart} ${s.period} failed: ${(e as Error).message}`); + } + job.progress(i + 1); + if ((i + 1) % 10 === 0) job.log(`charts ${i + 1}/${specs.length}: new songs ${total.created}, linked ${total.linked}`); + await sleep(opts.delayMs ?? 2500); + } + job.log(`charts done: ${total.charts} charts, ${total.rows} rows, new songs ${total.created}, linked ${total.linked}${blocked.size ? `, blocked: ${[...blocked].join(',')}` : ''}`); + job.finish('done'); + } catch (e) { + job.log(`stopped: ${(e as Error).message}`); + job.finish('failed'); + throw e; + } + return total; +} + +// ------------------------------------------------------------------ 멜론 곡 상세 (발매일·장르·가사) +const MELON_GENRES: [RegExp, string][] = [ + [/발라드/, 'ballad'], + [/댄스/, 'dance'], + [/랩|힙합/, 'hiphop'], + [/R&B|소울/i, 'rnb'], + [/록|메탈/, 'rock'], + [/인디/, 'indie'], + [/포크|블루스/, 'folk'], + [/일렉트로/, 'electronic'], + [/성인가요|트로트/, 'trot'], + [/재즈/, 'jazz'], + [/클래식|뉴에이지/, 'classical'], + [/OST|드라마|영화|뮤지컬/, 'ost'], + [/애니메이션|게임|웹툰/, 'anime'], + [/동요|키즈/, 'kids'], + [/J-POP/i, 'jpop'], +]; + +export function parseMelonDetail(html: string): { releaseDate: string | null; genres: string[]; lyrics: string | null } { + const dl = /

([\s\S]*?)<\/dl>/.exec(html)?.[1] ?? ''; + const field = (name: string) => decode(new RegExp(`
${name}
\\s*
([\\s\\S]*?)
`).exec(dl)?.[1] ?? ''); + const date = /^(\d{4})\.(\d{2})\.(\d{2})$/.exec(field('발매일')); + const genreText = field('장르'); + const genres = MELON_GENRES.filter(([re]) => re.test(genreText)).map(([, g]) => g); + const lyr = /id="d_video_summary"[^>]*>([\s\S]*?)<\/div>/.exec(html)?.[1]; + const lyrics = lyr ? decode(lyr.replace(//g, '').replace(//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 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+1 +

0변동없음

+
+
+ + +NEON 대표이미지 + + +곡정보 + +

+NEON +

+
+

+ +A2O + + +A2O +

+
+NEON + +듣기 + +재생목록에 추가 + +내 앨범에 담기 + +flac 다운로드 + +영상 재생 + +기타 기능 +
+
+2 +

0변동없음

+
+
+ + +꿈꾸던 어른이 되었나요? 대표이미지 + + +곡정보 + +

+꿈꾸던 어른이 되었나요? +

+
+

+머무르 +

+
+꿈꾸던 어른이 되었나요? + +듣기 + +재생목록에 추가 + +내 앨범에 담기 + +flac 다운로드 + +영상 재생 불가 + +기타 기능 +
\ 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 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
1 + + 2집 살다가 + + + + TITLE + + + + + + + 죄와 벌 (罪와 罰) + + SG워너비 + | + 2집 살다가 + 듣기재생목록에 추가다운로드 +
+ + + 뮤직비디오 보기 + + + +
+
+
+ + +
+
2 + + Buzz Effect + + + + TITLE + + + + + + + 겁쟁이 + + 버즈 (Buzz) + | + Buzz Effect + 듣기재생목록에 추가다운로드 +
+ + + 뮤직비디오 보기 + + + +
+
+
+ + +
+
3 + + Difference + + + + TITLE + + + + + + + 사랑했나봐 + + 윤도현 + | + Difference + 듣기재생목록에 추가다운로드 +
+ + + 뮤직비디오 보기 + + + +
+
+
+ + +
+
\ 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 +
+ + + 죄와벌 상세정보 페이지 이동 +
+
+ + + + + + + 죄와벌 +

+ +
+
+ +
+ +
+ +
+ +
+ 2 +
+ + + 겁쟁이 상세정보 페이지 이동 +
+
+ + + + + + + 겁쟁이 +

+
+ + + | + +
+
+
+ +
+ +
+ +
+ +
+ 3 +
+ + + 사랑했나봐 상세정보 페이지 이동 +
+
+ + + + + + + 사랑했나봐 +

+
+ + + | + +
+
+
+ +
+ +
+ +
\ 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 @@ +
+
앨범
+
Buzz Effect
+
발매일
+
2005.03.03
+
장르
+
록/메탈
+ +
FLAC
+
Flac 16bit
+ +
+
첫째 줄 가사
둘째 줄 & 가사

셋째 줄
\ No newline at end of file diff --git a/apps/server/src/collector/fixtures/youtube-heatmap.txt b/apps/server/src/collector/fixtures/youtube-heatmap.txt new file mode 100644 index 0000000..2aca1a9 --- /dev/null +++ b/apps/server/src/collector/fixtures/youtube-heatmap.txt @@ -0,0 +1 @@ +,{"entityKey":"EgpIRUFUU0VFS0VSIJICKAE%3D","type":"ENTITY_MUTATION_TYPE_REPLACE","payload":{"macroMarkersListEntity":{"key":"EgpIRUFUU0VFS0VSIJICKAE%3D","externalVideoId":"VO88htcm09E","markersList":{"markerType":"MARKER_TYPE_HEATMAP","markers":[{"startMillis":"0","durationMillis":"2370","intensityScoreNormalized":0.95607400288322919},{"startMillis":"2370","durationMillis":"2370","intensityScoreNormalized":0.53340680991281664},{"startMillis":"4740","durationMillis":"2370","intensityScoreNormalized":0.53425241985309257},{"startMillis":"7110","durationMillis":"2370","intensityScoreNormalized":0.53596004668085395},{"startMillis":"9480","durationMillis":"2370","intensityScoreNormalized":0.55162730829958129},{"startMillis":"11850","durationMillis":"2370","intensityScoreNormalized":0.56407990663829199},{"startMillis":"14220","durationMillis":"2370","intensityScoreNormalized":0.57979103453010228},{"startMillis":"16590","durationMillis":"2370","intensityScoreNormalized":0.5906798929086291},{"startMillis":"18960","durationMillis":"2370","intensityScoreNormalized":0.61591528797968009},{"startMillis":"21330","durationMillis":"2370","intensityScoreNormalized":0.65988961350998832},{"startMillis":"23700","durationMillis":"2370","intensityScoreNormalized":0.68037536898469142},{"startMillis":"26070","durationMillis":"2370","intensityScoreNormalized":0.68134770371387388},{"startMillis":"28440","durationMillis":"2370","intensityScoreNormalized":0.6911774558934578},{"startMillis":"30810","durationMillis":"2370","intensityScoreNormalized":0.71084959154252758},{"startMillis":"33180","durationMillis":"2370","intensityScoreNormalized":0.72209542115741054},{"startMillis":"35550","durationMillis":"2370","intensityScoreNormalized":0.7643912953936981},{"startMillis":"37920","durationMillis":"2370","intensityScoreNormalized":0.78691082583922567},{"startMillis":"40290","durationMillis":"2370","intensityScoreNormalized":0.8348328413537448},{"startMillis":"42660","durationMillis":"2370","intensityScoreNormalized":0.83144545891398369},{"startMillis":"45030","durationMillis":"2370","intensityScoreNormalized":0.82801867234159399},{"startMillis":"47400","durationMillis":"2370","intensityScoreNormalized":0.81625523443399461},{"startMillis":"49770","durationMillis":"2370","intensityScoreNormalized":0.83080277339191322},{"startMillis":"52140","durationMillis":"2370","intensityScoreNormalized":0.83397157959772084},{"startMillis":"54510","durationMillis":"2370","intensityScoreNormalized":0.85942788494542455},{"startMillis":"56880","durationMillis":"2370","intensityScoreNormalized":0.8851958536417931},{"startMillis":"59250","durationMillis":"2370","intensityScoreNormalized":0.90345534427129814},{"startMillis":"61620","durationMillis":"2370","intensityScoreNormalized":0.90741168394315919},{"startMillis":"63990","durationMillis":"2370","intensityScoreNormalized":0.89951273426237388},{"startMillis":"66360","durationMillis":"2370","intensityScoreNormalized":0.91515480194961218},{"startMillis":"68730","durationMillis":"2370","intensityScoreNormalized":0.92816132353950709},{"startMillis":"71100","durationMillis":"2370","intensityScoreNormalized":0.96142362874991416},{"startMillis":"73470","durationMillis":"2370","intensityScoreNormalized":0.97725379281938629},{"startMillis":"75840","durationMillis":"2370","intensityScoreNormalized":1},{"startMillis":"78210","durationMillis":"2370","intensityScoreNormalized":0.97306432347085881},{"startMillis":"80580","durationMillis":"2370","intensityScoreNormalized":0.92810681677764806},{"startMillis":"82950","durationMillis":"2370","intensityScoreNormalized":0.85369327932999239},{"startMillis":"85320","durationMillis":"2370","intensityScoreNormalized":0.80319434337887008},{"startMillis":"87690","durationMillis":"2370","intensityScoreNormalized":0.75261042081416896},{"startMillis":"90060","durationMillis":"2370","intensityScoreNormalized":0.72280524473124186},{"startMillis":"92430","durationMillis":"2370","intensityScoreNormalized":0.69715439005972402},{"startMillis":"94800","durationMillis":"2370","intensityScoreNormalized":0.68093924624150481},{"startMillis":"97170","durationMillis":"2370","intensityScoreNormalized":0.67792434955721836},{"startMillis":"99540","durationMillis":"2370","intensityScoreNormalized":0.67097370769547604},{"startMillis":"101910","durationMillis":"2370","intensityScoreNormalized":0.68028859751493098},{"startMillis":"104280","durationMillis":"2370","intensityScoreNormalized":0.68622365620924008},{"startMillis":"106650","durationMillis":"2370","intensityScoreNormalized":0.69377854053682986},{"startMillis":"109020","durationMillis":"2370","intensityScoreNormalized":0.68560568408045586},{"startMillis":"111390","durationMillis":"2370","intensityScoreNormalized":0.69243577950161328},{"startMillis":"113760","durationMillis":"2370","intensityScoreNormalized":0.69147909658817874},{"startMillis":"116130","durationMillis":"2370","intensityScoreNormalized":0.70558454039953322},{"startMillis":"118500","durationMillis":"2370","intensityScoreNormalized":0.72698688817189538},{"startMillis":"120870","durationMillis":"2370","intensityScoreNormalized":0.78015459600466808},{"startMillis":"123240","durationMillis":"2370","intensityScoreNormalized":0.79231331090821722},{"startMillis":"125610","durationMillis":"2370","intensityScoreNormalized":0.77572952564014552},{"startMillis":"127980","durationMillis":"2370","intensityScoreNormalized":0.7737335072423972},{"startMillis":"130350","durationMillis":"2370","intensityScoreNormalized":0.75996636232580494},{"startMillis":"132720","durationMillis":"2370","intensityScoreNormalized":0.77018603693279331},{"startMillis":"135090","durationMillis":"2370","intensityScoreNormalized":0.75900405025056639},{"startMillis":"137460","durationMillis":"2370","intensityScoreNormalized":0.75536747442850283},{"startMillis":"139830","durationMillis":"2370","intensityScoreNormalized":0.75615514519118554},{"startMillis":"142200","durationMillis":"2370","intensityScoreNormalized":0.75914381821926269},{"startMillis":"144570","durationMillis":"2370","intensityScoreNormalized":0.75986998009198869},{"startMillis":"146940","durationMillis":"2370","intensityScoreNormalized":0.77486469417175807},{"startMillis":"149310","durationMillis":"2370","intensityScoreNormalized":0.78206233266973291},{"startMillis":"151680","durationMillis":"2370","intensityScoreNormalized":0.81537543763300613},{"startMillis":"154050","durationMillis":"2370","intensityScoreNormalized":0.84398132765840594},{"startMillis":"156420","durationMillis":"2370","intensityScoreNormalized":0.87561831537035761},{"startMillis":"158790","durationMillis":"2370","intensityScoreNormalized":0.8939058145122537},{"startMillis":"161160","durationMillis":"2370","intensityScoreNormalized":0.87428118349694517},{"startMillis":"163530","durationMillis":"2370","intensityScoreNormalized":0.82966485892771336},{"startMillis":"165900","durationMillis":"2370","intensityScoreNormalized":0.76253710441408662},{"startMillis":"168270","durationMillis":"2370","intensityScoreNormalized":0.72873398778059995},{"startMillis":"170640","durationMillis":"2370","intensityScoreNormalized":0.69537681059929979},{"startMillis":"173010","durationMillis":"2370","intensityScoreNormalized":0.69034022104757331},{"startMillis":"175380","durationMillis":"2370","intensityScoreNormalized":0.67678657238964779},{"startMillis":"177750","durationMillis":"2370","intensityScoreNormalized":0.67257472369053339},{"startMillis":"180120","durationMillis":"2370","intensityScoreNormalized":0.67325132148005762},{"startMillis":"182490","durationMillis":"2370","intensityScoreNormalized":0.66129045101942752},{"startMillis":"184860","durationMillis":"2370","intensityScoreNormalized":0.64888954486167361},{"startMillis":"187230","durationMillis":"2370","intensityScoreNormalized":0.6463393972677971},{"startMillis":"189600","durationMillis":"2370","intensityScoreNormalized":0.63875966225029179},{"startMillis":"191970","durationMillis":"2370","intensityScoreNormalized":0.60928468456099405},{"startMillis":"194340","durationMillis":"2370","intensityScoreNormalized":0.60370453765360066},{"startMillis":"196710","durationMillis":"2370","intensityScoreNormalized":0.58963163314340628},{"startMillis":"199080","durationMillis":"2370","intensityScoreNormalized":0.60387258872794669},{"startMillis":"201450","durationMillis":"2370","intensityScoreNormalized":0.60638772568133448},{"startMillis":"203820","durationMillis":"2370","intensityScoreNormalized":0.63271023546371941},{"startMillis":"206190","durationMillis":"2370","intensityScoreNormalized":0.63635038099814645},{"startMillis":"208560","durationMillis":"2370","intensityScoreNormalized":0.67021665408114228},{"startMillis":"210930","durationMillis":"2370","intensityScoreNormalized":0.64786448822681408},{"startMillis":"213300","durationMillis":"2370","intensityScoreNormalized":0.61790018535044966},{"startMillis":"215670","durationMillis":"2370","intensityScoreNormalized":0.54393087114711336},{"startMillis":"218040","durationMillis":"2370","intensityScoreNormalized":0.47509638223381617},{"startMillis":"220410","durationMillis":"2370","intensityScoreNormalized":0.39096670556737834},{"startMillis":"222780","durationMillis":"2370","intensityScoreNormalized":0.32197597308986065},{"startMillis":"225150","durationMillis":"2370","intensityScoreNormalized":0.25685755474703098},{"startMillis":"227520","durationMillis":"2370","intensityScoreNormalized":0.19081245280428366},{"startMillis":"229890","durationMillis":"2370","intensityScoreNormalized":0.11530136610146222},{"startMillis":"232260","durationMillis":"2370","intensityScoreNormalized":0.043207935745177457},{"startMillis":"234630","durationMillis":"2370","intensityScoreNormalized":0}],"markersMetadata":{"heatmapMetadata":{"maxHeightD \ No newline at end of file diff --git a/apps/server/src/collector/heatmap.ts b/apps/server/src/collector/heatmap.ts new file mode 100644 index 0000000..c3d5a9d --- /dev/null +++ b/apps/server/src/collector/heatmap.ts @@ -0,0 +1,94 @@ +/** + * 하이라이트 (docs/08 §3): YouTube's "가장 많이 다시 본 구간" (watch page heatmap markers) → highlight_sec. + * Admin-set highlights are never touched. The opening few seconds always peak (people start there), so they are ignored. + * One page per song, 3s apart, a daily cap, stops at the first block signal (the same home IP as music_bot_v2). + */ +import type { Database } from 'bun:sqlite'; +import { Catalog, Job, sleep } from './catalog'; +import { BROWSER_UA, Blocked } from './charts'; + +export interface Marker { + startMs: number; + durationMs: number; + intensity: number; +} + +export function parseHeatmap(html: string): Marker[] { + const i = html.indexOf('"markerType":"MARKER_TYPE_HEATMAP"'); + if (i < 0) return []; + const list = /"markers":\[([\s\S]*?)\]/.exec(html.slice(i, i + 200_000))?.[1] ?? ''; + return [...list.matchAll(/"startMillis":"(\d+)","durationMillis":"(\d+)","intensityScoreNormalized":([\d.eE-]+)/g)].map((m) => ({ + startMs: Number(m[1]), + durationMs: Number(m[2]), + intensity: Number(m[3]), + })); +} + +/** Start (seconds) of the most replayed stretch: 3-marker moving average, skipping the first 10% / last 5% of the song. */ +export function pickHighlight(markers: Marker[]): number | null { + if (markers.length < 10) return null; + const n = markers.length; + const from = Math.max(1, Math.ceil(n * 0.1)); + const to = Math.floor(n * 0.95); + let best = -1; + let at = -1; + for (let k = from; k < to; k++) { + const avg = (markers[k - 1]!.intensity + markers[k]!.intensity + markers[k + 1]!.intensity) / 3; + if (avg > best) ((best = avg), (at = k)); + } + if (at < 0) return null; + // start a little before the peak so the hook is heard from its beginning + return Math.max(0, Math.round((markers[at - 1]!.startMs / 1000) * 10) / 10); +} + +export async function collectHeatmaps(db: Database, opts: { limit?: number; delayMs?: number; fetchPage?: (id: string) => Promise } = {}) { + const rows = db + .query<{ id: number; youtube_id: string }, [number, number]>( + `SELECT s.id, s.youtube_id FROM songs s WHERE s.deleted_at IS NULL AND s.youtube_status = 'matched' AND s.youtube_id IS NOT NULL + AND COALESCE(s.highlight_source, '') NOT IN ('admin', 'heatmap') + AND NOT EXISTS (SELECT 1 FROM signals g WHERE g.song_id = s.id AND g.kind = 'yt_heatmap_tried' AND g.value > ?) + ORDER BY s.id LIMIT ?`, + ) + .all(Date.now() - 30 * 86400_000, opts.limit ?? 500); + const fetchPage = + opts.fetchPage ?? + (async (id: string) => { + const res = await fetch(`https://www.youtube.com/watch?v=${id}&hl=ko`, { headers: { 'user-agent': BROWSER_UA, 'accept-language': 'ko-KR,ko;q=0.9' }, signal: AbortSignal.timeout(20_000) }); + if (res.status === 429 || res.status === 403) throw new Blocked(`youtube ${res.status}`); + const text = await res.text(); + if (/consent\.youtube\.com|google\.com\/sorry/.test(res.url) || (/g-recaptcha|unusual traffic/i.test(text) && text.length < 200_000)) throw new Blocked('youtube bot check'); + return text; + }); + const job = new Job(db, 'heatmap', rows.length); + const cat = new Catalog(db); + const stats = { set: 0, none: 0, failed: 0 }; + try { + for (const [i, s] of rows.entries()) { + try { + const sec = pickHighlight(parseHeatmap(await fetchPage(s.youtube_id))); + if (sec !== null) { + db.query("UPDATE songs SET highlight_sec = ?, highlight_source = 'heatmap', updated_at = ? WHERE id = ? AND COALESCE(highlight_source, '') <> 'admin'").run(sec, Date.now(), s.id); + stats.set++; + } else stats.none++; + cat.signal(s.id, 'yt_heatmap_tried', Date.now()); + } catch (e) { + stats.failed++; + if (e instanceof Blocked) { + job.log(`stopped: ${(e as Error).message}`); + break; + } + job.log(`${s.youtube_id} failed: ${(e as Error).message}`); + } + job.progress(i + 1); + if ((i + 1) % 50 === 0) job.log(`heatmap ${i + 1}/${rows.length}: set ${stats.set}, no data ${stats.none}`); + await sleep(opts.delayMs ?? 3000); + } + job.log(`heatmap done: set ${stats.set}, no data ${stats.none}, failed ${stats.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/levels.ts b/apps/server/src/collector/levels.ts new file mode 100644 index 0000000..8278c6b --- /dev/null +++ b/apps/server/src/collector/levels.ts @@ -0,0 +1,143 @@ +/** + * 난이도 계산 (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): Map { + const sorted = [...scores].sort((a, b) => b[1] - a[1] || a[0] - b[0]); + const out = new Map(); + 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 { + const songs = db.query<{ id: number }, []>('SELECT id FROM songs WHERE deleted_at IS NULL').all(); + const map = new Map(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; scopes: number } { + const job = new Job(db, 'levels', 0); + const cat = new Catalog(db); + const signals = loadSignals(db); + const scores = new Map(); + for (const [id, s] of signals) scores.set(id, popularity(s)); + const scopes = new Map([['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 = {}; + 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 }; +} diff --git a/apps/server/src/db/migrations/006_charts.sql b/apps/server/src/db/migrations/006_charts.sql new file mode 100644 index 0000000..37040dd --- /dev/null +++ b/apps/server/src/db/migrations/006_charts.sql @@ -0,0 +1,15 @@ +-- 9단계 수집 확장 (docs/07): raw chart rows, kept so re-classifying never re-fetches. +CREATE TABLE chart_entries ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + source TEXT NOT NULL, -- melon | genie | bugs | tj + chart TEXT NOT NULL, -- year-kpop | year-pop | year | realtime + period TEXT NOT NULL, -- 2005 | 2026-10-18 + rank INTEGER NOT NULL, + raw_title TEXT NOT NULL, + raw_artist TEXT NOT NULL, + raw_ref TEXT, + song_id INTEGER REFERENCES songs(id) ON DELETE SET NULL, + fetched_at INTEGER NOT NULL, + UNIQUE (source, chart, period, rank) +); +CREATE INDEX chart_entries_song ON chart_entries(song_id); diff --git a/apps/web/src/pages/admin/AdminMore.tsx b/apps/web/src/pages/admin/AdminMore.tsx index a0691c5..9a1c9c4 100644 --- a/apps/web/src/pages/admin/AdminMore.tsx +++ b/apps/web/src/pages/admin/AdminMore.tsx @@ -437,7 +437,7 @@ export function CollectPage() { const t = setInterval(reload, 5000); return () => clearInterval(t); }, [reload]); - const label = (kind: string) => data?.kinds.find((k) => k.id === kind)?.label ?? { 'import-norabose': '노라보세 가져오기', 'import-sta': '스타맵 가져오기' }[kind] ?? kind; + const label = (kind: string) => data?.kinds.find((k) => k.id === kind)?.label ?? { 'import-norabose': '노라보세 가져오기', 'import-sta': '스타맵 가져오기', 'melon-detail': '멜론 곡 정보', heatmap: '하이라이트 찾기', levels: '난이도 계산', charts: '차트 모으기' }[kind] ?? kind; return ( <>

수집