원곡이 아닌 곡 정리 1단계: 제목 정리 함수(cleanTitle — 괄호·feat.·버전 표시를 지우고 괄호 안 다른 이름은 정답 별칭으로, 앞 괄호·Part 번호는 단어로 남김, 일본어 제목+한글 괄호는 한글 제목)와 원곡 아님 판별(versionKind: remix/live/inst/acoustic/sped, videoVersionKind: 영상만 라이브·반주). drop-versions CLI(--dry-run, --keep): 리믹스·라이브·Inst. 곡과 영상이 라이브·반주인 재생 곡을 휴지통으로. 차트는 리믹스·라이브·Inst.를 새 곡으로 넣지 않음. 원곡 찾기: 영상 제목이 '- Bossa Unplugged'처럼 다른 버전이면 연결하지 않음(놓치던 것). 테스트

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-11-04 15:52:43 +09:00
parent 4e2b81c224
commit 239c314764
9 changed files with 384 additions and 8 deletions

View File

@@ -4,7 +4,7 @@
* 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 { songMatchKey, versionKind } from '@mq/shared';
import { Catalog, Job, sleep } from './catalog';
import { decodeEntities } from './text';
@@ -175,7 +175,8 @@ export function saveChart(db: Database, spec: Pick<ChartSpec, 'source' | 'chart'
db.transaction(() => {
for (const row of rows) {
let songId = findSong(db, spec.source, row);
if (!songId && spec.create) {
// a remix / live / inst. on the chart is not a new song for the quiz (docs/13): left unlinked
if (!songId && spec.create && !versionKind(row.title)) {
const [id, isNew] = cat.upsert({
melonId: spec.source === 'melon' ? Number(row.ref) : null,
title: row.title,

View File

@@ -12,6 +12,7 @@
* bun apps/server/src/collector/cli.ts age-audio [--limit N] [--delay ms] (연령제한 곡: download their audio with the adult-verified cookie, docs/08 §2-1)
* bun apps/server/src/collector/cli.ts levels
* bun apps/server/src/collector/cli.ts fix-text (one-off: decode `&#x27;`/`&amp;` saved in titles, let 원곡 찾기 retry them)
* bun apps/server/src/collector/cli.ts drop-versions [--dry-run] [--keep id,id] (one-off: remix/live/inst. songs and songs linked to such a video → 휴지통)
* bun apps/server/src/collector/cli.ts stats
* In the container: docker exec music_quiz-app-1 bun apps/server/src/collector/cli.ts …
*/
@@ -29,7 +30,7 @@ import { collectLoudness } from './loudness';
import { computeLevels } from './levels';
import { collectAgeAudio } from './age-audio';
import { audioDir } from '../songs/audio';
import { fixEntities } from './text';
import { dropVersions, fixEntities } from './text';
const [cmd, ...rest] = process.argv.slice(2);
const flag = (name: string) => {
@@ -96,11 +97,19 @@ switch (cmd) {
case 'fix-text':
console.log(JSON.stringify(fixEntities(db), null, 1));
break;
case 'drop-versions': {
const i = rest.indexOf('--keep');
const keep = i >= 0 ? rest[i + 1]!.split(',').map(Number).filter(Number.isFinite) : [];
const r = dropVersions(db, { dryRun: rest.includes('--dry-run'), keep });
for (const s of r.songs) console.log(`${s.id}\t${s.why}:${s.kind}\t${s.artist} - ${s.title}${s.why === 'video' ? `\t(영상: ${s.video})` : ''}`);
console.log(`${rest.includes('--dry-run') ? 'dry run: would trash' : 'trashed'} ${rest.includes('--dry-run') ? r.songs.length : r.trashed}`);
break;
}
case 'stats':
console.log(JSON.stringify(catalogStats(db), null, 1));
break;
default:
console.log('usage: cli.ts import-norabose|import-sta|match-youtube|reconfirm-youtube|research-youtube|charts|melon-detail|heatmap|loudness|age-audio|levels|fix-text|stats');
console.log('usage: cli.ts import-norabose|import-sta|match-youtube|reconfirm-youtube|research-youtube|charts|melon-detail|heatmap|loudness|age-audio|levels|fix-text|drop-versions|stats');
process.exitCode = 1;
}
db.close();

View File

@@ -5,6 +5,7 @@
* Paced 5s apart (2s ran into a 429 and then an ended session on 11/03); the cron caps a day at 300 songs.
*/
import type { Database } from 'bun:sqlite';
import { videoVersionKind } from '@mq/shared';
import { Job, sleep } from './catalog';
import { checkEmbed } from './oembed';
import { addsJunk, addsVideo, confirmedDespiteLength, isConfident, namesOtherCut, scoreResult, type Scored } from './score';
@@ -49,9 +50,10 @@ function setAutoVideo(db: Database, id: number, status: 'matched' | 'candidate',
/**
* The actual video (its YouTube title, not the search row) turns out to be a music video, inst., live … — whatever the
* length — or, for a result confirmed despite a length difference, another mix/edit/year: left as 후보.
* videoVersionKind also catches "- Bossa Unplugged", "(Live At …)" written as the video's own version (docs/13).
*/
function isOtherCut(c: Scored, videoTitle: string, songTitle: string): boolean {
if (addsVideo(videoTitle, songTitle) || addsJunk(videoTitle, songTitle)) return true;
if (addsVideo(videoTitle, songTitle) || addsJunk(videoTitle, songTitle) || videoVersionKind(videoTitle, songTitle)) return true;
return confirmedDespiteLength(c) && namesOtherCut(videoTitle, songTitle);
}

View File

@@ -6,7 +6,8 @@ import { openDb } from '../db';
import { tempDbPath } from '../test-utils';
import { Catalog } from './catalog';
import { parseMelon, saveChart } from './charts';
import { decodeEntities, fixEntities } from './text';
import { decodeEntities, dropVersions, fixEntities } from './text';
import { matchYoutube } from './match-youtube';
test('entities: hex, decimal and named, one pass, unknown ones kept', () => {
expect(decodeEntities('Somebody&#x27;s Watching Me')).toBe("Somebody's Watching Me");
@@ -66,3 +67,69 @@ test('fix-text repairs saved songs, chart rows and artists, retries 원곡 찾
]);
expect(fixEntities(db)).toMatchObject({ songs: 0, retry: 0, artists: 0, chartRows: 0 });
});
test('drop-versions: remix/live/inst. songs and songs linked to such a video go to the trash, kept ids and originals stay', () => {
const db = openDb(tempDbPath());
const add = (title: string, artist: string, status = 'matched', video: string | null = title) =>
Number(
db
.query('INSERT INTO songs (title, artist, match_key, youtube_status, youtube_title, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 0, 0)')
.run(title, artist, songMatchKey(title, artist), status, video).lastInsertRowid,
);
const remix = add('Macarena (Bayside Boys Remix)', 'Los Del Rio');
const siren = add('사이렌 Remix', '호미들', 'matched', 'Siren Remix (Feat. UNEDUCATED KID)');
const live = add('Signs (Live At The Trocadero / 1990)', 'Tesla');
const inst = add('아침(Inst.)', '김민기', 'none', null);
const liveVideo = add('바다 이야기', '윤종신', 'matched', 'Over See (Live) (바다 이야기)');
const mrVideo = add('달콤한 빈말', '백아연', 'matched', '달콤한 빈말 (Feat. 바버렛츠) (MR)');
const opus = add('Live Is Life (Digitally Remastered) (Single Ver.)', 'Opus', 'matched', 'Live Is Life (Digitally Remastered) [Live] (Single Version)');
const candidate = add('그대 내품에', '박정운', 'candidate', '그대 내품에 (Live) (그대 내품에)');
const originals = ['Live Wire', 'How Do I Live', '미스터 (Mr.)', 'Radio Ga Ga (Remastered 2011)'].map((t) => add(t, '가수'));
const karaoke = add('노래방에서', '장범준', 'matched', 'karaoke (노래방에서)');
const dry = dropVersions(db, { dryRun: true, keep: [siren, opus] });
expect(dry.trashed).toBe(0);
expect(dry.songs.map((s) => [s.id, s.why, s.kind])).toEqual([
[remix, 'title', 'remix'],
[live, 'title', 'live'],
[inst, 'title', 'inst'],
[liveVideo, 'video', 'live'],
[mrVideo, 'video', 'inst'],
]);
expect(db.query<{ n: number }, []>('SELECT COUNT(*) n FROM songs WHERE deleted_at IS NOT NULL').get()!.n).toBe(0);
expect(dropVersions(db, { keep: [siren, opus] }).trashed).toBe(5);
const alive = db.query<{ id: number }, []>('SELECT id FROM songs WHERE deleted_at IS NULL ORDER BY id').all().map((r) => r.id);
expect(alive).toEqual([siren, opus, candidate, ...originals, karaoke]);
});
test('charts never add a remix / live / inst. as a new song', () => {
const db = openDb(tempDbPath());
const r = saveChart(db, { source: 'melon', chart: 'realtime', period: '2026-11-04', create: 'kpop' }, [
{ rank: 1, ref: '101', title: '거북선 Remix', artists: [{ name: '팔로알토' }] },
{ rank: 2, ref: '102', title: 'Fields Of Gold (Live At Villa Il Palagio, Italy/2001)', artists: [{ name: 'Sting' }] },
{ rank: 3, ref: '103', title: 'Live Wire', artists: [{ name: '서태지' }] },
]);
expect(r).toEqual({ created: 1, linked: 1, rows: 3 });
expect(db.query<{ title: string }, []>('SELECT title FROM songs').all().map((x) => x.title)).toEqual(['Live Wire']);
});
test('원곡 찾기 never links a video whose own title says Live / MR / Unplugged (2026-11-04 prod cases)', async () => {
const db = openDb(tempDbPath());
const c = new Catalog(db);
const songs = [
['바다 이야기', '윤종신', 'Over See (Live) (바다 이야기)'],
['달콤한 빈말', '백아연', '달콤한 빈말 (Feat. 바버렛츠) (MR)'],
['Only When I Sleep', '이은주', 'Only When I Sleep - Bossa Unplugged'],
] as const;
const titles: Record<string, string> = {};
const results: Record<string, { videoId: string; title: string; artists: string; album: null; durationSec: number }[]> = {};
songs.forEach(([title, artist, video], i) => {
c.upsert({ title, artists: [{ name: artist }], durationSec: 240, source: 't', ref: String(i) });
const id = `vid${i}`.padEnd(11, '0');
titles[id] = video;
results[`${artist} ${title}`] = [{ videoId: id, title, artists: artist, album: null, durationSec: 240 }];
});
const stats = await matchYoutube(db, { searchSongs: async (q) => results[q] ?? [] }, { delayMs: 0 }, async (id) => ({ state: 'ok', author: 'x - Topic', title: titles[id]! }));
expect(stats.matched).toBe(0);
expect(db.query<{ n: number }, []>("SELECT COUNT(*) n FROM songs WHERE youtube_status = 'matched'").get()!.n).toBe(0);
});

View File

@@ -1,7 +1,7 @@
/** HTML entities in collected song text (`Somebody&#x27;s`, `Salty &amp; Sweet`): decoding and the one-off DB repair. */
import type { Database } from 'bun:sqlite';
import { songMatchKey } from '@mq/shared';
import { mergeSongs } from '../songs/admin-ops';
import { songMatchKey, versionKind, videoVersionKind, type VersionKind } from '@mq/shared';
import { mergeSongs, trashSongs } from '../songs/admin-ops';
const NAMED: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' };
@@ -67,3 +67,30 @@ export function fixEntities(db: Database, now = Date.now()) {
return out;
})();
}
/**
* 원곡이 아닌 곡 지우기 (2026-11-04, docs/13): songs whose title is a remix / live take / instrumental … and played songs
* whose linked video is one while the title is not ("바다 이야기" → "Over See (Live)"). They go to the 휴지통 (30 days,
* 관리자 → 곡 → 휴지통에서 되살리기). `keep` = ids an admin chose to keep (사이렌 Remix).
*/
export function dropVersions(db: Database, opts: { dryRun?: boolean; keep?: number[] } = {}, now = Date.now()) {
const keep = new Set(opts.keep ?? []);
const out: { id: number; title: string; artist: string; why: 'title' | 'video'; kind: VersionKind; video: string | null }[] = [];
const rows = db
.query<{ id: number; title: string; artist: string; youtube_status: string; youtube_title: string | null }, []>(
'SELECT id, title, artist, youtube_status, youtube_title FROM songs WHERE deleted_at IS NULL ORDER BY id',
)
.all();
for (const r of rows) {
if (keep.has(r.id)) continue;
const t = versionKind(r.title);
if (t) {
out.push({ id: r.id, title: r.title, artist: r.artist, why: 'title', kind: t, video: r.youtube_title });
continue;
}
const v = r.youtube_status === 'matched' && r.youtube_title ? videoVersionKind(r.youtube_title, r.title) : null;
if (v) out.push({ id: r.id, title: r.title, artist: r.artist, why: 'video', kind: v, video: r.youtube_title });
}
const trashed = opts.dryRun ? 0 : trashSongs(db, out.map((x) => x.id), now);
return { trashed, songs: out };
}