정답: 가수가 제목 정답에 섞이던 것·틀린 한글 발음 정답 고치기 (docs 13)
- 퀴즈 편집 화면: '추가 정답' 한 칸을 '제목 정답'·'가수 정답' 두 칸으로
- 괄호 안이 그 곡 가수 이름이면 제목 정답이 아님: cleanTitle(title, artist) — Crank That (Soulja Boy), 레이 (LAY). 정답 생성·플레이리스트·파일 읽기 모두 가수를 넘김
- 재생목록으로 엑셀 만들기: 정답·가수 정답 칸에 제목·가수를 다시 적지 않음(다른 표기만)
- 한글 발음 정답은 검수한 표기표(answers/lexicon.json: 단어 2,299·제목 74·가수 이름 1,111, 띄어 쓴 꼴과 붙여 쓴 꼴)만. 표기표에 없는 단어가 있으면 발음 정답 없이 unknownWords → 새 곡은 '확인 필요'(발음 확인 필요: …), 관리자 → 제목 정리에서 제목/가수 정답을 더해 적용. 규칙 읽기(en-ko.ts)는 후보·옛 정답 찾기에만
- cli redo-readings [--dry-run] [--old-lexicon]: 옛 규칙(이나 이전 표기표)이 만든 발음 정답만 빼고 표기표 표기로 — DB 별칭(source auto)과 일반 퀴즈 정답, 관리자 별칭·직접 쓴 정답·이지선다는 그대로. cli lexicon-missing: 표기표에 없는 단어와 규칙 후보
- 멜론 차트: 재생이 막힌 곡은 제목 칸에 링크가 없어 가수 링크를 제목으로 읽던 것 → 제목 칸만 읽음. cli fix-melon-titles: 제목이 가수 이름인 멜론 곡을 곡 정보 페이지 제목으로(자기 이름 곡은 그대로), 같은 곡이 이미 있으면 합침, 잘못 찾은 후보 영상은 원곡 찾기로
- decodeEntities: é·° 등(Céline Dion)
- 가수 칸의 따옴표 안을 with로 자르지 않음('Miki Matsubara Official "stay with me"' → 가수 정답 '미')
- 테스트: 표기표 읽기(사용자가 짚은 10곡 포함), 확인 필요로 보내기·정답 더해 적용, 발음 정답 바꾸기(DB·퀴즈·이지선다 제외·이전 표기표), 멜론 제목 칸·곡명·fix-melon-titles, 가수 괄호, 엑셀 칸; e2e quiz(재생목록 엑셀 칸)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
/** 정답 자동 생성 (docs/13): 영어 한글 발음, 일본어 읽는 소리, J-POP 한글 이름. */
|
||||
import { expect, test } from 'bun:test';
|
||||
import { arpabetToHangul, englishToHangul } from './en-ko';
|
||||
import { hangulReadings } from './lexicon';
|
||||
import { kanaToHangul, romajiToHangul } from './ja-ko';
|
||||
import { readJapanese } from './ja-reading';
|
||||
import { wikiLookup } from './wiki';
|
||||
@@ -9,7 +10,7 @@ import { openDb } from '../db';
|
||||
import { tempDbPath } from '../test-utils';
|
||||
import { startImport } from '../quizzes/playlist';
|
||||
|
||||
test('영어 → 한글: 외래어 표기 규칙과 흔히 쓰는 표기', () => {
|
||||
test('영어 → 한글 (rule reader: suggestions for the 표기표 and the old answers it replaces): 외래어 표기 규칙', () => {
|
||||
const cases: Record<string, string> = {
|
||||
Pretender: '프리텐더',
|
||||
Lemon: '레몬',
|
||||
@@ -47,7 +48,43 @@ test('영어 → 한글: 외래어 표기 규칙과 흔히 쓰는 표기', () =>
|
||||
expect(arpabetToHangul('M EH1 L AH0 N')).toBe('멜런'); // l between vowels doubles
|
||||
});
|
||||
|
||||
test('영어 → 한글: a word nobody can read leaves the whole title out; Korean/Japanese text is not English', () => {
|
||||
test('한글 표기표: checked spellings only, spaced and joined; a word the table lacks gives no reading', () => {
|
||||
const title = (t: string) => hangulReadings(t).readings[0];
|
||||
const artist = (t: string) => hangulReadings(t, 'artist').readings;
|
||||
// the readings the old rule reader got wrong (2026-11-04 테스트용1)
|
||||
expect(title('Eine Kleine')).toBe('아이네 클라이네');
|
||||
expect(title('Emerald Sword')).toBe('에메랄드 소드');
|
||||
expect(title('Heaven')).toBe('헤븐');
|
||||
expect(title('Outside Castle')).toBe('아웃사이드 캐슬');
|
||||
expect(artist('Jung Kook')).toContain('정국');
|
||||
expect(artist('a-ha')).toContain('아하');
|
||||
expect(artist('Billy Joel')).toEqual(['빌리 조엘', '빌리조엘']);
|
||||
expect(artist('Sabrina Carpenter')[0]).toBe('사브리나 카펜터');
|
||||
expect(artist("GIRLS' GENERATION")).toContain('소녀시대');
|
||||
expect(artist('Ai Higuchi')[0]).toBe('히구치 아이');
|
||||
expect(artist('Miki Matsubara')[0]).toBe('마츠바라 미키');
|
||||
expect(artist('USA For Africa')[0]).toBe('유에스에이 포 아프리카');
|
||||
expect(artist('Rod Stewart')[0]).toBe('로드 스튜어트');
|
||||
// two common spellings of a word: both, one word at a time
|
||||
expect(hangulReadings('Sorry Sorry').readings).toEqual(expect.arrayContaining(['쏘리 쏘리', '소리 쏘리', '쏘리 소리']));
|
||||
expect(title('Thank You')).toBe('땡큐');
|
||||
expect(title('R.O.D.')).toBe('알 오 디');
|
||||
expect(hangulReadings('Heaven Xqzt')).toEqual({ readings: [], unknown: ['xqzt'] });
|
||||
expect(hangulReadings('좋은 날')).toEqual({ readings: [], unknown: [] });
|
||||
});
|
||||
|
||||
test('곡 정답: a title word missing from the 표기표 is listed and gets no reading; quoted words in an artist are not split', async () => {
|
||||
const [a, b] = await songAnswersBatch(null, [
|
||||
{ title: 'Heaven Xqzt', artist: 'Rod Stewart' },
|
||||
{ title: '真夜中のドア〜stay with me', artist: 'Miki Matsubara Official "stay with me"' },
|
||||
]);
|
||||
expect(a!.unknownWords).toEqual(['xqzt']);
|
||||
expect(a!.titleAnswers).toEqual([]);
|
||||
expect(a!.artistAnswers).toContain('로드 스튜어트');
|
||||
expect(b!.artistAnswers).not.toContain('미');
|
||||
});
|
||||
|
||||
test('영어 → 한글 (rule reader, suggestions only): a word nobody can read leaves the whole title out; Korean/Japanese text is not English', () => {
|
||||
expect(englishToHangul('Despacito Xqzt')).toBeNull();
|
||||
expect(englishToHangul('좋은 날')).toBeNull();
|
||||
expect(englishToHangul('夜に駆ける')).toBeNull();
|
||||
@@ -108,8 +145,8 @@ test('곡 정답: cleaned title, other names, 한글 발음; J-POP shown by its
|
||||
{ korean: true, wiki },
|
||||
);
|
||||
// no Korean name and no reading for the artist: shown as is and marked 확인 필요
|
||||
expect(pretender).toEqual({ title: 'Pretender', artist: 'Official髭男dism', titleAnswers: ['프리텐더'], artistAnswers: [], note: '확인 필요' });
|
||||
expect(night).toEqual({ title: '밤을 달리다', artist: 'YOASOBI', titleAnswers: ['夜に駆ける', '요루니 카케루', '요루니 가케루'], artistAnswers: ['요아소비'], note: null });
|
||||
expect(pretender).toEqual({ title: 'Pretender', artist: 'Official髭男dism', titleAnswers: ['프리텐더'], artistAnswers: [], note: '확인 필요', unknownWords: [] });
|
||||
expect(night).toEqual({ title: '밤을 달리다', artist: 'YOASOBI', titleAnswers: ['夜に駆ける', '요루니 카케루', '요루니 가케루'], artistAnswers: ['요아소비'], note: null, unknownWords: [] });
|
||||
// no Korean article: the reading is shown (and said so); the artist's Korean name from Wikipedia
|
||||
expect(flower).toEqual({
|
||||
title: '유키노 하나',
|
||||
@@ -117,8 +154,9 @@ test('곡 정답: cleaned title, other names, 한글 발음; J-POP shown by its
|
||||
titleAnswers: ['雪の華'],
|
||||
artistAnswers: ['米津玄師', '요네츠 겐시', '요네쓰 겐시'],
|
||||
note: '한글 이름 자동 변환',
|
||||
unknownWords: [],
|
||||
});
|
||||
expect(plain).toEqual({ title: '좋은 날', artist: '아이유', titleAnswers: [], artistAnswers: [], note: null });
|
||||
expect(plain).toEqual({ title: '좋은 날', artist: '아이유', titleAnswers: [], artistAnswers: [], note: null, unknownWords: [] });
|
||||
// without `korean` (the file fill): the names stay, the answers are the same kind
|
||||
const [asIs] = await songAnswersBatch(null, [{ title: '夜に駆ける', artist: 'YOASOBI' }]);
|
||||
expect(asIs).toMatchObject({ title: '夜に駆ける', titleAnswers: ['요루니 카케루', '요루니 가케루'] });
|
||||
@@ -164,7 +202,7 @@ test('플레이리스트 가져오기: the answers come from the title as found
|
||||
if (typeof job === 'string') throw new Error(job);
|
||||
for (let i = 0; i < 200 && job.status === 'running'; i++) await Bun.sleep(20);
|
||||
expect(job.status).toBe('done');
|
||||
expect(job.rows[0]).toMatchObject({ title: '사랑을 했다', titleAnswers: ['LOVE SCENARIO', '사랑을 했다 LOVE SCENARIO', '러브 시나리오'] });
|
||||
expect(job.rows[0]).toMatchObject({ title: '사랑을 했다', titleAnswers: ['LOVE SCENARIO', '사랑을 했다 LOVE SCENARIO', '러브 시나리오', '러브시나리오'] });
|
||||
expect(job.rows[1]!.title).toBe('밤을 달리다');
|
||||
expect(job.rows[1]!.titleAnswers).toEqual(expect.arrayContaining(['夜に駆ける', '요루니 카케루', '요루니 가케루']));
|
||||
});
|
||||
|
||||
@@ -2,13 +2,15 @@
|
||||
* 정답 자동 생성 (docs/13): for a song's title and artist, the answers people may type besides the names shown.
|
||||
* - the title without brackets / feat. / version marks (cleanTitle) and the other names that were in brackets
|
||||
* - the aliases the server DB already has for that song and its artists
|
||||
* - 영어 → 한글 발음 (Pretender → 프리텐더), 일본어 → 원어 + 읽는 소리 두 가지 (夜に駆ける → 요루니 가케루 / 요루니 카케루)
|
||||
* - 로마자 → 검수한 한글 표기 (lexicon.ts: Pretender → 프리텐더, Rod Stewart → 로드 스튜어트); a word the table lacks leaves that
|
||||
* text without a reading and is listed in `unknownWords` (the DB cleanup sends the song to '확인 필요')
|
||||
* - 일본어 → 원어 + 읽는 소리 두 가지 (夜に駆ける → 요루니 가케루 / 요루니 카케루)
|
||||
* With `korean`, a Japanese title/artist is shown by its Korean name: 위키백과 한국어 문서 이름 → 괄호 안 한글 제목 →
|
||||
* 읽는 소리 (note '한글 이름 자동 변환'); nothing found → note '확인 필요'. The names shown always count on their own.
|
||||
*/
|
||||
import type { Database } from 'bun:sqlite';
|
||||
import { cleanTitle } from '@mq/shared';
|
||||
import { englishToHangul } from './en-ko';
|
||||
import { hangulReadings, knownArtist } from './lexicon';
|
||||
import { kanaToHangul } from './ja-ko';
|
||||
import { hasJapanese, japaneseName, readJapanese, type JaReader } from './ja-reading';
|
||||
import type { WikiLookup } from './wiki';
|
||||
@@ -22,6 +24,8 @@ export interface SongAnswers {
|
||||
artistAnswers: string[];
|
||||
/** '한글 이름 자동 변환' / '확인 필요' for a Japanese name shown in Korean, else null. */
|
||||
note: string | null;
|
||||
/** Words of the title or the artist missing from the 한글 표기표: those got no Hangul reading. */
|
||||
unknownWords: string[];
|
||||
}
|
||||
|
||||
export interface AnswerOptions {
|
||||
@@ -59,13 +63,21 @@ export function dbAliases(db: Database, songId: number): { title: string[]; arti
|
||||
};
|
||||
}
|
||||
|
||||
/** The names in an artist credit ("A, B & C"); the whole credit too. */
|
||||
const artistNames = (a: string) => [...new Set([a, ...a.split(/\s*(?:,|&|\/|·|\sx\s|\bfeat\.?\s|\bwith\s)\s*/i)].map((x) => x.trim()).filter(Boolean))];
|
||||
/**
|
||||
* The names in an artist credit ("A, B & C"); the whole credit too. Quoted words are never split
|
||||
* (Miki Matsubara Official "stay with me" is not "… stay" and "me").
|
||||
*/
|
||||
const artistNames = (a: string) => {
|
||||
const quoted: string[] = [];
|
||||
const masked = a.replace(/"[^"]*"|“[^”]*”|「[^」]*」/g, (m) => `\u0000${quoted.push(m) - 1}\u0000`);
|
||||
const parts = masked.split(/\s*(?:,|&|\/|·|\sx\s|\bfeat\.?\s|\bwith\s)\s*/i).map((x) => x.replace(/\u0000(\d+)\u0000/g, (_, i: string) => quoted[Number(i)]!));
|
||||
return [...new Set([a, ...parts].map((x) => x.trim()).filter(Boolean))];
|
||||
};
|
||||
|
||||
/** Answers for many songs at once (one Japanese reading process, one Wikipedia request per 50 names). */
|
||||
export async function songAnswersBatch(db: Database | null, songs: { title: string; artist: string; songId?: number | null }[], opts: AnswerOptions = {}): Promise<SongAnswers[]> {
|
||||
const read = opts.read ?? readJapanese;
|
||||
const clean = songs.map((s) => cleanTitle(s.title));
|
||||
const clean = songs.map((s) => cleanTitle(s.title, s.artist));
|
||||
// every Japanese text whose reading we want: titles, their bracket names, artist names
|
||||
const jaTexts = new Set<string>();
|
||||
songs.forEach((s, i) => {
|
||||
@@ -88,9 +100,9 @@ export async function songAnswersBatch(db: Database | null, songs: { title: stri
|
||||
return r ? [r.common, r.rule] : [];
|
||||
}
|
||||
if (HANGUL.test(t)) return [];
|
||||
const e = englishToHangul(t);
|
||||
return e ? [e] : [];
|
||||
return hangulReadings(t).readings;
|
||||
};
|
||||
const sayArtist = (t: string): string[] => (hasJapanese(t) || HANGUL.test(t) ? say(t) : hangulReadings(t, 'artist').readings);
|
||||
return songs.map((s, i) => {
|
||||
const c = clean[i]!;
|
||||
const fromDb = db && s.songId ? dbAliases(db, s.songId) : { title: [], artist: [] };
|
||||
@@ -124,10 +136,13 @@ export async function songAnswersBatch(db: Database | null, songs: { title: stri
|
||||
if (opts.korean && hasJapanese(artist)) artist = korean(artist, undefined, extraArtist);
|
||||
const titleAnswers = uniq([...c.aliases, ...extraTitle, ...fromDb.title, ...[c.title, ...c.aliases, ...extraTitle, ...fromDb.title].flatMap(say)], [title]);
|
||||
const names = artistNames(s.artist);
|
||||
const artistAnswers = uniq([...extraArtist, ...fromDb.artist, ...names.flatMap(say), ...fromDb.artist.flatMap(say)], [artist, s.artist === artist ? '' : s.artist].filter(Boolean));
|
||||
const artistAnswers = uniq([...extraArtist, ...fromDb.artist, ...names.flatMap(sayArtist), ...fromDb.artist.flatMap(sayArtist)], [artist, s.artist === artist ? '' : s.artist].filter(Boolean));
|
||||
// the artist as written stays an answer when it was replaced by its Korean name
|
||||
if (artist !== s.artist && !artistAnswers.includes(s.artist)) artistAnswers.unshift(s.artist);
|
||||
return { title, artist, titleAnswers, artistAnswers: artistAnswers.slice(0, MAX), note: notes.length ? [...new Set(notes)].join(' · ') : null };
|
||||
// the title and each artist name: a word the 표기표 lacks (a credit the table knows whole, "Hootie & The Blowfish", is one name)
|
||||
const credit = knownArtist(s.artist) || names.length === 1 ? [] : names.slice(1);
|
||||
const unknownWords = [...new Set([...hangulReadings(c.title).unknown, ...(names.length === 1 ? [s.artist] : credit).flatMap((t) => hangulReadings(t, 'artist').unknown)])];
|
||||
return { title, artist, titleAnswers, artistAnswers: artistAnswers.slice(0, MAX), note: notes.length ? [...new Set(notes)].join(' · ') : null, unknownWords };
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
3486
apps/server/src/answers/lexicon.json
Normal file
3486
apps/server/src/answers/lexicon.json
Normal file
File diff suppressed because it is too large
Load Diff
75
apps/server/src/answers/lexicon.ts
Normal file
75
apps/server/src/answers/lexicon.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* 한글 발음 표기표 (docs/13): 로마자 제목·가수 이름 → 한국에서 흔히 쓰는 한글 표기. Only checked spellings become answers.
|
||||
* - artists: a whole artist name ("Rod Stewart" → 로드 스튜어트, "GIRLS' GENERATION" → 소녀시대, "Ai Higuchi" → 히구치 아이)
|
||||
* - titles: a whole title read differently from its words ("Thnks fr th Mmrs" → 땡스포더메모리즈, "La Vie en Rose" → 라비앙로즈)
|
||||
* - words: one word as said in song titles ("heaven" → 헤븐, "summer" → 썸머 / 서머)
|
||||
* A text with a word the table does not know gets no reading at all (`unknown` lists those words): a guessed spelling is
|
||||
* never an answer. The rule reading in en-ko.ts only suggests spellings for the next table update (cli lexicon-missing).
|
||||
*/
|
||||
import table from './lexicon.json';
|
||||
|
||||
export type LexiconTable = Record<'words' | 'titles' | 'artists', Record<string, string[]>>;
|
||||
const TABLE = table as LexiconTable;
|
||||
const { artists: ARTISTS } = TABLE;
|
||||
|
||||
/** Key of a whole name: letters and digits only ("a-ha" = "A Ha" = "aha", "P.M. Dawn" = "pmdawn"; & = and). */
|
||||
export const nameKey = (s: string) => s.normalize('NFKC').toLowerCase().replace(/&/g, 'and').replace(/[^\p{L}\p{N}]+/gu, '');
|
||||
/** Whether the table has this artist name as a whole. */
|
||||
export const knownArtist = (s: string) => !!ARTISTS[nameKey(s)];
|
||||
|
||||
/** The words of a title, as the table keys them ("Can’t" → can't, "R&B" → r and b). */
|
||||
export function lexWords(text: string): string[] {
|
||||
return text
|
||||
.normalize('NFKC')
|
||||
.replace(/&/g, ' and ')
|
||||
.split(/[\s\-_/,.!?~:;()"[\]{}]+/)
|
||||
.map((w) =>
|
||||
w
|
||||
.replace(/[’‘`]/g, "'")
|
||||
.replace(/^[^A-Za-z0-9]+|[^A-Za-z0-9']+$/g, '')
|
||||
.toLowerCase(),
|
||||
)
|
||||
.filter((w) => /[a-z0-9]/.test(w));
|
||||
}
|
||||
|
||||
const LETTER: Record<string, string> = {
|
||||
a: '에이', b: '비', c: '씨', d: '디', e: '이', f: '에프', g: '지', h: '에이치', i: '아이', j: '제이', k: '케이', l: '엘', m: '엠',
|
||||
n: '엔', o: '오', p: '피', q: '큐', r: '알', s: '에스', t: '티', u: '유', v: '브이', w: '더블유', x: '엑스', y: '와이', z: '제트',
|
||||
};
|
||||
|
||||
const isLatinText = (t: string) => /[A-Za-z]/.test(t) && !/[\p{Script=Hangul}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u.test(t);
|
||||
const MAX_READINGS = 4;
|
||||
|
||||
/** Spacing counts in the default answer check: each spelling also without its spaces (로드 스튜어트 / 로드스튜어트). */
|
||||
const withJoined = (list: string[]) => [...new Set(list.flatMap((r) => (/\s/.test(r) ? [r, r.replace(/\s+/g, '')] : [r])))];
|
||||
|
||||
/**
|
||||
* Hangul readings of a Latin-letter title or name: the table's whole-name spellings, else word by word (the first spelling
|
||||
* of each word, then one other spelling at a time). `unknown`: words missing from the table (then no readings).
|
||||
*/
|
||||
export function hangulReadings(text: string, kind: 'title' | 'artist' = 'title', t: LexiconTable = TABLE): { readings: string[]; unknown: string[] } {
|
||||
if (!isLatinText(text)) return { readings: [], unknown: [] };
|
||||
const WORDS = t.words;
|
||||
const whole = (kind === 'artist' ? t.artists : t.titles)[nameKey(text)];
|
||||
if (whole) return { readings: withJoined(whole), unknown: [] };
|
||||
const raw = text.normalize('NFKC').replace(/\bthank\s+(?:you|u)\b/gi, 'thankyou');
|
||||
// "R.O.D.", "I.O.U": letters said by name
|
||||
if (/^\s*(?:[A-Za-z]\.){2,}[A-Za-z]?\.?\s*$/.test(raw)) return { readings: withJoined([[...raw.replace(/[^A-Za-z]/g, '').toLowerCase()].map((c) => LETTER[c]).join(' ')]), unknown: [] };
|
||||
const parts: string[][] = [];
|
||||
const unknown: string[] = [];
|
||||
for (const w of lexWords(raw)) {
|
||||
if (/^\d+$/.test(w)) parts.push([w]);
|
||||
else if (WORDS[w]?.length) parts.push(WORDS[w]!);
|
||||
else unknown.push(w);
|
||||
}
|
||||
if (unknown.length || !parts.length) return { readings: [], unknown: [...new Set(unknown)] };
|
||||
const first = parts.map((p) => p[0]!);
|
||||
const out = [first.join(' ')];
|
||||
parts.forEach((p, i) => {
|
||||
for (const alt of p.slice(1)) {
|
||||
if (out.length >= MAX_READINGS) return;
|
||||
out.push(first.map((x, k) => (k === i ? alt : x)).join(' '));
|
||||
}
|
||||
});
|
||||
return { readings: withJoined(out), unknown: [] };
|
||||
}
|
||||
@@ -4,7 +4,7 @@ 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 { fixMelonTitles, parseBugs, parseGenie, parseMelon, parseMelonDetail, parseMelonSongName, parseTj, saveChart } from './charts';
|
||||
import { collectHeatmaps, parseHeatmap, pickHighlight } from './heatmap';
|
||||
import { computeLevels, levelsByShare, LEVEL_CUTS, popularity } from './levels';
|
||||
|
||||
@@ -17,6 +17,17 @@ describe('chart parsers (saved pages, 2026-10-18)', () => {
|
||||
expect(rows[0]).toEqual({ rank: 1, ref: '711627', title: '죄와벌', artists: [{ ref: '108363', name: 'SG 워너비' }] });
|
||||
expect(rows[1]).toMatchObject({ rank: 2, title: '겁쟁이', artists: [{ name: '버즈' }] });
|
||||
});
|
||||
test('멜론: 재생이 막혀 제목에 링크가 없는 곡은 가수 링크를 제목으로 읽지 않음 (Sheep, 레이 (LAY))', () => {
|
||||
const html = `<tr class="lst50" data-song-no="31278454"><td><span class="rank top">93</span></td>
|
||||
<input type="checkbox" title="Sheep (Alan Walker Relift) 곡 선택" disabled="disabled" class="input_check" name="input_check" value="31278454" />
|
||||
<div class="wrap_song_info"><div class="ellipsis rank01"><span>
|
||||
<span class="fc_lgray"><div class="ellipsis" style="max-width:200px">Sheep (Alan Walker Relift)</div></span>
|
||||
</span></div><br />
|
||||
<div><div class="ellipsis rank02"><a href="/artist/detail.htm?artistId=715178" title="레이 (LAY) - 페이지 이동">레이 (LAY)</a>, <a href="/artist/detail.htm?artistId=943471" title="Alan Walker - 페이지 이동">Alan Walker</a><span class="checkEllipsis" style="display:none"></span></div></div></div></tr>`;
|
||||
expect(parseMelon(html)).toEqual([
|
||||
{ rank: 93, ref: '31278454', title: 'Sheep (Alan Walker Relift)', artists: [{ ref: '715178', name: '레이 (LAY)' }, { ref: '943471', name: 'Alan Walker' }] },
|
||||
]);
|
||||
});
|
||||
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' }] });
|
||||
@@ -27,6 +38,42 @@ describe('chart parsers (saved pages, 2026-10-18)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('songs saved with the singer as the title (2026-11-04)', () => {
|
||||
test('멜론 곡 페이지의 곡명', () => {
|
||||
expect(parseMelonSongName('<div class="song_name">\n<strong class="none">곡명</strong>\n\t\tLivin' My Love (개그콘서트)\n</div>')).toBe("Livin' My Love (개그콘서트)");
|
||||
expect(parseMelonSongName('<div class="song_name"><strong class="none">곡명</strong><span class="bullet_icons age_19">19금</span>Your Song</div>')).toBe('Your Song');
|
||||
});
|
||||
test('fixed from the Melon song page; self-titled songs stay; a song we already have is merged into it', async () => {
|
||||
const db = openDb(tempDbPath());
|
||||
const c = new Catalog(db);
|
||||
const song = (title: string, artist: string, melonId: number) => c.upsert({ melonId, title, artists: [{ name: artist }], source: 'melon-chart', ref: String(melonId) })[0]!;
|
||||
const rod = song('Rod Stewart', 'Rod Stewart', 1);
|
||||
const snsd = song('소녀시대', '소녀시대', 2);
|
||||
const chuckie = song('Chuckie', 'Chuckie', 3);
|
||||
const noise = song('Make Some Noise', 'Chuckie', 4);
|
||||
const plain = song('Your Song', 'Elton John', 5);
|
||||
db.query("UPDATE songs SET youtube_id = 'wrongguess1', youtube_status = 'candidate' WHERE id = ?").run(rod);
|
||||
db.query("INSERT INTO song_aliases (song_id, part, alias, source) VALUES (?, 'title', '로드 스투어트', 'auto')").run(rod);
|
||||
const names: Record<number, string> = { 1: 'Your Song', 2: "소녀시대 (Girls' Generation)", 3: 'Make Some Noise (Original Mix)', 5: 'never asked' };
|
||||
const asked: number[] = [];
|
||||
const fetchName = async (id: number) => (asked.push(id), names[id] ?? null);
|
||||
expect((await fixMelonTitles(db, { dryRun: true, delayMs: 0, fetchName })).map((f) => f.id)).toEqual([rod, chuckie]);
|
||||
expect(asked).toEqual([1, 2, 3]);
|
||||
const fixed = await fixMelonTitles(db, { delayMs: 0, fetchName });
|
||||
expect(fixed.map((f) => [f.id, f.to, f.mergedInto])).toEqual([
|
||||
[rod, 'Your Song', null],
|
||||
[chuckie, 'Make Some Noise (Original Mix)', noise],
|
||||
]);
|
||||
const row = (id: number) => db.query<{ title: string; youtube_id: string | null; youtube_status: string; deleted_at: number | null }, [number]>('SELECT title, youtube_id, youtube_status, deleted_at FROM songs WHERE id = ?').get(id)!;
|
||||
expect(row(rod)).toMatchObject({ title: 'Your Song', youtube_id: null, youtube_status: 'none', deleted_at: null });
|
||||
expect(db.query('SELECT COUNT(*) n FROM song_aliases WHERE song_id = ?').get(rod)).toEqual({ n: 0 });
|
||||
expect(row(snsd).title).toBe('소녀시대');
|
||||
expect(row(chuckie).deleted_at).not.toBeNull();
|
||||
expect(row(noise).deleted_at).toBeNull();
|
||||
expect(row(plain).title).toBe('Your Song');
|
||||
});
|
||||
});
|
||||
|
||||
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());
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
* 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, versionKind } from '@mq/shared';
|
||||
import { cleanTitle, creditKeys, looseKey, songMatchKey, versionKind } from '@mq/shared';
|
||||
import { mergeSongs } from '../songs/admin-ops';
|
||||
import { Catalog, Job, sleep } from './catalog';
|
||||
import { decodeEntities } from './text';
|
||||
|
||||
@@ -29,7 +30,9 @@ export function parseMelon(html: string): 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];
|
||||
// a song that can't be played has no link in its title: read the title cell alone, never the artist links after it
|
||||
const cell = /class="ellipsis rank01">([\s\S]*?)class="ellipsis rank02"/.exec(block)?.[1] ?? '';
|
||||
const title = /<a [^>]*>([\s\S]*?)<\/a>/.exec(cell)?.[1] ?? cell.replace(/<\/div>\s*<br\s*\/?>[\s\S]*$/, '');
|
||||
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;
|
||||
@@ -317,3 +320,57 @@ export async function fillMelonDetails(db: Database, opts: { limit?: number; del
|
||||
}
|
||||
return stats;
|
||||
}
|
||||
|
||||
/** The song name on a Melon song page ("곡명"). */
|
||||
export function parseMelonSongName(html: string): string | null {
|
||||
const cell = /<div class="song_name">([\s\S]*?)<\/div>/.exec(html)?.[1];
|
||||
if (!cell) return null;
|
||||
return decode(cell.replace(/<strong[^>]*>[\s\S]*?<\/strong>/g, '').replace(/<span[^>]*>[\s\S]*?<\/span>/g, '')) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Songs saved with their singer's name as the title (2026-11-04): a Melon chart row of a song that could not be played has no
|
||||
* link in its title cell, and the old parser read the artist link after it ("Rod Stewart" for Your Song). For every Melon
|
||||
* song whose title is one of its artists' names, the Melon song page says the real name; self-titled songs (소녀시대) stay.
|
||||
* Fixed songs get the Melon name and a new match key, lose their generated answers and their 제목 정리 row (clean-titles makes
|
||||
* them again) and, when the video was only a guess from the wrong title, go back to 원곡 찾기. When another song already is that
|
||||
* song (same match key: Chuckie → Make Some Noise), the wrong one is merged into it (휴지통, 관리자 → 중복 합치기 the same way).
|
||||
*/
|
||||
export async function fixMelonTitles(
|
||||
db: Database,
|
||||
opts: { dryRun?: boolean; delayMs?: number; fetchName?: (melonId: number) => Promise<string | null>; now?: number } = {},
|
||||
): Promise<{ id: number; melonId: number; from: string; to: string; artist: string; video: string | null; mergedInto: number | null }[]> {
|
||||
const fetchName = opts.fetchName ?? (async (id: number) => parseMelonSongName(await get(`https://www.melon.com/song/detail.htm?songId=${id}`)));
|
||||
const now = opts.now ?? Date.now();
|
||||
const rows = db
|
||||
.query<{ id: number; melon_id: number; title: string; artist: string; youtube_status: string; youtube_source: string | null; youtube_id: string | null }, []>(
|
||||
'SELECT id, melon_id, title, artist, youtube_status, youtube_source, youtube_id FROM songs WHERE deleted_at IS NULL AND melon_id IS NOT NULL ORDER BY id',
|
||||
)
|
||||
.all()
|
||||
.filter((s) => creditKeys(s.artist).has(looseKey(s.title)));
|
||||
const out: Awaited<ReturnType<typeof fixMelonTitles>> = [];
|
||||
for (const [i, s] of rows.entries()) {
|
||||
if (i) await sleep(opts.delayMs ?? 1500);
|
||||
const name = await fetchName(s.melon_id);
|
||||
// self-titled songs: "소녀시대 (Girls' Generation)", "이로한 (Feat. ELO, Jessi)"
|
||||
if (!name || looseKey(cleanTitle(name, s.artist).title) === looseKey(s.title)) continue;
|
||||
const key = songMatchKey(name, s.artist);
|
||||
const guessVideo = s.youtube_source !== 'admin' && (s.youtube_status === 'none' || s.youtube_status === 'candidate');
|
||||
const sameKey = db.query<{ id: number }, [string, number]>('SELECT id FROM songs WHERE match_key = ? AND id <> ? AND deleted_at IS NULL').all(key, s.id).map((r) => r.id);
|
||||
out.push({ id: s.id, melonId: s.melon_id, from: s.title, to: name, artist: s.artist, video: s.youtube_id, mergedInto: sameKey[0] ?? null });
|
||||
if (opts.dryRun) continue;
|
||||
db.transaction(() => {
|
||||
db.query('UPDATE songs SET title = ?, match_key = ?, updated_at = ? WHERE id = ?').run(name, key, now, s.id);
|
||||
db.query("DELETE FROM song_aliases WHERE song_id = ? AND source = 'auto'").run(s.id);
|
||||
db.query('DELETE FROM title_reviews WHERE song_id = ?').run(s.id);
|
||||
db.query("UPDATE chart_entries SET raw_title = ? WHERE source = 'melon' AND raw_ref = ? AND raw_title = ?").run(name, String(s.melon_id), s.title);
|
||||
if (guessVideo) {
|
||||
db.query("UPDATE songs SET youtube_id = NULL, youtube_status = 'none', youtube_title = NULL, youtube_channel = NULL, embeddable = NULL WHERE id = ?").run(s.id);
|
||||
db.query('DELETE FROM youtube_candidates WHERE song_id = ?').run(s.id);
|
||||
db.query("DELETE FROM signals WHERE song_id = ? AND kind LIKE 'yt_tried_%'").run(s.id);
|
||||
}
|
||||
})();
|
||||
if (sameKey[0]) mergeSongs(db, sameKey[0], [s.id], now);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -14,6 +14,9 @@
|
||||
* bun apps/server/src/collector/cli.ts fix-text (one-off: decode `'`/`&` saved in titles, let 원곡 찾기 retry them)
|
||||
* bun apps/server/src/collector/cli.ts clean-titles [--review] [--limit N] (제목 정리·정답 만들기: 새 곡은 바로 반영, 일본어·확인 필요는 검토 목록; --review = 모두 검토 목록, docs/13)
|
||||
* 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 fix-melon-titles [--dry-run] (one-off: songs saved with their singer's name as the title get the Melon song name, then clean-titles)
|
||||
* bun apps/server/src/collector/cli.ts redo-readings [--dry-run] [--old-lexicon file.json] (발음 정답 from the old rule reader → the 한글 표기표, DB and saved quizzes; after a 표기표 fix, --old-lexicon = the table before it, from git)
|
||||
* bun apps/server/src/collector/cli.ts lexicon-missing (words the 한글 표기표 lacks, with a rule guess, for the next table update)
|
||||
* bun apps/server/src/collector/cli.ts stats
|
||||
* In the container: docker exec music_quiz-app-1 bun apps/server/src/collector/cli.ts …
|
||||
*/
|
||||
@@ -33,6 +36,10 @@ import { collectAgeAudio } from './age-audio';
|
||||
import { audioDir } from '../songs/audio';
|
||||
import { dropVersions, fixEntities } from './text';
|
||||
import { buildTitleReviews } from '../songs/title-review';
|
||||
import { redoReadings } from '../songs/readings-redo';
|
||||
import { fixMelonTitles } from './charts';
|
||||
import { wordToHangul } from '../answers/en-ko';
|
||||
import type { LexiconTable } from '../answers/lexicon';
|
||||
import { wikiLookup } from '../answers/wiki';
|
||||
|
||||
const [cmd, ...rest] = process.argv.slice(2);
|
||||
@@ -122,11 +129,35 @@ switch (cmd) {
|
||||
console.log(`${rest.includes('--dry-run') ? 'dry run: would trash' : 'trashed'} ${rest.includes('--dry-run') ? r.songs.length : r.trashed}`);
|
||||
break;
|
||||
}
|
||||
case 'fix-melon-titles': {
|
||||
const dryRun = rest.includes('--dry-run');
|
||||
const fixed = await fixMelonTitles(db, { dryRun });
|
||||
for (const f of fixed) console.log(`${f.id}\tmelon ${f.melonId}\t${f.artist}: ${f.from} → ${f.to}${f.video ? `\t(영상 ${f.video})` : ''}${f.mergedInto ? `\t같은 곡 ${f.mergedInto}에 합침` : ''}`);
|
||||
console.log(`${dryRun ? 'dry run: would fix' : 'fixed'} ${fixed.length}`);
|
||||
if (!dryRun && fixed.length) {
|
||||
const r = await buildTitleReviews(db, { ids: fixed.filter((f) => !f.mergedInto).map((f) => f.id), wiki: wikiLookup() });
|
||||
console.log(`clean-titles: 바로 반영 ${r.auto}, 검토 ${r.pending}, 바뀔 것 없음 ${r.same}`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'redo-readings': {
|
||||
const i = rest.indexOf('--old-lexicon');
|
||||
const oldTables = i >= 0 ? [(await Bun.file(rest[i + 1]!).json()) as LexiconTable] : [];
|
||||
const r = redoReadings(db, { dryRun: rest.includes('--dry-run'), oldTables });
|
||||
for (const e of r.examples) console.log(`${e.where}\t${e.name}\t- ${e.drop.join(', ')}\t+ ${e.add.join(', ')}`);
|
||||
console.log(JSON.stringify({ songs: r.songs, quizItems: r.quizItems, unknownSongs: r.unknownSongs, unknownWords: r.unknownWords.size }));
|
||||
break;
|
||||
}
|
||||
case 'lexicon-missing': {
|
||||
const r = redoReadings(db, { dryRun: true });
|
||||
for (const [w, n] of [...r.unknownWords].sort((a, b) => b[1] - a[1])) console.log(`${w}\t${n}\t${(() => { try { return wordToHangul(w) ?? '?'; } catch { return '?'; } })()}`);
|
||||
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|clean-titles|drop-versions|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|clean-titles|drop-versions|fix-melon-titles|redo-readings|lexicon-missing|stats');
|
||||
process.exitCode = 1;
|
||||
}
|
||||
db.close();
|
||||
|
||||
@@ -13,6 +13,7 @@ test('entities: hex, decimal and named, one pass, unknown ones kept', () => {
|
||||
expect(decodeEntities('Somebody's Watching Me')).toBe("Somebody's Watching Me");
|
||||
expect(decodeEntities('AC/DC 'n' Salty & Sweet "x" <3>')).toBe(`AC/DC 'n' Salty & Sweet "x" <3>`);
|
||||
expect(decodeEntities('&#x27;')).toBe(''');
|
||||
expect(decodeEntities('Céline Dion · 98° · ROSÉ')).toBe('Céline Dion · 98° · ROSÉ');
|
||||
expect(decodeEntities('R&B & Soul; &bogus; �')).toBe('R&B & Soul; &bogus; �');
|
||||
});
|
||||
|
||||
|
||||
@@ -3,12 +3,19 @@ import type { Database } from 'bun:sqlite';
|
||||
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: ' ' };
|
||||
const NAMED: Record<string, string> = {
|
||||
amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ',
|
||||
// names seen in Melon pop titles/artists ("Céline Dion", "98°")
|
||||
deg: '°', eacute: 'é', egrave: 'è', ecirc: 'ê', euml: 'ë', aacute: 'á', agrave: 'à', acirc: 'â', auml: 'ä', atilde: 'ã', aring: 'å',
|
||||
iacute: 'í', igrave: 'ì', icirc: 'î', iuml: 'ï', oacute: 'ó', ograve: 'ò', ocirc: 'ô', ouml: 'ö', otilde: 'õ', oslash: 'ø',
|
||||
uacute: 'ú', ugrave: 'ù', ucirc: 'û', uuml: 'ü', ntilde: 'ñ', ccedil: 'ç', szlig: 'ß', yacute: 'ý',
|
||||
hellip: '…', ndash: '–', mdash: '—', lsquo: '‘', rsquo: '’', ldquo: '“', rdquo: '”', middot: '·', times: '×', hearts: '♥',
|
||||
};
|
||||
|
||||
/** One pass, so `&#x27;` becomes the literal text `'` (not `'`). Unknown entities stay as they are. */
|
||||
export function decodeEntities(s: string): string {
|
||||
return s.replace(/&(#[xX][0-9a-fA-F]+|#\d+|[a-zA-Z]+);/g, (m, e: string) => {
|
||||
if (e[0] !== '#') return NAMED[e.toLowerCase()] ?? m;
|
||||
if (e[0] !== '#') return NAMED[e] ?? (NAMED[e.toLowerCase()] && /^[A-Z][a-z]+$/.test(e) && e.length > 4 ? NAMED[e.toLowerCase()]!.toUpperCase() : NAMED[e.toLowerCase()]) ?? m;
|
||||
const n = e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : Number(e.slice(1));
|
||||
return n > 0 && n <= 0x10ffff ? String.fromCodePoint(n) : m;
|
||||
});
|
||||
|
||||
@@ -215,7 +215,7 @@ test('플레이리스트 가져오기: DB songs by video, cleaned YouTube titles
|
||||
expect(rows[2]).toMatchObject({ status: 'found', videoId: 'hypeboy0001' });
|
||||
expect(rows[3]).toMatchObject({ status: 'missing', videoId: null });
|
||||
// answers besides the shown names (docs/13): the DB song's aliases come along
|
||||
expect(rows[0]).toMatchObject({ titleAnswers: ['Good Day', '굿 데이'], artistAnswers: ['IU'] });
|
||||
expect(rows[0]).toMatchObject({ titleAnswers: ['Good Day', '굿 데이', '굿데이'], artistAnswers: ['IU'] });
|
||||
// someone else's job is not visible
|
||||
const g = await guest(s.base, '손님');
|
||||
expect((await api(s.base, `/api/admin/quizzes/pick/playlist/${job.id}`, { cookie: g.cookie })).res.status).toBe(403);
|
||||
@@ -230,8 +230,8 @@ test('정답 자동 채우기 (docs/13): cleaned-title names and the aliases of
|
||||
body: JSON.stringify({ songs: [{ title: '좋은 날', artist: '아이유' }, { title: '사랑을 했다(LOVE SCENARIO)', artist: '아이콘' }, { title: '모르는 곡' }] }),
|
||||
});
|
||||
expect(r.body.answers).toEqual([
|
||||
{ titleAnswers: ['Good Day', '굿 데이'], artistAnswers: ['IU'] },
|
||||
{ titleAnswers: ['LOVE SCENARIO', '사랑을 했다 LOVE SCENARIO', '러브 시나리오'], artistAnswers: [] },
|
||||
{ titleAnswers: ['Good Day', '굿 데이', '굿데이'], artistAnswers: ['IU'] },
|
||||
{ titleAnswers: ['LOVE SCENARIO', '사랑을 했다 LOVE SCENARIO', '러브 시나리오', '러브시나리오'], artistAnswers: [] },
|
||||
{ titleAnswers: [], artistAnswers: [] },
|
||||
]);
|
||||
const g = await guest(s.base, '손님');
|
||||
|
||||
@@ -306,7 +306,18 @@ export function mountCatalogAdmin(
|
||||
.object({
|
||||
ids: z.array(z.number().int()).max(5000).optional(),
|
||||
kind: z.enum(kindIds).optional(),
|
||||
edits: z.array(z.object({ id: z.number().int(), title: z.string().trim().max(200).optional(), artist: z.string().trim().max(200).optional() })).max(5000).optional(),
|
||||
edits: z
|
||||
.array(
|
||||
z.object({
|
||||
id: z.number().int(),
|
||||
title: z.string().trim().max(200).optional(),
|
||||
artist: z.string().trim().max(200).optional(),
|
||||
titleAnswers: z.array(z.string().trim().min(1).max(200)).max(30).optional(),
|
||||
artistAnswers: z.array(z.string().trim().min(1).max(200)).max(30).optional(),
|
||||
}),
|
||||
)
|
||||
.max(5000)
|
||||
.optional(),
|
||||
})
|
||||
.refine((x) => x.ids?.length || x.kind, '곡이나 묶음을 골라 주세요.')
|
||||
.safeParse(await h.body(c));
|
||||
|
||||
@@ -180,7 +180,7 @@ async function runImport(d: ImportDeps, job: ImportJob, tracks: LavalinkTrack[])
|
||||
// shown title without brackets / feat. / version marks (the answers come at the end, docs/13)
|
||||
// the title as found goes to the answers below (its brackets hold other names), the row shows it cleaned meanwhile
|
||||
rawTitles.push(row.title);
|
||||
row.title = cleanTitle(row.title).title;
|
||||
row.title = cleanTitle(row.title, row.artist).title;
|
||||
job.rows.push(row);
|
||||
job.done = i + 1;
|
||||
}
|
||||
|
||||
71
apps/server/src/readings-redo.test.ts
Normal file
71
apps/server/src/readings-redo.test.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
/** 발음 정답 다시 만들기 (2026-11-04, docs/13): old rule readings → the checked 한글 표기표, in the DB and in saved quizzes. */
|
||||
import { expect, test } from 'bun:test';
|
||||
import { openDb } from './db';
|
||||
import { tempDbPath } from './test-utils';
|
||||
import { Catalog } from './collector/catalog';
|
||||
import { redoReadings } from './songs/readings-redo';
|
||||
|
||||
function aliases(db: ReturnType<typeof openDb>, id: number, part: string) {
|
||||
return db
|
||||
.query<{ alias: string }, [number, string]>('SELECT alias FROM song_aliases WHERE song_id = ? AND part = ? ORDER BY alias')
|
||||
.all(id, part)
|
||||
.map((r) => r.alias);
|
||||
}
|
||||
|
||||
test('DB songs: the old reader\'s readings and the singer bracket go, checked spellings come, an admin alias stays', () => {
|
||||
const db = openDb(tempDbPath());
|
||||
const c = new Catalog(db);
|
||||
const [rod] = c.upsert({ title: 'Heaven', artists: [{ name: 'Rod Stewart' }], source: 't', ref: '1' });
|
||||
const [crank] = c.upsert({ title: 'Crank That', artists: [{ name: 'Soulja Boy' }], source: 't', ref: '2' });
|
||||
const add = db.query('INSERT INTO song_aliases (song_id, part, alias, source) VALUES (?, ?, ?, ?)');
|
||||
// what the 2026-11-04 cleanup wrote with the old rule reader
|
||||
add.run(rod!, 'artist', '로드 스투어트', 'auto');
|
||||
add.run(rod!, 'title', '헤벤', 'auto');
|
||||
add.run(rod!, 'artist', '로드', 'admin');
|
||||
db.query("INSERT INTO title_reviews (song_id, kind, status, old_title, old_artist, new_title, new_artist, title_answers, artist_answers, created_at) VALUES (?, 'title', 'applied', ?, ?, ?, ?, '[]', '[]', 0)").run(
|
||||
crank!,
|
||||
'Crank That (Soulja Boy)',
|
||||
'Soulja Boy',
|
||||
'Crank That',
|
||||
'Soulja Boy',
|
||||
);
|
||||
for (const a of ['Crank That (Soulja Boy)', 'Crank That Soulja Boy', 'Soulja Boy', '솔야 보이', '크랭크 댓', '크랭크 댓 솔야 보이']) add.run(crank!, 'title', a, 'auto');
|
||||
add.run(crank!, 'artist', '솔야 보이', 'auto');
|
||||
|
||||
const dry = redoReadings(db, { dryRun: true });
|
||||
expect(dry.songs.changed).toBe(2);
|
||||
expect(aliases(db, rod!, 'artist')).toEqual(['로드', '로드 스투어트']);
|
||||
|
||||
redoReadings(db);
|
||||
expect(aliases(db, rod!, 'artist')).toEqual(['로드', '로드 스튜어트', '로드스튜어트']);
|
||||
expect(aliases(db, rod!, 'title')).toEqual(['헤븐']);
|
||||
// the old title as collected stays; the singer in its bracket and every reading of it go
|
||||
expect(aliases(db, crank!, 'title')).toEqual(['Crank That (Soulja Boy)', '크랭크 댓', '크랭크댓']);
|
||||
expect(aliases(db, crank!, 'artist')).toEqual(['솔자 보이', '솔자보이']);
|
||||
// a second run changes nothing
|
||||
expect(redoReadings(db).songs.changed).toBe(0);
|
||||
// a 표기표 fix later: a spelling the table had before (not the rule reader's) goes only when that table is passed
|
||||
const before = { words: { heaven: ['헤에븐'] }, titles: {}, artists: {} };
|
||||
db.query("INSERT INTO song_aliases (song_id, part, alias, source) VALUES (?, 'title', '헤에븐', 'auto')").run(rod!);
|
||||
expect(redoReadings(db).songs.changed).toBe(0);
|
||||
expect(redoReadings(db, { oldTables: [before] }).songs.dropped).toBe(1);
|
||||
expect(aliases(db, rod!, 'title')).toEqual(['헤븐']);
|
||||
});
|
||||
|
||||
test('saved quizzes: generated readings replaced, typed answers kept, 이지선다 quizzes left alone', () => {
|
||||
const db = openDb(tempDbPath());
|
||||
db.query("INSERT INTO users (id, kind, nickname, created_at, last_seen_at) VALUES ('u', 'member', 'u', 0, 0)").run();
|
||||
const normal = (db.query("INSERT INTO custom_quizzes (owner_id, name, description, visibility, settings_json, kind, created_at, updated_at) VALUES ('u', 'q', '', 'private', '{}', 'normal', 0, 0) RETURNING id").get() as { id: number }).id;
|
||||
const duel = (db.query("INSERT INTO custom_quizzes (owner_id, name, description, visibility, settings_json, kind, created_at, updated_at) VALUES ('u', 'd', '', 'private', '{}', 'duel', 0, 0) RETURNING id").get() as { id: number }).id;
|
||||
const item = db.query(
|
||||
"INSERT INTO custom_quiz_items (quiz_id, pos, video_id, title, artist, title_answers, artist_answers) VALUES (?, ?, 'aaaaaaaaaaa', ?, ?, ?, ?) RETURNING id",
|
||||
);
|
||||
const a = (item.get(normal, 0, 'Dreamers', 'Jung Kook', JSON.stringify(['드리머즈 노래']), JSON.stringify(['융 쿠크', '정꾹이'])) as { id: number }).id;
|
||||
const b = (item.get(duel, 0, 'Dreamers', 'Jung Kook', '[]', '[]') as { id: number }).id;
|
||||
const r = redoReadings(db);
|
||||
expect(r.quizItems.changed).toBe(1);
|
||||
const got = (id: number) => db.query<{ t: string; a: string }, [number]>('SELECT title_answers t, artist_answers a FROM custom_quiz_items WHERE id = ?').get(id)!;
|
||||
expect(JSON.parse(got(a).t)).toEqual(['드리머즈 노래', '드리머스', '드리머즈']);
|
||||
expect(JSON.parse(got(a).a)).toEqual(['정꾹이', '정국']);
|
||||
expect(got(b)).toEqual({ t: '[]', a: '[]' });
|
||||
});
|
||||
175
apps/server/src/songs/readings-redo.ts
Normal file
175
apps/server/src/songs/readings-redo.ts
Normal file
@@ -0,0 +1,175 @@
|
||||
/**
|
||||
* 발음 정답 다시 만들기 (2026-11-04, docs/13): the Hangul readings made by the old rule reader (en-ko.ts: "Rod Stewart" →
|
||||
* 로드 스투어트) are replaced by the checked 한글 표기표 (lexicon.ts: 로드 스튜어트), in the server DB (song_aliases source
|
||||
* 'auto') and in the saved quizzes. Only answers equal to what the old reader made from that song's own names go; answers
|
||||
* an admin typed stay. Also drops what an old bracket of the singer's name made a title answer ("Crank That (Soulja Boy)" →
|
||||
* Soulja Boy, 솔야 보이). A text whose words the table lacks gets no reading (listed in `unknown`). 이지선다 quizzes are skipped.
|
||||
*/
|
||||
import type { Database } from 'bun:sqlite';
|
||||
import { cleanTitle } from '@mq/shared';
|
||||
import { englishToHangul } from '../answers/en-ko';
|
||||
import { hangulReadings, knownArtist, type LexiconTable } from '../answers/lexicon';
|
||||
|
||||
const HANGUL = /\p{Script=Hangul}/u;
|
||||
const LATIN_ONLY = (t: string) => /[A-Za-z]/.test(t) && !/[\p{Script=Hangul}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u.test(t);
|
||||
/** The old artist split (before quoted names were kept whole): what the old reader read. */
|
||||
const oldNames = (a: string) => [a, ...a.split(/\s*(?:,|&|\/|·|\sx\s|\bfeat\.?\s|\bwith\s)\s*/i)].map((x) => x.trim()).filter(Boolean);
|
||||
const newNames = (a: string) => {
|
||||
const quoted: string[] = [];
|
||||
const masked = a.replace(/"[^"]*"|“[^”]*”|「[^」]*」/g, (m) => `\u0000${quoted.push(m) - 1}\u0000`);
|
||||
return [a, ...masked.split(/\s*(?:,|&|\/|·|\sx\s|\bfeat\.?\s|\bwith\s)\s*/i).map((x) => x.replace(/\u0000(\d+)\u0000/g, (_, i: string) => quoted[Number(i)]!))].map((x) => x.trim()).filter(Boolean);
|
||||
};
|
||||
const low = (s: string) => s.trim().toLowerCase();
|
||||
|
||||
/** What the old rule reader (and earlier 표기표 versions, `oldTables`) made from these texts. */
|
||||
function oldReadings(texts: string[], kind: 'title' | 'artist', oldTables: LexiconTable[]): Set<string> {
|
||||
const out = new Set<string>();
|
||||
for (const t of texts) {
|
||||
if (!LATIN_ONLY(t)) continue;
|
||||
const r = englishToHangul(t);
|
||||
if (r) out.add(low(r));
|
||||
for (const table of oldTables) for (const x of hangulReadings(t, kind, table).readings) out.add(low(x));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Readings of the texts; the words the table lacks are noted only for `report` texts (the shown title, the artist names). */
|
||||
function newReadings(texts: string[], kind: 'title' | 'artist', unknown: Set<string>, report: Set<string>): string[] {
|
||||
const out: string[] = [];
|
||||
for (const t of texts) {
|
||||
if (!LATIN_ONLY(t)) continue;
|
||||
const r = hangulReadings(t, kind);
|
||||
out.push(...r.readings);
|
||||
if (report.has(t)) for (const w of r.unknown) unknown.add(w);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export interface RedoPlan {
|
||||
/** Answers that go / come, per part. */
|
||||
title: { drop: string[]; add: string[] };
|
||||
artist: { drop: string[]; add: string[] };
|
||||
unknown: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Old and new answers of one song or quiz item. `title`/`artist` = the names now shown, `source` = the title as collected
|
||||
* (its brackets made the old answers), `answers` = the answers it has now.
|
||||
*/
|
||||
export function planReadings(
|
||||
p: { title: string; artist: string; source?: string; titleAnswers: string[]; artistAnswers: string[] },
|
||||
oldTables: LexiconTable[] = [],
|
||||
): RedoPlan {
|
||||
const src = p.source ?? p.title;
|
||||
const before = cleanTitle(src);
|
||||
const after = cleanTitle(src, p.artist);
|
||||
// bracket names that were the singer's: no longer title answers, nor their readings
|
||||
const dropped = before.aliases.filter((a) => !after.aliases.some((b) => low(b) === low(a)));
|
||||
const titleTexts = [p.title, src, before.title, ...before.aliases, ...p.titleAnswers];
|
||||
const oldTitle = new Set([...oldReadings(titleTexts, 'title', oldTables), ...dropped.map(low)]);
|
||||
const oldArtist = oldReadings([...oldNames(p.artist), ...p.artistAnswers], 'artist', oldTables);
|
||||
const unknown = new Set<string>();
|
||||
// an answer that is the old title as collected ("Song (feat. X)") is read without its notes
|
||||
const keptTitleTexts = [...new Set([p.title, after.title, ...after.aliases, ...p.titleAnswers.filter((a) => !oldTitle.has(low(a))).map((a) => cleanTitle(a, p.artist).title)])];
|
||||
const newTitle = newReadings(keptTitleTexts, 'title', unknown, new Set([p.title]));
|
||||
const names = newNames(p.artist);
|
||||
const credit = knownArtist(p.artist) || names.length === 1 ? [p.artist] : names.slice(1);
|
||||
const newArtist = newReadings([...new Set([...names, ...p.artistAnswers.filter((a) => !oldArtist.has(low(a)))])], 'artist', unknown, new Set(credit));
|
||||
const shownT = new Set([low(p.title), low(src)]);
|
||||
const shownA = new Set([low(p.artist)]);
|
||||
const keepT = new Set(newTitle.map(low));
|
||||
const keepA = new Set(newArtist.map(low));
|
||||
const has = (list: string[]) => new Set(list.map(low));
|
||||
const hadT = has(p.titleAnswers);
|
||||
const hadA = has(p.artistAnswers);
|
||||
return {
|
||||
title: {
|
||||
drop: p.titleAnswers.filter((a) => oldTitle.has(low(a)) && !keepT.has(low(a)) && (HANGUL.test(a) || dropped.some((d) => low(d) === low(a)) || after.aliases.every((b) => low(b) !== low(a)))),
|
||||
add: [...new Set(newTitle)].filter((a) => !hadT.has(low(a)) && !shownT.has(low(a))),
|
||||
},
|
||||
artist: {
|
||||
drop: p.artistAnswers.filter((a) => oldArtist.has(low(a)) && !keepA.has(low(a)) && HANGUL.test(a)),
|
||||
add: [...new Set(newArtist)].filter((a) => !hadA.has(low(a)) && !shownA.has(low(a))),
|
||||
},
|
||||
unknown: [...unknown],
|
||||
};
|
||||
}
|
||||
|
||||
export interface RedoResult {
|
||||
songs: { changed: number; dropped: number; added: number };
|
||||
quizItems: { changed: number; dropped: number; added: number };
|
||||
unknownSongs: number;
|
||||
unknownWords: Map<string, number>;
|
||||
examples: { where: string; name: string; drop: string[]; add: string[] }[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the plan over every DB song and every saved quiz item. `dryRun` changes nothing. After a 표기표 fix, pass the table
|
||||
* as it was before (`oldTables`, from git) so the spellings it made go too.
|
||||
*/
|
||||
export function redoReadings(db: Database, opts: { dryRun?: boolean; oldTables?: LexiconTable[] } = {}): RedoResult {
|
||||
const out: RedoResult = { songs: { changed: 0, dropped: 0, added: 0 }, quizItems: { changed: 0, dropped: 0, added: 0 }, unknownSongs: 0, unknownWords: new Map(), examples: [] };
|
||||
const songs = db
|
||||
.query<{ id: number; title: string; artist: string; old_title: string | null }, []>(
|
||||
'SELECT s.id, s.title, s.artist, r.old_title FROM songs s LEFT JOIN title_reviews r ON r.song_id = s.id WHERE s.deleted_at IS NULL ORDER BY s.id',
|
||||
)
|
||||
.all();
|
||||
const aliases = db.query<{ part: string; alias: string; source: string }, [number]>('SELECT part, alias, source FROM song_aliases WHERE song_id = ?');
|
||||
const del = db.query("DELETE FROM song_aliases WHERE song_id = ? AND part = ? AND alias = ? AND source = 'auto'");
|
||||
const add = db.query("INSERT OR IGNORE INTO song_aliases (song_id, part, alias, source) VALUES (?, ?, ?, 'auto')");
|
||||
const run = () => {
|
||||
for (const s of songs) {
|
||||
const al = aliases.all(s.id);
|
||||
// only generated answers can go; an admin's alias is read (it may be English) but never dropped
|
||||
const auto = (part: string) => al.filter((a) => a.part === part && a.source === 'auto').map((a) => a.alias);
|
||||
const admin = (part: string) => al.filter((a) => a.part === part && a.source !== 'auto').map((a) => a.alias);
|
||||
const plan = planReadings(
|
||||
{ title: s.title, artist: s.artist, source: s.old_title ?? s.title, titleAnswers: [...auto('title'), ...admin('title')], artistAnswers: [...auto('artist'), ...admin('artist')] },
|
||||
opts.oldTables,
|
||||
);
|
||||
const autoT = new Set(auto('title'));
|
||||
const autoA = new Set(auto('artist'));
|
||||
const dropT = plan.title.drop.filter((a) => autoT.has(a));
|
||||
const dropA = plan.artist.drop.filter((a) => autoA.has(a));
|
||||
if (plan.unknown.length) {
|
||||
out.unknownSongs++;
|
||||
for (const w of plan.unknown) out.unknownWords.set(w, (out.unknownWords.get(w) ?? 0) + 1);
|
||||
}
|
||||
if (!dropT.length && !dropA.length && !plan.title.add.length && !plan.artist.add.length) continue;
|
||||
out.songs.changed++;
|
||||
out.songs.dropped += dropT.length + dropA.length;
|
||||
out.songs.added += plan.title.add.length + plan.artist.add.length;
|
||||
out.examples.push({ where: `song ${s.id}`, name: `${s.artist} - ${s.title}`, drop: [...dropT, ...dropA], add: [...plan.title.add, ...plan.artist.add] });
|
||||
if (opts.dryRun) continue;
|
||||
for (const a of dropT) del.run(s.id, 'title', a);
|
||||
for (const a of dropA) del.run(s.id, 'artist', a);
|
||||
for (const a of plan.title.add) add.run(s.id, 'title', a.slice(0, 200));
|
||||
for (const a of plan.artist.add) add.run(s.id, 'artist', a.slice(0, 200));
|
||||
}
|
||||
// 이지선다 quizzes have no answers
|
||||
const items = db
|
||||
.query<{ id: number; title: string; artist: string; title_answers: string; artist_answers: string }, []>(
|
||||
"SELECT i.id, i.title, i.artist, i.title_answers, i.artist_answers FROM custom_quiz_items i JOIN custom_quizzes q ON q.id = i.quiz_id WHERE q.kind <> 'duel'",
|
||||
)
|
||||
.all();
|
||||
const save = db.query('UPDATE custom_quiz_items SET title_answers = ?, artist_answers = ? WHERE id = ?');
|
||||
for (const it of items) {
|
||||
const ta = JSON.parse(it.title_answers) as string[];
|
||||
const aa = JSON.parse(it.artist_answers) as string[];
|
||||
const plan = planReadings({ title: it.title, artist: it.artist, titleAnswers: ta, artistAnswers: aa }, opts.oldTables);
|
||||
if (!plan.title.drop.length && !plan.artist.drop.length && !plan.title.add.length && !plan.artist.add.length) continue;
|
||||
const dT = new Set(plan.title.drop);
|
||||
const dA = new Set(plan.artist.drop);
|
||||
const nt = [...ta.filter((a) => !dT.has(a)), ...plan.title.add].slice(0, 30);
|
||||
const na = [...aa.filter((a) => !dA.has(a)), ...plan.artist.add].slice(0, 30);
|
||||
out.quizItems.changed++;
|
||||
out.quizItems.dropped += plan.title.drop.length + plan.artist.drop.length;
|
||||
out.quizItems.added += plan.title.add.length + plan.artist.add.length;
|
||||
out.examples.push({ where: `quiz item ${it.id}`, name: `${it.artist} - ${it.title}`, drop: [...plan.title.drop, ...plan.artist.drop], add: [...plan.title.add, ...plan.artist.add] });
|
||||
if (!opts.dryRun) save.run(JSON.stringify(nt), JSON.stringify(na), it.id);
|
||||
}
|
||||
};
|
||||
if (opts.dryRun) run();
|
||||
else db.transaction(run)();
|
||||
return out;
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
/**
|
||||
* 제목 정리 검토 (docs/13): every DB song gets its cleaned title/artist and generated answers (answers/index.ts) once.
|
||||
* - `review` (the first run over the existing DB): everything that would change waits for an admin (pending).
|
||||
* - otherwise (new songs, cron / 관리자 → 수집): applied at once, except Japanese songs and '확인 필요' ones (pending).
|
||||
* - otherwise (new songs, cron / 관리자 → 수집): applied at once, except Japanese songs and '확인 필요' ones (pending):
|
||||
* a Japanese name with no Korean name found, or a word the 한글 표기표 does not know (note '발음 확인 필요: …', no reading added).
|
||||
* Applying writes the shown title/artist and adds the answers as song aliases (source 'auto'); match_key stays, so the
|
||||
* charts keep finding the song by its source name. A row whose song was edited since it was made is not applied.
|
||||
*/
|
||||
@@ -79,13 +80,15 @@ export async function buildTitleReviews(
|
||||
const ta = newAnswers(db, s.id, 'title', a.titleAnswers, [a.title, s.title]);
|
||||
const aa = newAnswers(db, s.id, 'artist', a.artistAnswers, [a.artist, s.artist]);
|
||||
const renamed = a.title !== s.title || a.artist !== s.artist;
|
||||
if (!renamed && !ta.length && !aa.length) {
|
||||
if (!renamed && !ta.length && !aa.length && !a.unknownWords.length) {
|
||||
save.run(s.id, 'answers', 'same', s.title, s.artist, s.title, s.artist, '[]', '[]', null, now);
|
||||
out.same++;
|
||||
return;
|
||||
}
|
||||
const notes = a.note ? [a.note] : [];
|
||||
const kind: TitleReviewKind = a.note?.includes('확인 필요') ? 'check' : japaneseName(s.title) || japaneseName(s.artist) ? 'japanese' : renamed ? 'title' : 'answers';
|
||||
if (a.unknownWords.length) notes.push(`발음 확인 필요: ${a.unknownWords.slice(0, 8).join(', ')}`);
|
||||
const kind: TitleReviewKind =
|
||||
a.note?.includes('확인 필요') || a.unknownWords.length ? 'check' : japaneseName(s.title) || japaneseName(s.artist) ? 'japanese' : renamed ? 'title' : 'answers';
|
||||
const status = opts.review || kind === 'japanese' || kind === 'check' ? 'pending' : 'auto';
|
||||
save.run(s.id, kind, status, s.title, s.artist, a.title, a.artist, JSON.stringify(ta), JSON.stringify(aa), notes.join(' · ') || null, now);
|
||||
if (status === 'auto') {
|
||||
@@ -101,8 +104,16 @@ export async function buildTitleReviews(
|
||||
|
||||
const parse = (s: string) => JSON.parse(s) as string[];
|
||||
|
||||
export interface TitleReviewEdit {
|
||||
title?: string;
|
||||
artist?: string;
|
||||
/** Answers the admin adds (a reading the 표기표 lacked). */
|
||||
titleAnswers?: string[];
|
||||
artistAnswers?: string[];
|
||||
}
|
||||
|
||||
/** Writes one review (with an admin's edit of the names): returns why it was not applied, or null. */
|
||||
function applyOne(db: Database, songId: number, edit: { title?: string; artist?: string } | null, by: string, now: number): string | null {
|
||||
function applyOne(db: Database, songId: number, edit: TitleReviewEdit | null, by: string, now: number): string | null {
|
||||
const r = db
|
||||
.query<{ old_title: string; old_artist: string; new_title: string; new_artist: string; title_answers: string; artist_answers: string; status: string }, [number]>(
|
||||
'SELECT old_title, old_artist, new_title, new_artist, title_answers, artist_answers, status FROM title_reviews WHERE song_id = ?',
|
||||
@@ -117,10 +128,10 @@ function applyOne(db: Database, songId: number, edit: { title?: string; artist?:
|
||||
db.query('UPDATE songs SET title = ?, artist = ?, updated_at = ? WHERE id = ?').run(title, artist, now, songId);
|
||||
const add = db.query("INSERT OR IGNORE INTO song_aliases (song_id, part, alias, source) VALUES (?, ?, ?, 'auto')");
|
||||
// the names it had stay answers when they changed
|
||||
const titles = [...parse(r.title_answers), ...(title !== r.old_title ? [r.old_title] : []), ...(title !== r.new_title ? [r.new_title] : [])];
|
||||
const artists = [...parse(r.artist_answers), ...(artist !== r.old_artist ? [r.old_artist] : [])];
|
||||
for (const a of titles) if (a.toLowerCase() !== title.toLowerCase()) add.run(songId, 'title', a.slice(0, 200));
|
||||
for (const a of artists) if (a.toLowerCase() !== artist.toLowerCase()) add.run(songId, 'artist', a.slice(0, 200));
|
||||
const titles = [...parse(r.title_answers), ...(edit?.titleAnswers ?? []), ...(title !== r.old_title ? [r.old_title] : []), ...(title !== r.new_title ? [r.new_title] : [])];
|
||||
const artists = [...parse(r.artist_answers), ...(edit?.artistAnswers ?? []), ...(artist !== r.old_artist ? [r.old_artist] : [])];
|
||||
for (const a of titles) if (a.trim() && a.toLowerCase() !== title.toLowerCase()) add.run(songId, 'title', a.trim().slice(0, 200));
|
||||
for (const a of artists) if (a.trim() && a.toLowerCase() !== artist.toLowerCase()) add.run(songId, 'artist', a.trim().slice(0, 200));
|
||||
db.query('UPDATE title_reviews SET status = ?, new_title = ?, new_artist = ?, decided_at = ?, decided_by = ? WHERE song_id = ?').run(
|
||||
by === 'auto' ? 'auto' : 'applied',
|
||||
title,
|
||||
@@ -135,7 +146,7 @@ function applyOne(db: Database, songId: number, edit: { title?: string; artist?:
|
||||
/** 적용: the given pending rows (or every pending row of `kind`). Returns how many were applied and why others were not. */
|
||||
export function applyTitleReviews(
|
||||
db: Database,
|
||||
p: { ids?: number[]; kind?: TitleReviewKind; edits?: { id: number; title?: string; artist?: string }[] },
|
||||
p: { ids?: number[]; kind?: TitleReviewKind; edits?: ({ id: number } & TitleReviewEdit)[] },
|
||||
by: string,
|
||||
now = Date.now(),
|
||||
): { applied: number; failed: { id: number; why: string }[] } {
|
||||
|
||||
@@ -32,7 +32,7 @@ test('first run (--review): everything that would change waits; nothing is writt
|
||||
const list = listTitleReviews(db, {});
|
||||
expect(list.total).toBe(4);
|
||||
const row = (id: number) => list.rows.find((x) => x.songId === id)!;
|
||||
expect(row(ids.bracket)).toMatchObject({ kind: 'title', newTitle: '사랑을 했다', titleAnswers: ['LOVE SCENARIO', '사랑을 했다 LOVE SCENARIO', '러브 시나리오'] });
|
||||
expect(row(ids.bracket)).toMatchObject({ kind: 'title', newTitle: '사랑을 했다', titleAnswers: ['LOVE SCENARIO', '사랑을 했다 LOVE SCENARIO', '러브 시나리오', '러브시나리오'] });
|
||||
expect(row(ids.feat)).toMatchObject({ kind: 'title', newTitle: 'Finesse', titleAnswers: ['피네스'] });
|
||||
// a Japanese artist without a Korean name: 확인 필요 comes first
|
||||
expect(row(ids.english)).toMatchObject({ kind: 'check', newTitle: 'Pretender', titleAnswers: ['프리텐더'], note: '확인 필요' });
|
||||
@@ -109,3 +109,18 @@ test('new songs: a Japanese title with a Korean bracket ("夜に駆ける (밤
|
||||
expect(title(ko!)).toBe('몽');
|
||||
expect(db.query<{ alias: string }, [number]>("SELECT alias FROM song_aliases WHERE song_id = ? AND part = 'title'").all(ko!).map((x) => x.alias)).toContain('夢');
|
||||
});
|
||||
|
||||
test('new songs: a word the 한글 표기표 lacks sends the song to 확인 필요 without a reading; the admin can add the reading when applying', async () => {
|
||||
const db = openDb(tempDbPath());
|
||||
const c = new Catalog(db);
|
||||
const [id] = c.upsert({ title: 'Heaven Xqzt (feat. Rod Stewart)', artists: [{ name: 'Billy Joel' }], source: 't', ref: '1' });
|
||||
const r = await buildTitleReviews(db, { wiki: async () => new Map() });
|
||||
expect(r).toMatchObject({ pending: 1, auto: 0 });
|
||||
const row = listTitleReviews(db, {}).rows[0]!;
|
||||
expect(row).toMatchObject({ songId: id, kind: 'check', newTitle: 'Heaven Xqzt', titleAnswers: [], note: '발음 확인 필요: xqzt' });
|
||||
expect(row.artistAnswers).toContain('빌리 조엘');
|
||||
expect(applyTitleReviews(db, { ids: [id!], edits: [{ id: id!, titleAnswers: ['헤븐 엑스큐지티'] }] }, 'admin').applied).toBe(1);
|
||||
const song = quizSong(db, id!)!;
|
||||
const st = { space: true, number: true, symbol: true };
|
||||
for (const t of ['헤븐 엑스큐지티', 'Heaven Xqzt', '빌리 조엘']) expect([t, isCorrect(t, song, t === '빌리 조엘' ? 'artist' : 'title', st)]).toEqual([t, true]);
|
||||
});
|
||||
|
||||
@@ -646,8 +646,8 @@ function SongsTab({
|
||||
<th style={{ width: 28 }} aria-label="순서 옮기기" />
|
||||
<th style={{ width: 44 }}>번호</th>
|
||||
<th>노래</th>
|
||||
<th>{duel ? '조회수' : '추가 정답'}</th>
|
||||
{duel && <th>비고</th>}
|
||||
<th>{duel ? '조회수' : '제목 정답'}</th>
|
||||
<th>{duel ? '비고' : '가수 정답'}</th>
|
||||
<th>길이</th>
|
||||
<th>재생 위치</th>
|
||||
<th style={{ width: 120 }} />
|
||||
@@ -699,7 +699,10 @@ function SongsTab({
|
||||
<td className="small">{duelViewsNote(it) ?? <span className="muted">-</span>}</td>
|
||||
</>
|
||||
) : (
|
||||
<td className="small">{[...it.titleAnswers, ...it.artistAnswers].join(', ') || <span className="muted">-</span>}</td>
|
||||
<>
|
||||
<td className="small">{it.titleAnswers.join(', ') || <span className="muted">-</span>}</td>
|
||||
<td className="small">{it.artistAnswers.join(', ') || <span className="muted">-</span>}</td>
|
||||
</>
|
||||
)}
|
||||
<td className="mono small">{mmss(it.durationSec ?? (it.songId ? db[it.songId]?.durationSec : null))}</td>
|
||||
<td className="small">{it.auto ? <span className="muted">자동</span> : `처음 ${mmss(it.startSec ?? 0)} · 하이라이트 ${mmss(it.highlightSec)}`}</td>
|
||||
|
||||
@@ -35,7 +35,8 @@ export function TitleReviewsPage() {
|
||||
const [page, setPage] = useState(0);
|
||||
const [data, setData] = useState<ListResp | null>(null);
|
||||
const [pick, setPick] = useState<Set<number>>(new Set());
|
||||
const [edits, setEdits] = useState<Record<number, { title?: string; artist?: string }>>({});
|
||||
// addTitle / addArtist: answers typed by the admin (a reading the 한글 표기표 lacked), comma separated
|
||||
const [edits, setEdits] = useState<Record<number, { title?: string; artist?: string; addTitle?: string; addArtist?: string }>>({});
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [confirmAll, setConfirmAll] = useState(false);
|
||||
const load = useCallback(() => {
|
||||
@@ -63,7 +64,14 @@ export function TitleReviewsPage() {
|
||||
};
|
||||
const rows = data?.rows ?? [];
|
||||
const chosen = [...pick];
|
||||
const editList = (ids: number[]) => ids.filter((id) => edits[id]).map((id) => ({ id, ...edits[id] }));
|
||||
const split = (s: string | undefined) => (s ?? '').split(',').map((x) => x.trim()).filter(Boolean);
|
||||
const editList = (ids: number[]) =>
|
||||
ids
|
||||
.filter((id) => edits[id])
|
||||
.map((id) => {
|
||||
const { addTitle, addArtist, ...names } = edits[id]!;
|
||||
return { id, ...names, titleAnswers: split(addTitle), artistAnswers: split(addArtist) };
|
||||
});
|
||||
const label = (k: Kind) => data?.kinds.find((x) => x.id === k)?.label ?? k;
|
||||
const pages = Math.ceil((data?.total ?? 0) / 100);
|
||||
return (
|
||||
@@ -177,7 +185,25 @@ export function TitleReviewsPage() {
|
||||
<td className="small">
|
||||
{r.titleAnswers.length > 0 && <div>제목: {r.titleAnswers.join(', ')}</div>}
|
||||
{r.artistAnswers.length > 0 && <div className="muted">가수: {r.artistAnswers.join(', ')}</div>}
|
||||
{!r.titleAnswers.length && !r.artistAnswers.length && <span className="muted">-</span>}
|
||||
{!r.titleAnswers.length && !r.artistAnswers.length && r.kind !== 'check' && <span className="muted">-</span>}
|
||||
{!done && r.kind === 'check' && (
|
||||
<div className="stack" style={{ gap: 4, marginTop: 4, minWidth: 200 }}>
|
||||
<input
|
||||
className="input sm"
|
||||
aria-label={`${r.oldTitle} 제목 정답 더하기`}
|
||||
placeholder="제목 정답 더하기 (,로 구분)"
|
||||
value={edits[r.songId]?.addTitle ?? ''}
|
||||
onChange={(e) => setEdits((cur) => ({ ...cur, [r.songId]: { ...cur[r.songId], addTitle: e.target.value } }))}
|
||||
/>
|
||||
<input
|
||||
className="input sm"
|
||||
aria-label={`${r.oldTitle} 가수 정답 더하기`}
|
||||
placeholder="가수 정답 더하기 (,로 구분)"
|
||||
value={edits[r.songId]?.addArtist ?? ''}
|
||||
onChange={(e) => setEdits((cur) => ({ ...cur, [r.songId]: { ...cur[r.songId], addArtist: e.target.value } }))}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="small">
|
||||
{done ? (
|
||||
|
||||
@@ -39,6 +39,22 @@
|
||||
5. [x] 배포 (2026-11-04 16:39~): 백업 `~/backups/music_quiz/app-before-title-clean-20261104-1639.db` → 651bc98 배포(015 마이그레이션) → `drop-versions --keep 7985,9066` 27곡 휴지통(목록 확인 뒤) → `clean-titles --review`: 제목·가수 정리 592, 정답만 3,638, 일본어 8, 확인 필요 2 검토 대기 → .9 crontab 02:50 `clean-titles`
|
||||
- 일본어 곡 중 アイドル은 위키백과가 낱말 문서(일본의 아이돌)로 이어져 이름이 틀림 — 검토 화면에서 고쳐 적용할 것
|
||||
|
||||
## 2026-11-04 저녁: 가수 정답 섞임 · 한글 발음 검수 (사용자 답 Q1~Q4 모두 진행)
|
||||
- 퀴즈 편집 화면: '추가 정답' 한 칸 → '제목 정답' · '가수 정답' 두 칸 (게임 판정은 원래 따로였음)
|
||||
- 괄호 안이 그 곡 가수 이름이면 제목 정답이 아님: `cleanTitle(title, artist)` (Crank That (Soulja Boy), 레이 (LAY)). 정답 생성·플레이리스트·파일 읽기 모두 가수를 넘김
|
||||
- 재생목록으로 엑셀 만들기: 정답·가수 정답 칸에 제목·가수를 다시 적지 않음(다른 표기만, 빈 칸은 파일로 만들 때 자동 채움). 내보내기(quizToRows)는 그대로 — 빈 칸이면 다시 읽을 때 자동 채움이 돌기 때문
|
||||
- 한글 발음: 규칙(en-ko.ts)은 후보로만, 정답은 검수한 표기표 `apps/server/src/answers/lexicon.json`(lexicon.ts)만
|
||||
- words 2,292 / titles 73(단어별로 읽으면 틀리는 제목) / artists 1,111(가수 이름 통째, 한국 공식 이름·일본 이름 성-이름 순서 포함)
|
||||
- 만든 방법: DB 영어 제목 단어 2,265개·가수 이름 1,155개(+ 영어 위키백과 → 한국어 문서 이름 764개)를 10묶음으로 나눠 검수, 띄어쓰기 보정, 손으로 고친 것(overrides). 작업 파일은 저장소 밖(`~/work/mq/lex/`)
|
||||
- 두 표기가 흔하면 둘 다(썸머/서머), 확실하지 않은 것은 넣지 않음(제목 단어 16, 가수 60)
|
||||
- 정답 판정 기본값이 띄어쓰기를 보므로 띄어 쓴 꼴과 붙여 쓴 꼴 둘 다 넣음(로드 스튜어트 / 로드스튜어트)
|
||||
- 표기표에 없는 단어가 있으면 그 글에는 발음 정답 없음 → `unknownWords`. 새 곡(02:50 clean-titles)은 '확인 필요' 검토(비고 '발음 확인 필요: …'), 관리자 → 제목 정리에서 '제목/가수 정답 더하기'로 직접 넣고 적용
|
||||
- 다음 표기표 갱신: `cli.ts lexicon-missing`(없는 단어, 규칙 후보, 곡 수) → lexicon.json에 추가 → 배포
|
||||
- 이미 들어간 발음 정답 바꾸기: `cli.ts redo-readings [--dry-run] [--old-lexicon 고치기전.json]` — 옛 규칙(과 넘긴 이전 표기표)이 그 곡 이름에서 만든 것과 같은 정답(source auto)만 빼고 표기표 표기를 넣음. 관리자가 넣은 별칭·퀴즈에 직접 쓴 정답은 그대로, 이지선다 퀴즈는 안 건드림. 표기표를 고친 뒤에는 `git show <고치기 전>:apps/server/src/answers/lexicon.json`을 --old-lexicon으로 넘겨야 이전 표기가 빠짐
|
||||
- 멜론 차트 파서: 재생이 막힌 곡은 제목 칸에 링크가 없어 다음 링크(가수)를 제목으로 읽던 것 → 제목 칸만 읽음. `cli.ts fix-melon-titles [--dry-run]`: 제목이 가수 이름과 같은 멜론 곡을 곡 정보 페이지 제목으로 고침(자기 이름 곡 소녀시대 등은 그대로), 자동 정답·제목 정리 행을 지우고 clean-titles로 다시, 제목으로 잘못 찾은 후보 영상은 원곡 찾기로 되돌림
|
||||
- `decodeEntities`: `é`·`°` 등 라틴 문자 이름 추가(Céline Dion) → `cli.ts fix-text`로 DB 고침
|
||||
- 퀴즈 파일 가수 칸의 따옴표 안('Miki Matsubara Official "stay with me"')을 with로 자르지 않음(가수 정답 '미' 같은 조각)
|
||||
|
||||
## 운영 DB에서 확인한 숫자 (2026-11-04 사본)
|
||||
- 10,762곡, 제목이 바뀌는 곡 617곡
|
||||
- `drop-versions`: 제목 21곡(사이렌 제외 20) + 영상 7곡(9066 제외) = 27곡, 퀴즈·플레이 기록에 쓰인 곡 없음
|
||||
|
||||
@@ -258,8 +258,9 @@ try {
|
||||
JSON.stringify(book[0]!.rows) ===
|
||||
JSON.stringify([
|
||||
['순번', '유튜브 영상 링크', '제목', '가수', '정답(;로 구분)', '가수 정답(;로 구분)', '힌트', '시작(초)', '하이라이트(초)', '길이(초)', '비고'],
|
||||
['1', 'https://youtu.be/jeqdYqsrsA0', '좋은 날', '아이유', '좋은 날', '아이유', '', '', '', '236', 'DB 곡'],
|
||||
['2', 'https://youtu.be/iIIjS6yDMQo', '밤편지', '아이유', '밤편지', '아이유', '', '', '', '260', '제목·가수 확인 필요 (영상 제목 형식이 달라 채널 이름을 가수로 씀)'],
|
||||
// the title and the artist always count: the answer cells hold only other names (none here)
|
||||
['1', 'https://youtu.be/jeqdYqsrsA0', '좋은 날', '아이유', '', '', '', '', '', '236', 'DB 곡'],
|
||||
['2', 'https://youtu.be/iIIjS6yDMQo', '밤편지', '아이유', '', '', '', '', '', '260', '제목·가수 확인 필요 (영상 제목 형식이 달라 채널 이름을 가수로 씀)'],
|
||||
]),
|
||||
`엑셀 내용: ${JSON.stringify(book[0]!.rows)}`,
|
||||
);
|
||||
|
||||
@@ -191,10 +191,10 @@ test('재생목록으로 엑셀 만들기: kept songs with 비고, unplayable /
|
||||
expect(sheets.map((x) => x.name)).toEqual(['퀴즈', '빠진 곡']);
|
||||
expect(sheets[0]!.rows).toEqual([
|
||||
['순번', '유튜브 영상 링크', '제목', '가수', '정답(;로 구분)', '가수 정답(;로 구분)', '힌트', '시작(초)', '하이라이트(초)', '길이(초)', '비고'],
|
||||
[1, 'https://youtu.be/goodday0001', '좋은 날', '아이유', '좋은 날; Good Day', '아이유; IU', null, null, null, 230, 'DB 곡'],
|
||||
[2, 'https://youtu.be/lovedive001', '곡 2', '가수 2', '곡 2', '가수 2', null, null, null, 200, '제목·가수 확인 필요 (영상 제목 형식이 달라 채널 이름을 가수로 씀)'],
|
||||
[3, 'https://youtu.be/hypeboy0001', '곡 6', '가수 6', '곡 6', '가수 6', null, null, null, 200, '확인 필요: NewJeans - Hype Boy'],
|
||||
[4, 'https://youtu.be/ditto000001', '곡 7', '가수 7', '곡 7', '가수 7', null, null, null, null, '유튜브 뮤직에서 찾음'],
|
||||
[1, 'https://youtu.be/goodday0001', '좋은 날', '아이유', 'Good Day', 'IU', null, null, null, 230, 'DB 곡'],
|
||||
[2, 'https://youtu.be/lovedive001', '곡 2', '가수 2', null, null, null, null, null, 200, '제목·가수 확인 필요 (영상 제목 형식이 달라 채널 이름을 가수로 씀)'],
|
||||
[3, 'https://youtu.be/hypeboy0001', '곡 6', '가수 6', null, null, null, null, null, 200, '확인 필요: NewJeans - Hype Boy'],
|
||||
[4, 'https://youtu.be/ditto000001', '곡 7', '가수 7', null, null, null, null, null, null, '유튜브 뮤직에서 찾음'],
|
||||
]);
|
||||
expect(sheets[1]!.rows.slice(1)).toEqual([
|
||||
[3, 'https://youtu.be/blocked0001', '원래 3', '채널', '다른 사이트 재생이 막힌 영상'],
|
||||
|
||||
@@ -201,8 +201,8 @@ export function parseQuizRows(rows: string[][], columns: (QuizColumn | null)[],
|
||||
const own = (start !== null && start !== undefined) || (highlight !== null && highlight !== undefined);
|
||||
const fromStart = !own && blank === 'start';
|
||||
const length = parseSec(cell(r, at('duration')));
|
||||
const clean = cleanTitle(title);
|
||||
const artist = cell(r, at('desc')).slice(0, 200);
|
||||
const clean = cleanTitle(title, artist);
|
||||
const written = splitAnswers(cell(r, at('answers')));
|
||||
const writtenArtist = splitAnswers(cell(r, at('descAnswers')));
|
||||
out.push({
|
||||
@@ -321,8 +321,9 @@ export function playlistSheets(list: PlaylistSheetRow[], kind: QuizKind = 'norma
|
||||
else
|
||||
kept.push([
|
||||
...head,
|
||||
[r.title, ...(r.titleAnswers ?? []).filter((a) => a !== r.title)].join('; '),
|
||||
[r.artist, ...(r.artistAnswers ?? []).filter((a) => a !== r.artist)].filter(Boolean).join('; '),
|
||||
// the title and the artist always count without being written: only the other names (an empty cell is filled on import)
|
||||
(r.titleAnswers ?? []).filter((a) => a !== r.title).join('; ') || null,
|
||||
(r.artistAnswers ?? []).filter((a) => a !== r.artist).join('; ') || null,
|
||||
null,
|
||||
...tail,
|
||||
]);
|
||||
|
||||
@@ -28,6 +28,13 @@ describe('제목 정리 (docs/13)', () => {
|
||||
expect(cleanTitle('광(狂)').title).toBe('광');
|
||||
expect(cleanTitle('미스터 (Mr.)')).toEqual({ title: '미스터', aliases: [] });
|
||||
});
|
||||
test("the singer's name in brackets is not another name of the song (Crank That (Soulja Boy))", () => {
|
||||
expect(cleanTitle('Crank That (Soulja Boy)', 'Soulja Boy')).toEqual({ title: 'Crank That', aliases: [] });
|
||||
expect(cleanTitle('레이 (LAY)', '레이 (LAY), Alan Walker')).toEqual({ title: '레이', aliases: [] });
|
||||
expect(cleanTitle('Still D.R.E. (Dr. Dre)', 'Dr. Dre, Snoop Dogg').aliases).toEqual([]);
|
||||
// another singer's name stays: it is not this song's credit
|
||||
expect(cleanTitle('사랑을 했다(LOVE SCENARIO)', 'iKON').aliases).toEqual(['LOVE SCENARIO', '사랑을 했다 LOVE SCENARIO']);
|
||||
});
|
||||
test('a leading bracket and a part number stay as words', () => {
|
||||
expect(cleanTitle("(I Can't Help) Falling In Love With You")).toEqual({ title: "I Can't Help Falling In Love With You", aliases: ['Falling In Love With You'] });
|
||||
expect(shown('Love The Way You Lie (Part II) (Feat. Eminem)')).toBe('Love The Way You Lie Part II');
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
* Artist names are left alone ("(여자)아이들", "LE SSERAFIM (르세라핌)").
|
||||
*/
|
||||
|
||||
import { looseKey } from './match-key';
|
||||
|
||||
const PAIRS: Record<string, string> = { '(': ')', '[': ']', '{': '}', '【': '】', '「': '」', '『': '』', '(': ')', '[': ']', '〈': '〉', '《': '》' };
|
||||
const CLOSERS = new Set(Object.values(PAIRS));
|
||||
|
||||
@@ -74,8 +76,24 @@ 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 {
|
||||
/** Each name in an artist credit ("레이 (LAY), Alan Walker" → 레이 (LAY), 레이, LAY, Alan Walker …) as a loose key. */
|
||||
export function creditKeys(artist: string): Set<string> {
|
||||
const out = new Set<string>();
|
||||
for (const part of [artist, ...artist.split(/\s*(?:,|&|\/|·|\sx\s|\bfeat\.?\s|\bwith\s)\s*/i)]) {
|
||||
for (const n of [part, part.replace(/\s*[([(][^)\])]*[)\])]/g, ''), ...[...part.matchAll(/[([(]([^)\])]+)[)\])]/g)].map((m) => m[1]!)]) {
|
||||
const k = looseKey(n);
|
||||
if (k) out.add(k);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Strips brackets, feat. and version marks from a song title; see the file comment. With the song's `artist`, a bracket
|
||||
* that only names its singer ("Crank That (Soulja Boy)", "레이 (LAY)") is a credit, not another name of the song.
|
||||
*/
|
||||
export function cleanTitle(raw: string, artist?: string): CleanTitle {
|
||||
const credit = artist ? creditKeys(artist) : null;
|
||||
const src = squash(raw.normalize('NFC'));
|
||||
let s = src;
|
||||
const dash = DASH_SUFFIX.exec(s);
|
||||
@@ -91,7 +109,7 @@ export function cleanTitle(raw: string): CleanTitle {
|
||||
whole += before;
|
||||
rest += before;
|
||||
at = g.end;
|
||||
if (isTitleNote(g.inner)) {
|
||||
if (isTitleNote(g.inner) || credit?.has(looseKey(g.inner))) {
|
||||
shown += ' ';
|
||||
whole += ' ';
|
||||
rest += ' ';
|
||||
|
||||
Reference in New Issue
Block a user