9단계 수집 확장: 멜론 연도별·실시간, 지니 연도별, 벅스 실시간, TJ 노래방 연간 차트(chart_entries) + 멜론 곡 정보(발매일·장르·가사) + 유튜브 많이 다시 본 구간 하이라이트 + 인기도 점수로 난이도 10단계(전체·큰 장르·연대별), 관리자 수집 화면에서 실행

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-18 22:34:08 +09:00
parent 4165712fac
commit 46240ac699
13 changed files with 1277 additions and 3 deletions

View File

@@ -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);
});
});

View File

@@ -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(/&nbsp;/g, ' ')
.replace(/&amp;/g, '&')
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&#39;|&apos;/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(/<tr class="lst(?:50|100)"/).slice(1)) {
const ref = /name="input_check" value="(\d+)"/.exec(block)?.[1] ?? /data-song-no="(\d+)"/.exec(block)?.[1];
const rank = Number(/<span class="rank[^"]*">\s*(\d+)/.exec(block)?.[1]);
const title = /class="ellipsis rank01">[\s\S]*?<a [^>]*>([\s\S]*?)<\/a>/.exec(block)?.[1];
const artistPart = /class="ellipsis rank02">([\s\S]*?)<span class="checkEllipsis"/.exec(block)?.[1] ?? '';
const artists = [...artistPart.matchAll(/artistId=(\d+)[^>]*>([\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(/<tr class="list" songid=/).slice(1)) {
const ref = /^"(\d+)"/.exec(block)?.[1];
const rank = Number(/<td class="number">\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(/<span class="icon[^"]*">[\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(/<tr [^>]*rowType="track"/).slice(0)) {
const ref = /trackId="(\d+)"/.exec(block)?.[1] ?? /name="_isStream" value="(\d+)"/.exec(block)?.[1];
const rank = Number(/<div class="ranking">\s*<strong>(\d+)<\/strong>/.exec(block)?.[1]);
const title = /<p class="title"[^>]*>\s*<a [^>]*>([\s\S]*?)<\/a>/.exec(block)?.[1];
const artist = /<p class="artist">[\s\S]*?<a [^>]*>([\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<ChartRow[]>;
}
export class Blocked extends Error {}
async function get(url: string, init: RequestInit = {}): Promise<string> {
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<ChartSpec, 'source' | 'chart' | 'period' | 'create' | 'year'>, 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<string>();
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 = /<dl class="list">([\s\S]*?)<\/dl>/.exec(html)?.[1] ?? '';
const field = (name: string) => decode(new RegExp(`<dt>${name}</dt>\\s*<dd>([\\s\\S]*?)</dd>`).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(/<!--[\s\S]*?-->/g, '').replace(/<br\s*\/?>/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;
}

View File

@@ -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();

View File

@@ -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)] : [])];
}

View File

@@ -0,0 +1,168 @@
<table><tr albumId="4156473" artistId="80409316" mvId="641880" trackId="6511885" multiArtist="Y" rowType="track" >
<input type="hidden" name="_isStream" value="6511885" />
<input type="hidden" name="_isDown" value="6511885" />
<td class="check"><input type="checkbox" value="6511885" name="check" disc_id="1" title="NEON" buyMinQuality="T"></td>
<td>
<div class="ranking">
<strong>1</strong>
<p class="change none"><em>0</em><span>변동없음</span></p>
</div>
</td>
<td>
<a href="https://music.bugs.co.kr/album/4156473?wl_ref=list_tr_07_chart" class="thumbnail"
onclick="
">
<span class="mask"></span>
<img src="https://image.bugsm.co.kr/album/images/50/41564/4156473.jpg?version=20261014014805" onerror="bugs.utils.imgError(this);" alt="NEON 대표이미지">
</a>
</td>
<td >
<a href="https://music.bugs.co.kr/track/6511885?wl_ref=list_tr_08_chart" class="trackInfo"
onclick="
">곡정보</a>
</td>
<th scope="row">
<p class="title" adult_yn="N">
<a href="javascript:;" adultCheckVal="1"
onclick="bugs.wiselog.area('list_tr_09_chart');bugs.music.listen('6511885',true);
"
title="NEON" aria-label="새창">NEON</a>
</p>
</th>
<td class="left">
<p class="artist">
<!-- a tag title -->
<a href="https://music.bugs.co.kr/artist/80409316?wl_ref=list_tr_10_chart" class="artistTitle" title="A2O" >A2O</a>
<!-- a tag link -->
<a href="javascript:void(0);" name="atag_martist_list" class="more" title="아티스트 전체보기" wise_log_str="?wl_ref=list_tr_10_chart" onclick="bugs.layermenu.openMultiArtistSearchResultPopLayer(this, 'A2O||A2O||80409316||OK\\nA2O LITE||A2O LITE||14891482||OK', ''); return false;">
A2O
</a> </p>
</td>
<td class="left" >
<a href="https://music.bugs.co.kr/album/4156473?wl_ref=list_tr_11_chart" class="album" title="NEON"
onclick="
">NEON</a>
</td>
<td>
<a href="javascript:;" adultCheckVal="1"
onclick="bugs.wiselog.area('list_tr_12_chart');bugs.music.listen('6511885',true);
"
class="btn play" aria-label="새창">듣기</a>
</td>
<td>
<a href="javascript:;" adultCheckVal="1"
onclick="bugs.wiselog.area('list_tr_13_chart');bugs.music.listen('6511885');
"
class="btn addPlaylist" aria-label="새창">재생목록에 추가</a>
</td>
<td>
<a href="javascript:;" onclick="bugs.wiselog.area('list_tr_14_chart');bugs.music.addTrackToMyAlbum(this,'6511885');
"
track_title="NEON" class="btn addAlbum">내 앨범에 담기</a>
</td>
<td>
<a href="javascript:;" adultCheckVal="1" onclick="bugs.wiselog.area('list_tr_15_chart');bugs.layermenu.down(this,'6511885','true','true','44.1','false','', null );
"
class="btn download flac" aria-label="새창"><em class="flac">flac </em>다운로드</a>
</td>
<td>
<a href="javascript:;" onclick="bugs.wiselog.area('list_tr_16_chart');
bugs.layermenu.mv(this,6511885, 641880, 'Y', 'Y', 'Y', 'Y', 6511885, 'N','ALL', 'N', '');
"
class="btn viewMV" aria-label="새창">영상 재생</a>
</td>
<td>
<a href="javascript:;"
onclick="bugs.wiselog.area('list_tr_17_chart');
bugs.layermenu.trackMoreAction(this,'6511885','0','4156473','bugs.music.listenRadioFromSeed(\'6511885\',\'track\');','N', 'Y', '_chart');
"
track_title="NEON"
artist_id="80409316"
artist_disp_nm="A2O"
layerPositionTarget="td"
layer_type="CHART"
class="btnActions">기타 기능</a>
</td>
</tr>
<tr albumId="20818608" artistId="14619367" mvId="0" trackId="33972776" multiArtist="N" rowType="track" >
<input type="hidden" name="_isStream" value="33972776" />
<input type="hidden" name="_isDown" value="33972776" />
<td class="check"><input type="checkbox" value="33972776" name="check" disc_id="1" title="꿈꾸던 어른이 되었나요?" buyMinQuality="T"></td>
<td>
<div class="ranking">
<strong>2</strong>
<p class="change none"><em>0</em><span>변동없음</span></p>
</div>
</td>
<td>
<a href="https://music.bugs.co.kr/album/20818608?wl_ref=list_tr_07_chart" class="thumbnail"
onclick="
">
<span class="mask"></span>
<img src="https://image.bugsm.co.kr/album/images/50/208186/20818608.jpg?version=20261016011623" onerror="bugs.utils.imgError(this);" alt="꿈꾸던 어른이 되었나요? 대표이미지">
</a>
</td>
<td >
<a href="https://music.bugs.co.kr/track/33972776?wl_ref=list_tr_08_chart" class="trackInfo"
onclick="
">곡정보</a>
</td>
<th scope="row">
<p class="title" adult_yn="N">
<a href="javascript:;" adultCheckVal="1"
onclick="bugs.wiselog.area('list_tr_09_chart');bugs.music.listen('33972776',true);
"
title="꿈꾸던 어른이 되었나요?" aria-label="새창">꿈꾸던 어른이 되었나요?</a>
</p>
</th>
<td class="left">
<p class="artist">
<a href="https://music.bugs.co.kr/artist/14619367?wl_ref=list_tr_10_chart" title="머무르"
onclick="
">머무르</a>
</p>
</td>
<td class="left" >
<a href="https://music.bugs.co.kr/album/20818608?wl_ref=list_tr_11_chart" class="album" title="꿈꾸던 어른이 되었나요?"
onclick="
">꿈꾸던 어른이 되었나요?</a>
</td>
<td>
<a href="javascript:;" adultCheckVal="1"
onclick="bugs.wiselog.area('list_tr_12_chart');bugs.music.listen('33972776',true);
"
class="btn play" aria-label="새창">듣기</a>
</td>
<td>
<a href="javascript:;" adultCheckVal="1"
onclick="bugs.wiselog.area('list_tr_13_chart');bugs.music.listen('33972776');
"
class="btn addPlaylist" aria-label="새창">재생목록에 추가</a>
</td>
<td>
<a href="javascript:;" onclick="bugs.wiselog.area('list_tr_14_chart');bugs.music.addTrackToMyAlbum(this,'33972776');
"
track_title="꿈꾸던 어른이 되었나요?" class="btn addAlbum">내 앨범에 담기</a>
</td>
<td>
<a href="javascript:;" adultCheckVal="1" onclick="bugs.wiselog.area('list_tr_15_chart');bugs.layermenu.down(this,'33972776','true','true','44.1','true','48', null );
"
class="btn download flac" aria-label="새창"><em class="flac">flac </em>다운로드</a>
</td>
<td>
<span class="btn viewMV">영상 재생 불가</span>
</td>
<td>
<a href="javascript:;"
onclick="bugs.wiselog.area('list_tr_17_chart');
bugs.layermenu.trackMoreAction(this,'33972776','0','20818608','bugs.music.listenRadioFromSeed(\'33972776\',\'track\');','N', 'Y', '_chart');
"
track_title="꿈꾸던 어른이 되었나요?"
artist_id="14619367"
artist_disp_nm="머무르"
layerPositionTarget="td"
layer_type="CHART"
class="btnActions">기타 기능</a>
</td>
</tr>
</table>

View File

@@ -0,0 +1,211 @@
<table><tr class="list" songid="16188070">
<td class="check"><input type="checkbox" class="select-check" title="죄와 벌 (罪와 罰)" /></td>
<td class="number">1
</td>
<td><a href="#" class="cover" onclick="fnViewAlbumLayer('15029509');return false;"><span class="mask"></span><img src="//image.genie.co.kr/Y/IMAGE/IMG_ALBUM/015/029/509/15029509_1391496911476_1_140x140.JPG/dims/resize/Q_80,0" onerror="this.src='//image.genie.co.kr/imageg/web/common/blank_68.gif';" alt="2집 살다가" /></a></td>
<td class="link"><a href="#" class="btn-basic btn-info" onclick="fnViewSongInfo('16188070');return false;">곡 제목 정보 페이지</a></td>
<td class="info">
<a href="#" class="title ellipsis" title="재생" onclick="fnPlaySong('16188070','1');return false;">
<span class="icon icon-title">TITLE</span>
죄와 벌 (罪와 罰)</a>
<a href="#" class="artist ellipsis" onclick="fnViewArtist('14949971');return false;">SG워너비</a>
<i class="bar">|</i>
<a href="#" class="albumtitle ellipsis" onclick="fnViewAlbumLayer('15029509');return false;">2집 살다가</a>
</td>
<td class="btns"><a href="#" class="btn-basic btn-listen" title="재생" onclick="fnPlaySong('16188070;' ,'1'); return false;">듣기</a></td>
<td class="btns"><a href="#" class="btn-basic btn-add" title="추가" onclick="fnPlaySong('16188070;' ,'3'); return false;">재생목록에 추가</a></td>
<td class="btns"><button type="button" class="btn-basic btn-album" songId="16188070" id="add_my_album_16188070" onclick="fnAddMyAlbumForm('#add_my_album_16188070' , '16188070' ,10, 10);return false;">플레이리스트에 담기</button></td>
<td class="btns"><a href="#" class="btn-basic btn-down" title="다운" onclick="fnDownSong('16188070');return false;">다운로드</a></td>
<td class="btns">
<div class="toggle-button-box lyr-mv" id="list-mv_16188070">
<a href="#" class="btn btn-basic btn-mv" title="뮤비" alt="죄와 벌 (罪와 罰)" onclick="fnPlayMv('16188070','3'); return false;">뮤직비디오 보기</a>
</div>
</td>
<td class="more">
<div class="toggle-button-box">
<button type="button" class="btn btn-basic btn-more">더보기</button>
<ul class="list">
<li><a href="#" class="item" title="공유" onclick="shareDo('16188070');return false;">공유하기/음악나누기</a></li>
<li><a href="#" class="item" title="선물" onclick="fnGiftSong('16188070');return false;">선물하기</a></li>
</ul>
</div>
</td>
</tr>
<tr class="list" songid="17465590">
<td class="check"><input type="checkbox" class="select-check" title="겁쟁이" /></td>
<td class="number">2
</td>
<td><a href="#" class="cover" onclick="fnViewAlbumLayer('17465580');return false;"><span class="mask"></span><img src="//image.genie.co.kr/Y/IMAGE/IMG_ALBUM/017/465/580/17465580_1678087775917_1_140x140.JPG/dims/resize/Q_80,0" onerror="this.src='//image.genie.co.kr/imageg/web/common/blank_68.gif';" alt="Buzz Effect " /></a></td>
<td class="link"><a href="#" class="btn-basic btn-info" onclick="fnViewSongInfo('17465590');return false;">곡 제목 정보 페이지</a></td>
<td class="info">
<a href="#" class="title ellipsis" title="재생" onclick="fnPlaySong('17465590','1');return false;">
<span class="icon icon-title">TITLE</span>
겁쟁이</a>
<a href="#" class="artist ellipsis" onclick="fnViewArtist('14940266');return false;">버즈 (Buzz)</a>
<i class="bar">|</i>
<a href="#" class="albumtitle ellipsis" onclick="fnViewAlbumLayer('17465580');return false;">Buzz Effect </a>
</td>
<td class="btns"><a href="#" class="btn-basic btn-listen" title="재생" onclick="fnPlaySong('17465590;' ,'1'); return false;">듣기</a></td>
<td class="btns"><a href="#" class="btn-basic btn-add" title="추가" onclick="fnPlaySong('17465590;' ,'3'); return false;">재생목록에 추가</a></td>
<td class="btns"><button type="button" class="btn-basic btn-album" songId="17465590" id="add_my_album_17465590" onclick="fnAddMyAlbumForm('#add_my_album_17465590' , '17465590' ,10, 10);return false;">플레이리스트에 담기</button></td>
<td class="btns"><a href="#" class="btn-basic btn-down" title="다운" onclick="fnDownSong('17465590');return false;">다운로드</a></td>
<td class="btns">
<div class="toggle-button-box lyr-mv" id="list-mv_17465590">
<a href="#" class="btn btn-basic btn-mv" title="뮤비" alt="겁쟁이" onclick="fnPlayMv('17465590','3'); return false;">뮤직비디오 보기</a>
</div>
</td>
<td class="more">
<div class="toggle-button-box">
<button type="button" class="btn btn-basic btn-more">더보기</button>
<ul class="list">
<li><a href="#" class="item" title="공유" onclick="shareDo('17465590');return false;">공유하기/음악나누기</a></li>
<li><a href="#" class="item" title="선물" onclick="fnGiftSong('17465590');return false;">선물하기</a></li>
</ul>
</div>
</td>
</tr>
<tr class="list" songid="17455815">
<td class="check"><input type="checkbox" class="select-check" title="사랑했나봐" /></td>
<td class="number">3
</td>
<td><a href="#" class="cover" onclick="fnViewAlbumLayer('17345265');return false;"><span class="mask"></span><img src="//image.genie.co.kr/Y/IMAGE/IMG_ALBUM/017/345/265/17345265_1641258325766_1_140x140.JPG/dims/resize/Q_80,0" onerror="this.src='//image.genie.co.kr/imageg/web/common/blank_68.gif';" alt="Difference" /></a></td>
<td class="link"><a href="#" class="btn-basic btn-info" onclick="fnViewSongInfo('17455815');return false;">곡 제목 정보 페이지</a></td>
<td class="info">
<a href="#" class="title ellipsis" title="재생" onclick="fnPlaySong('17455815','1');return false;">
<span class="icon icon-title">TITLE</span>
사랑했나봐</a>
<a href="#" class="artist ellipsis" onclick="fnViewArtist('14952120');return false;">윤도현</a>
<i class="bar">|</i>
<a href="#" class="albumtitle ellipsis" onclick="fnViewAlbumLayer('17345265');return false;">Difference</a>
</td>
<td class="btns"><a href="#" class="btn-basic btn-listen" title="재생" onclick="fnPlaySong('17455815;' ,'1'); return false;">듣기</a></td>
<td class="btns"><a href="#" class="btn-basic btn-add" title="추가" onclick="fnPlaySong('17455815;' ,'3'); return false;">재생목록에 추가</a></td>
<td class="btns"><button type="button" class="btn-basic btn-album" songId="17455815" id="add_my_album_17455815" onclick="fnAddMyAlbumForm('#add_my_album_17455815' , '17455815' ,10, 10);return false;">플레이리스트에 담기</button></td>
<td class="btns"><a href="#" class="btn-basic btn-down" title="다운" onclick="fnDownSong('17455815');return false;">다운로드</a></td>
<td class="btns">
<div class="toggle-button-box lyr-mv" id="list-mv_17455815">
<a href="#" class="btn btn-basic btn-mv" title="뮤비" alt="사랑했나봐" onclick="fnPlayMv('17455815','3'); return false;">뮤직비디오 보기</a>
</div>
</td>
<td class="more">
<div class="toggle-button-box">
<button type="button" class="btn btn-basic btn-more">더보기</button>
<ul class="list">
<li><a href="#" class="item" title="공유" onclick="shareDo('17455815');return false;">공유하기/음악나누기</a></li>
<li><a href="#" class="item" title="선물" onclick="fnGiftSong('17455815');return false;">선물하기</a></li>
</ul>
</div>
</td>
</tr>
</table>

View File

@@ -0,0 +1,163 @@
<table><tr class="lst50" id="lst50" >
<td><div class="wrap pd_none left">
<input type="checkbox" title="죄와벌 곡 선택" class="input_check" name="input_check" value="711627" />
</div></td>
<td><div class="wrap">
<span class="rank top">1</span>
</div></td>
<td><div class="wrap">
<a href="/album/detail.htm?albumId=50578" class="image_type15">
<img onerror="WEBPOCIMG.defaultAlbumImg(this);" width="48" height="48" src="https://cdnimg.melon.co.kr/cm/album/images/000/50/578/50578_500.jpg/melon/resize/48/quality/80/optimize" alt="죄와벌 앨범 이미지"/>
<span class="bg_album_frame"></span>
</a>
</div></td>
<td class="t_left"><div class="wrap">
<button type="button" class="btn_icon play" title="재생" onclick="melon.play.playSong('19070205',711627);"><span class="odd_span">재생</span></button>
<button type="button" class="btn_icon add" title="담기" onclick="melon.play.addPlayList(711627);"><span class="odd_span">담기</span></button>
<a href="/song/detail.htm?songId=711627" title="곡정보 보기" class="btn btn_icon_detail"><span class="odd_span">죄와벌 상세정보 페이지 이동</span></a>
<div class="wrap_song_info">
<div class="ellipsis rank01"><span>
<strong><a href="javascript:melon.play.playSong('19070205','711627');" title="죄와벌" >죄와벌 </a></strong>
</span></div><br />
<div>
<div class="ellipsis rank02"><a href="/artist/detail.htm?artistId=108363" title="SG&nbsp;워너비 - 페이지 이동">SG&nbsp;워너비</a><span class="checkEllipsis" style="display:none"><a href="javascript:melon.link.goArtistDetail('108363');" title="SG 워너비 - 페이지 이동" class="fc_mgray">SG 워너비</a></span></div>
<em class="bar">|</em>
<div class="ellipsis rank03">
<a href="/album/detail.htm?albumId=50578" title="살다가 - 페이지 이동" class="fc_mgray">살다가</a>
</div>
</div>
</div>
</div></td>
<td class="t_left"><div class="wrap right_none">
<button type="button" class="btn_icon like" title="죄와벌 좋아요" data-song-no="711627" data-song-menuId="19070205">
<span class="odd_span">좋아요</span>
<span class="cnt"><span class="none">총건수</span>0</span>
</button>
</div></td>
<td><div class="wrap pd_none left">
<button type="button" class="btn_icon mv" title="죄와벌 뮤직비디오 - 페이지 이동" onClick="melon.link.goMvDetail('19070205', '711627','song');"><span class="odd_span">뮤직비디오</span></button>
</div></td>
<td><div class="wrap pd_none right">
<button type="button" class="btn_icon dl" title="죄와벌 다운로드 - 새창" onClick="melon.buy.goBuyProduct('frm', '711627', '3C0001', '','0', '');"><span class="odd_span">다운로드</span></button>
</div></td>
</tr>
<tr class="lst50" id="lst50" >
<td><div class="wrap pd_none left">
<input type="checkbox" title="겁쟁이 곡 선택" class="input_check" name="input_check" value="732512" />
</div></td>
<td><div class="wrap">
<span class="rank top">2</span>
</div></td>
<td><div class="wrap">
<a href="/album/detail.htm?albumId=300646" class="image_type15">
<img onerror="WEBPOCIMG.defaultAlbumImg(this);" width="48" height="48" src="https://cdnimg.melon.co.kr/cm2/album/images/003/00/646/300646_20230306155609_500.jpg/melon/resize/48/quality/80/optimize" alt="겁쟁이 앨범 이미지"/>
<span class="bg_album_frame"></span>
</a>
</div></td>
<td class="t_left"><div class="wrap">
<button type="button" class="btn_icon play" title="재생" onclick="melon.play.playSong('19070205',732512);"><span class="odd_span">재생</span></button>
<button type="button" class="btn_icon add" title="담기" onclick="melon.play.addPlayList(732512);"><span class="odd_span">담기</span></button>
<a href="/song/detail.htm?songId=732512" title="곡정보 보기" class="btn btn_icon_detail"><span class="odd_span">겁쟁이 상세정보 페이지 이동</span></a>
<div class="wrap_song_info">
<div class="ellipsis rank01"><span>
<strong><a href="javascript:melon.play.playSong('19070205','732512');" title="겁쟁이" >겁쟁이 </a></strong>
</span></div><br />
<div>
<div class="ellipsis rank02"><a href="/artist/detail.htm?artistId=160091" title="버즈 - 페이지 이동">버즈</a><span class="checkEllipsis" style="display:none"><a href="javascript:melon.link.goArtistDetail('160091');" title="버즈 - 페이지 이동" class="fc_mgray">버즈</a></span></div>
<em class="bar">|</em>
<div class="ellipsis rank03">
<a href="/album/detail.htm?albumId=300646" title="Buzz Effect - 페이지 이동" class="fc_mgray">Buzz Effect</a>
</div>
</div>
</div>
</div></td>
<td class="t_left"><div class="wrap right_none">
<button type="button" class="btn_icon like" title="겁쟁이 좋아요" data-song-no="732512" data-song-menuId="19070205">
<span class="odd_span">좋아요</span>
<span class="cnt"><span class="none">총건수</span>0</span>
</button>
</div></td>
<td><div class="wrap pd_none left">
<button type="button" class="btn_icon mv" title="겁쟁이 뮤직비디오 - 페이지 이동" onClick="melon.link.goMvDetail('19070205', '732512','song');"><span class="odd_span">뮤직비디오</span></button>
</div></td>
<td><div class="wrap pd_none right">
<button type="button" class="btn_icon dl" title="겁쟁이 다운로드 - 새창" onClick="melon.buy.goBuyProduct('frm', '732512', '3C0001', '','0', '');"><span class="odd_span">다운로드</span></button>
</div></td>
</tr>
<tr class="lst50" id="lst50" >
<td><div class="wrap pd_none left">
<input type="checkbox" title="사랑했나봐 곡 선택" class="input_check" name="input_check" value="837567" />
</div></td>
<td><div class="wrap">
<span class="rank top">3</span>
</div></td>
<td><div class="wrap">
<a href="/album/detail.htm?albumId=301886" class="image_type15">
<img onerror="WEBPOCIMG.defaultAlbumImg(this);" width="48" height="48" src="https://cdnimg.melon.co.kr/cm/album/images/003/01/886/301886_500.jpg/melon/resize/48/quality/80/optimize" alt="사랑했나봐 앨범 이미지"/>
<span class="bg_album_frame"></span>
</a>
</div></td>
<td class="t_left"><div class="wrap">
<button type="button" class="btn_icon play" title="재생" onclick="melon.play.playSong('19070205',837567);"><span class="odd_span">재생</span></button>
<button type="button" class="btn_icon add" title="담기" onclick="melon.play.addPlayList(837567);"><span class="odd_span">담기</span></button>
<a href="/song/detail.htm?songId=837567" title="곡정보 보기" class="btn btn_icon_detail"><span class="odd_span">사랑했나봐 상세정보 페이지 이동</span></a>
<div class="wrap_song_info">
<div class="ellipsis rank01"><span>
<strong><a href="javascript:melon.play.playSong('19070205','837567');" title="사랑했나봐" >사랑했나봐 </a></strong>
</span></div><br />
<div>
<div class="ellipsis rank02"><a href="/artist/detail.htm?artistId=923" title="윤도현 - 페이지 이동">윤도현</a><span class="checkEllipsis" style="display:none"><a href="javascript:melon.link.goArtistDetail('923');" title="윤도현 - 페이지 이동" class="fc_mgray">윤도현</a></span></div>
<em class="bar">|</em>
<div class="ellipsis rank03">
<a href="/album/detail.htm?albumId=301886" title="Difference - 페이지 이동" class="fc_mgray">Difference</a>
</div>
</div>
</div>
</div></td>
<td class="t_left"><div class="wrap right_none">
<button type="button" class="btn_icon like" title="사랑했나봐 좋아요" data-song-no="837567" data-song-menuId="19070205">
<span class="odd_span">좋아요</span>
<span class="cnt"><span class="none">총건수</span>0</span>
</button>
</div></td>
<td><div class="wrap pd_none left">
<button type="button" disabled="disabled" class="btn_icon mv disabled" title="사랑했나봐 뮤직비디오 - 페이지 이동" onClick="melon.link.goMvDetail('19070205', '837567','song');"><span class="odd_span">뮤직비디오</span></button>
</div></td>
<td><div class="wrap pd_none right">
<button type="button" class="btn_icon dl" title="사랑했나봐 다운로드 - 새창" onClick="melon.buy.goBuyProduct('frm', '837567', '3C0001', '','0', '');"><span class="odd_span">다운로드</span></button>
</div></td>
</tr>
</table>

View File

@@ -0,0 +1,13 @@
<dl class="list">
<dt>앨범</dt>
<dd><a href="javascript:melon.link.goAlbumDetail('300646');">Buzz&nbsp;Effect</a></dd>
<dt>발매일</dt>
<dd>2005.03.03</dd>
<dt>장르</dt>
<dd>록/메탈</dd>
<dt>FLAC</dt>
<dd>Flac 16bit</dd>
</dl>
<div class="lyric" id="d_video_summary"><!-- height:auto; 로 변경시, 확장됨 --> 첫째 줄 가사<br>둘째 줄 &amp; 가사<br><br>셋째 줄</div>

File diff suppressed because one or more lines are too long

View File

@@ -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<string> } = {}) {
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;
}

View File

@@ -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<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 };
}

View File

@@ -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);

View File

@@ -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 (
<>
<h1>수집</h1>