원곡이 아닌 곡 정리 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

@@ -0,0 +1,192 @@
/**
* 제목 정리 (docs/13): the title people see has no brackets, no feat. and no version marks
* ("Radio Ga Ga (Remastered 2011)" → "Radio Ga Ga", "Seven (feat. Latto) - Clean Ver." → "Seven").
* What was inside a bracket that is another name of the song ("사랑을 했다(LOVE SCENARIO)") is kept as an answer alias.
* Artist names are left alone ("(여자)아이들", "LE SSERAFIM (르세라핌)").
*/
const PAIRS: Record<string, string> = { '(': ')', '[': ']', '{': '}', '【': '】', '「': '」', '『': '』', '(': ')', '[': ']', '〈': '〉', '《': '》' };
const CLOSERS = new Set(Object.values(PAIRS));
/** A bracket starting with one of these is a note about the recording or the credits, not a name. */
const TAIL_START =
/^(?:feat\.?|ft\.?|featuring|prod\.?|produced|with|from|duet|narr\.?|원곡|inst\.?|instrumental|remaster(?:ed)?|digitally|bonus|explicit|clean|dirty|sped\s*up|slowed|live|ver\.?|version|mr|radio|single|album|lp|mono|stereo|extended|original|acoustic|unplugged|stripped|remix|edit|demo|cover|theme|taken\s+from|soundtrack|re-?recorded|revised|english|korean|japanese|chinese|cf\b|(?:19|20)\d{2}\b)/i;
/** …or ending with one of these. */
const TAIL_END =
/(?:\bver\.?|\bversion|\bremix(?:ed)?|\bmix|\bedit|\bost|\bsoundtrack|\bremaster(?:ed)?|\blive|\bedition|\bcut|\bmr|\binst\.?|\binstrumental|\btheme|\bsolo|\bcf|버전|리믹스|라이브|반주|주제가|삽입곡|가창곡|리메이크곡|배경음악|추천곡|광고|오프닝곡?|엔딩곡?|ost|편)\s*$/i;
/** …or containing one of these anywhere ("Track Masters Remix Featuring …", "드라마 '도깨비' OST Part.1", "여름날 우리 X 로이킴"). */
const TAIL_ANY =
/\bremix(?:ed)?\b|\bfeat(?:uring)?\b|\bft\.|\bprod\.|\bost\b|\bremaster|\bunplugged\b|\bsoundtrack\b|\btheme\s+from\b|\sX\s|원곡|리믹스|라이브|반주|버전|ver\.|삽입곡|주제가|광고|드라마|웹툰|영화|애니메이션|무한도전|\bopening\b|\bending\b/i;
/** A bracket that numbers the song stays as words: "Love The Way You Lie (Part II)" → "… Part II". */
const NUMBERING = /^(?:part|pt\.?|vol\.?|no\.?|chapter|ep\.?|season)\s*(?:\d+|[ivx]+|one|two|three|four|five)\.?$/i;
/** The inside of a bracket (or a ` - ` suffix) is a note, not another name of the song. */
export function isTitleNote(inner: string): boolean {
const t = inner.trim();
if (!t) return true;
return TAIL_START.test(t) || TAIL_END.test(t) || TAIL_ANY.test(t) || /^(?:19|20)\d{2}$/.test(t);
}
/** feat./ft./Featuring/Prod. written after the title without brackets: everything from there on is credits. */
const BARE_CREDITS = /\s+(?:feat\.?|ft\.|featuring|prod\.|prod\s+by)\s.*$/i;
/**
* A version mark written after the title without brackets: "거북선 Remix", "깡 Official Remix", "S&M Remix", "… Clean Ver.",
* "… Inst.". A bare "Live"/"Acoustic" at the end is part of the name ("How Do I Live").
*/
const BARE_VERSION = /\s+(?:(?:official|original|korean|english|japanese|radio|club|extended)\s+)?remix\s*$|\s+(?:\S+\s+)?ver\.\s*$|\s+inst\.\s*$/i;
/** ` - Clean Ver.`, ` - Remastered 2011`. */
const DASH_SUFFIX = /\s+[-–—]\s+([^-–—]+)$/;
interface Group {
/** Text inside, nested brackets flattened to their words. */
inner: string;
start: number;
end: number;
}
/** Top-level bracket groups. A bracket glued inside a word ("Time Is [L]over") is not a group. */
function groups(s: string): Group[] {
const out: Group[] = [];
const stack: { ch: string; at: number }[] = [];
for (let i = 0; i < s.length; i++) {
const ch = s[i]!;
if (PAIRS[ch]) stack.push({ ch, at: i });
else if (CLOSERS.has(ch) && stack.length && PAIRS[stack[stack.length - 1]!.ch] === ch) {
const open = stack.pop()!;
if (stack.length) continue;
const glued = /[\p{L}\p{N}]/u.test(s[i + 1] ?? '') && /^[\p{L}\p{N}]{1,3}$/u.test(s.slice(open.at + 1, i));
if (glued) continue;
out.push({ inner: squash(s.slice(open.at + 1, i).replace(/[([{【「『([〈《)\]}】」』)]〉》]/g, ' ')), start: open.at, end: i + 1 });
}
}
return out;
}
export interface CleanTitle {
/** The title to show: no brackets, credits or version marks. Same as the input when nothing had to go. */
title: string;
/** Other names that were in brackets, as answers: each part alone and the whole title read without brackets. */
aliases: string[];
}
const squash = (s: string) => s.replace(/\s+/g, ' ').trim();
const KANA_HAN = /[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u;
const HANGUL = /\p{Script=Hangul}/u;
const hangulName = (s: string) => HANGUL.test(s) && !KANA_HAN.test(s) && !/[A-Za-z]/.test(s);
/** Strips brackets, feat. and version marks from a song title; see the file comment. */
export function cleanTitle(raw: string): CleanTitle {
const src = squash(raw.normalize('NFC'));
let s = src;
const dash = DASH_SUFFIX.exec(s);
if (dash && isTitleNote(dash[1]!) && s.slice(0, dash.index).trim()) s = s.slice(0, dash.index);
const names: string[] = [];
let shown = '';
let whole = '';
let rest = '';
let at = 0;
for (const g of groups(s)) {
const before = s.slice(at, g.start);
shown += before;
whole += before;
rest += before;
at = g.end;
if (isTitleNote(g.inner)) {
shown += ' ';
whole += ' ';
rest += ' ';
} else if (NUMBERING.test(g.inner) || (g.start === 0 && s.slice(g.end).trim())) {
// "(Part II)" names which song; "(I Just) Died In Your Arms" reads as one title
shown += ` ${g.inner} `;
whole += ` ${g.inner} `;
rest += ' ';
if (g.start === 0) names.push('');
} else {
names.push(g.inner);
shown += ' ';
whole += ` ${g.inner} `;
rest += ' ';
}
}
shown += s.slice(at);
whole += s.slice(at);
rest += s.slice(at);
const tidy = (x: string) => {
// an unclosed bracket at the end ("Title (feat. X") is cut off
let t = squash(x.replace(/\s*[([{【「『([〈《][^)\]}】」』)]〉》]*$/, ' ')).replace(BARE_CREDITS, '');
for (let i = 0; i < 2; i++) t = squash(t).replace(BARE_VERSION, '');
return squash(t).replace(/^[\s\-–—:/,·]+|[\s\-–—:/,·]+$/g, '');
};
let title = tidy(shown);
if (!title) return { title: src, aliases: [] };
const aliases = new Set<string>();
const add = (x: string) => {
const t = tidy(x);
if (t && t.toLowerCase() !== title.toLowerCase()) aliases.add(t);
};
for (const n of names) if (n) add(n);
if (names.length) {
add(whole);
add(rest);
}
// 貴方の恋人になりたい (당신의 연인이 되고 싶어): a Japanese title with its Korean name in brackets shows the Korean name
if (KANA_HAN.test(title) && !HANGUL.test(title)) {
const ko = names.find(hangulName);
if (ko) {
aliases.delete(ko);
aliases.add(title);
title = ko;
}
}
return { title, aliases: [...aliases] };
}
export type VersionKind = 'remix' | 'live' | 'inst' | 'acoustic' | 'sped';
const KIND_RULES: [VersionKind, RegExp][] = [
['remix', /\bremix(?:ed)?\b|리믹스/i],
['live', /^\s*live\b|\blive\s*(?:ver\.?|version)?\s*$|\blive\s+(?:at|in|from|on|session|concert|tour)\b|\bunplugged\b|라이브|실황/i],
['inst', /^\s*(?:inst\.?|instrumental|mr|karaoke)\s*$|\binstrumental\b|\binst\.(?=\W|$)|\bkaraoke\b|반주|노래방/i],
['acoustic', /\bacoustic\b|어쿠스틱/i],
['sped', /\bsped\s*up\b|\bslowed\b/i],
];
/**
* The title says the song is not the original recording: a remix, a live take, an instrumental/MR, an acoustic or sped-up
* version. Only marks in brackets, a ` - ` suffix or a bare "… Remix" at the end count ("Live Wire", "How Do I Live",
* "미스터 (Mr.)", "(From "To Live And Die In L.A." Soundtrack)" are originals).
*/
export function versionKind(title: string): VersionKind | null {
const t = squash(title.normalize('NFC'));
const parts = groups(t).map((g) => g.inner);
const dash = DASH_SUFFIX.exec(t);
if (dash) parts.push(dash[1]!);
for (const p of parts) {
if (/^\s*(?:from|taken\s+from)\b/i.test(p)) continue;
for (const [kind, re] of KIND_RULES) if (re.test(p)) return kind;
}
let bare = t;
for (const g of groups(t).reverse()) bare = bare.slice(0, g.start) + ' ' + bare.slice(g.end);
const m = BARE_VERSION.exec(squash(bare));
if (m) {
const w = m[0].toLowerCase();
if (/remix/.test(w)) return 'remix';
if (/inst/.test(w)) return 'inst';
for (const [kind, re] of KIND_RULES) if (re.test(w)) return kind;
}
return null;
}
const looseName = (s: string) => s.normalize('NFKC').toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '');
/**
* The linked video is a remix / live take / instrumental … that the song's own title does not say
* ("Over See (Live) (바다 이야기)" for 바다 이야기). A bracket that is just the song's title is not a mark ("karaoke (노래방에서)").
*/
export function videoVersionKind(videoTitle: string, songTitle: string): VersionKind | null {
if (versionKind(songTitle)) return null;
const own = new Set([looseName(songTitle), looseName(cleanTitle(songTitle).title)]);
let t = squash(videoTitle.normalize('NFC'));
for (const g of groups(t).reverse()) if (own.has(looseName(g.inner))) t = t.slice(0, g.start) + ' ' + t.slice(g.end);
return versionKind(t);
}