Files
music_quiz/packages/shared/src/quiz-file.test.ts
EJClaw b360ff0eb7 정답: 가수가 제목 정답에 섞이던 것·틀린 한글 발음 정답 고치기 (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>
2026-11-04 20:44:05 +09:00

255 lines
17 KiB
TypeScript

/** 퀴즈 파일: .xlsx / .csv reading and writing, column guessing, rows → quiz songs. */
import { expect, test } from 'bun:test';
import { decodeCsv, parseCsv, readSheetFile, readXlsx, writeXlsx, writeXlsxSheets } from './sheet';
import { deflatedZip } from './zip-fixture';
import { guessColumns, headerRow, parseQuizRows, parseSec, parseVideoId, parseViews, playlistSheets, quizTemplateRows, quizToRows, type PlaylistSheetRow } from './quiz-file';
test('reads an Excel-style workbook: shared strings, rich text, numbers, gaps, sheet order and names', async () => {
const x = deflatedZip({
'xl/workbook.xml': '<workbook xmlns:r="r"><sheets><sheet name="게임별 정렬" sheetId="1" r:id="rId1"/><sheet name="재생목록 &amp; 순서" sheetId="2" r:id="rId2"/></sheets></workbook>',
'xl/_rels/workbook.xml.rels': '<Relationships><Relationship Id="rId2" Target="worksheets/b.xml"/><Relationship Id="rId1" Target="/xl/worksheets/a.xml"/></Relationships>',
'xl/sharedStrings.xml': '<sst><si><t>링크</t></si><si><r><t>게임 </t></r><r><t xml:space="preserve">제목</t></r><rPh><t>げーむ</t></rPh></si><si><t>A&amp;B &lt;1&gt;</t></si></sst>',
'xl/worksheets/a.xml': '<worksheet><sheetData><row r="1"><c r="A1" t="s"><v>0</v></c><c r="C1" t="s"><v>1</v></c></row><row r="3"><c r="A3" t="inlineStr"><is><t>https://youtu.be/iIIjS6yDMQo</t></is></c><c r="B3"><v>74</v></c><c r="C3" t="s"><v>2</v></c></row></sheetData></worksheet>',
'xl/worksheets/b.xml': '<x:worksheet xmlns:x="m"><x:sheetData><x:row><x:c t="str"><x:v>하나</x:v></x:c><x:c t="b"><x:v>1</x:v></x:c></x:row><x:row r="2"/></x:sheetData></x:worksheet>',
});
const sheets = await readXlsx(x);
expect(sheets.map((s) => s.name)).toEqual(['게임별 정렬', '재생목록 & 순서']);
expect(sheets[0]!.rows).toEqual([['링크', '', '게임 제목'], [], ['https://youtu.be/iIIjS6yDMQo', '74', 'A&B <1>']]);
expect(sheets[1]!.rows).toEqual([['하나', 'TRUE']]);
await expect(readXlsx(new Uint8Array([1, 2, 3]))).rejects.toThrow('엑셀');
});
test('writes an .xlsx that reads back the same (numbers, empty cells, symbols, Korean)', async () => {
const rows = [['순번', '정답', '설명'], [1, '리그 오브 레전드', 'Still Here <2024> & "롤드컵"'], [2, null, '']];
const back = await readXlsx(writeXlsx('퀴즈/시트', rows, [6, 30]));
expect(back[0]!.name).toBe('퀴즈 시트');
expect(back[0]!.rows).toEqual([['순번', '정답', '설명'], ['1', '리그 오브 레전드', 'Still Here <2024> & "롤드컵"'], ['2']]);
});
test('CSV: quotes, commas and line breaks inside, tab files, BOM, and Korean Excel (CP949) files', async () => {
expect(parseCsv('링크,정답\r\n"https://youtu.be/x0-xFqvJ-U8","갓 오브 워, 2"\n"줄\n바꿈","따옴표 ""안"""\n\n')).toEqual([
['링크', '정답'],
['https://youtu.be/x0-xFqvJ-U8', '갓 오브 워, 2'],
['줄\n바꿈', '따옴표 "안"'],
]);
expect(parseCsv('링크\t정답\nabc\t가, 나')).toEqual([['링크', '정답'], ['abc', '가, 나']]);
const cp949 = new Uint8Array([0xc1, 0xa4, 0xb4, 0xe4, 0x2c, 0x41]); // "정답,A"
expect(decodeCsv(cp949)).toBe('정답,A');
expect((await readSheetFile('목록.csv', cp949))[0]).toEqual({ name: '목록', rows: [['정답', 'A']] });
await expect(readSheetFile('old.xls', new Uint8Array([0xd0, 0xcf]))).rejects.toThrow('.xls');
});
test('columns are found by their headers (the sent BGM sheet, our export, English)', () => {
expect(guessColumns(['번호', '유튜브 영상 링크', '게임 제목(한글)', '노래 제목', '힌트(게임장르)', '재생목록 순번'])).toEqual([null, 'link', 'answer', 'desc', 'hint', 'order']);
expect(guessColumns(quizToRows([]).rows[0] as string[])).toEqual(['order', 'link', 'answer', 'desc', 'answers', 'descAnswers', 'hint', 'start', 'highlight', 'duration', null]);
// old 일반 퀴즈 files: 정답 is the title, 설명 / 다른 정답 / 설명 다른 정답
expect(guessColumns(['순번', '유튜브 영상 링크', '정답', '설명', '힌트', '다른 정답(;로 구분)', '설명 다른 정답(;로 구분)'])).toEqual(['order', 'link', 'answer', 'desc', 'hint', 'answers', 'descAnswers']);
// new ones (docs/13): 제목 next to 정답 → 정답 lists more answers
expect(guessColumns(['링크', '제목', '가수', '정답', '가수 정답', '비고'])).toEqual(['link', 'answer', 'desc', 'answers', 'descAnswers', null]);
expect(guessColumns(['URL', 'Title', 'Artist', 'Hint 1', 'Hint 2'])).toEqual(['link', 'answer', 'desc', 'hint', 'hint']);
// the header row may sit under a title line
expect(headerRow([['게임 BGM 모음'], ['링크', '정답'], ['x', 'y']])).toBe(1);
});
test('rows → quiz songs: as written, 순번 order, bad links / no answer / repeated videos listed and left out', () => {
const rows = [
['번호', '유튜브 영상 링크', '게임 제목(한글)', '노래 제목', '힌트(게임장르)', '재생목록 순번'],
['1', 'https://youtu.be/iIIjS6yDMQo', '감옥탈출(구토할배)', '트레일러', '방탈출(플래시)', '3'],
['2', 'https://www.youtube.com/watch?v=x0-xFqvJ-U8&t=5', '갓 오브 워 2', 'The End Begins', '확인필요', '1'],
['', '', '', '', '', ''],
['3', 'https://example.com/a', '없음', '', '', '2'],
['4', 'youtu.be/iIIjS6yDMQo', '같은 영상', '', '', '4'],
['5', 'https://youtube.com/shorts/Yz-Af4p_Vv8', '', '설명만', '', '5'],
['6', 'Es6JbQQE79g', '번호 없음', '', '', ''],
];
const p = parseQuizRows(rows, guessColumns(rows[0]!), 0);
expect(p.items.map((i) => [i.videoId, i.title, i.artist, i.hints])).toEqual([
['x0-xFqvJ-U8', '갓 오브 워 2', 'The End Begins', ['확인필요']],
['iIIjS6yDMQo', '감옥탈출', '트레일러', ['방탈출(플래시)']],
['Es6JbQQE79g', '번호 없음', '', []],
]);
expect(p.items.every((i) => i.fromFile && i.songId === null && i.auto)).toBe(true);
expect(p.rows.filter((r) => r.problem).map((r) => [r.line, r.problem])).toEqual([
[5, '유튜브 링크가 아니에요'],
[6, '2번째 줄과 같은 영상이에요'],
[7, '제목이 비어 있어요'],
]);
// the bracket went from the title and stays an answer
expect(p.items[1]!.titleAnswers).toEqual(['구토할배', '감옥탈출 구토할배']);
});
test('일반 퀴즈 파일 (docs/13): 제목 cleaned, 정답 / 가수 정답 as written, empty ones marked for the server to fill', () => {
const rows = [
['링크', '제목', '가수', '정답', '가수 정답'],
['iIIjS6yDMQo', 'Pretender (feat. 누구)', 'Official髭男dism', 'Pretender; 프리텐더', '오피셜히게단디즘'],
['x0-xFqvJ-U8', '사랑을 했다(LOVE SCENARIO)', '아이콘', '', ''],
['Es6JbQQE79g', 'Finesse (Remix)', '', '', ''],
];
const p = parseQuizRows(rows, guessColumns(rows[0]!), 0);
expect(p.items.map((i) => [i.title, i.artist, i.titleAnswers, i.artistAnswers])).toEqual([
['Pretender', 'Official髭男dism', ['프리텐더'], ['오피셜히게단디즘']],
['사랑을 했다', '아이콘', ['LOVE SCENARIO', '사랑을 했다 LOVE SCENARIO'], []],
['Finesse', '', [], []],
]);
expect(p.rows.map((r) => r.fill)).toEqual([
{ title: false, artist: false },
{ title: true, artist: true },
{ title: true, artist: false },
]);
});
test('our export reads back to the same songs (answers, own positions, several hints) and the template is valid', () => {
const items = [
{ songId: null, videoId: 'iIIjS6yDMQo', title: '감옥탈출', artist: '트레일러', titleAnswers: ['구토할배'], artistAnswers: ['trailer'], hints: ['방탈출', '플래시'], fromFile: true, durationSec: null, auto: false, startSec: 12, highlightSec: 61.5, views: null, viewsAuto: null },
{ songId: 3, videoId: 'x0-xFqvJ-U8', title: '갓 오브 워 2', artist: '', titleAnswers: [], artistAnswers: [], hints: [], fromFile: false, durationSec: 200, auto: true, startSec: null, highlightSec: null, views: null, viewsAuto: null },
];
const { rows } = quizToRows(items);
const text = rows.map((r) => r.map((c) => (c === null ? '' : String(c))));
const back = parseQuizRows(text, guessColumns(text[0]!), 0).items;
expect(rows[1]!.slice(2, 6)).toEqual(['감옥탈출', '트레일러', '감옥탈출; 구토할배', '트레일러; trailer']);
expect(back).toEqual([items[0]!, { ...items[1]!, songId: null, fromFile: true }]);
const t = quizTemplateRows().rows.map((r) => r.map((c) => (c === null ? '' : String(c))));
expect(parseQuizRows(t, guessColumns(t[0]!), 0).items).toHaveLength(1);
});
test('video links and times', () => {
expect(parseVideoId('https://youtu.be/VO88htcm09E?si=x')).toBe('VO88htcm09E');
expect(parseVideoId('https://music.youtube.com/watch?v=VO88htcm09E&list=1')).toBe('VO88htcm09E');
expect(parseVideoId('m.youtube.com/watch?v=VO88htcm09E')).toBe('VO88htcm09E');
expect(parseVideoId('https://www.youtube.com/live/VO88htcm09E')).toBe('VO88htcm09E');
expect(parseVideoId('https://example.com/watch?v=VO88htcm09E')).toBeNull();
expect([parseSec('95'), parseSec('1:35'), parseSec('01:01:01'), parseSec('1분 5초'), parseSec(''), parseSec('조금')]).toEqual([95, 95, 3661, 65, null, undefined]);
});
test('조회수 as people write it', () => {
expect(parseViews('1234567')).toBe(1234567);
expect(parseViews('1,234,567')).toBe(1234567);
expect(parseViews('1,234,567회')).toBe(1234567);
expect(parseViews('123만')).toBe(1230000);
expect(parseViews('1.2억')).toBe(120000000);
expect(parseViews('1억 2,345만')).toBe(123450000);
expect(parseViews('3.4M')).toBe(3400000);
expect(parseViews('12K views')).toBe(12000);
expect(parseViews('1.2345E+9')).toBe(1234500000);
expect(parseViews('')).toBeNull();
expect(parseViews('많음')).toBeUndefined();
});
test('이지선다 파일: 제목·가수, 조회수 optional (empty = fetched by the server), export and template read back', () => {
const rows = [
['순번', '유튜브 링크', '제목', '가수', '조회수'],
['2', 'https://youtu.be/iIIjS6yDMQo', '감옥탈출', '트레일러', '1.2억'],
['1', 'x0-xFqvJ-U8', '갓 오브 워', '', '3,456,789'],
['3', 'https://youtu.be/Es6JbQQE79g', '조회수 없음', '누구', ''],
['4', 'https://youtu.be/VO88htcm09E', '이상한 값', '누구', '많음'],
];
const cols = guessColumns(rows[0]!);
expect(cols).toEqual(['order', 'link', 'answer', 'desc', 'views']);
const p = parseQuizRows(rows, cols, 0, 'duel');
expect(p.items.map((i) => [i.title, i.artist, i.views, i.viewsAuto])).toEqual([
['갓 오브 워', '', 3456789, null],
['감옥탈출', '트레일러', 120000000, null],
['조회수 없음', '누구', null, null],
]);
expect(p.rows.filter((r) => r.problem).map((r) => [r.line, r.problem])).toEqual([[5, '조회수를 읽을 수 없어요 (많음)']]);
// export: written numbers come back as written, fetched ones (and empty ones) come back empty
const fetched = { state: 'done' as const, topicId: 'aaaaaaaaaaa', topicViews: 10, mvId: 'bbbbbbbbbbb', mvViews: 20, error: null, at: 1 };
const withAuto = p.items.map((it, i) => (i === 1 ? { ...it, views: 30, viewsAuto: fetched } : it));
const { rows: out } = quizToRows(withAuto, 'duel');
expect(out[0]).toEqual(['순번', '유튜브 영상 링크', '제목', '가수', '조회수', '시작(초)', '하이라이트(초)', '길이(초)', '비고']);
const text = out.map((r) => r.map((c) => (c === null ? '' : String(c))));
expect(parseQuizRows(text, guessColumns(text[0]!), 0, 'duel').items.map((i) => i.views)).toEqual([3456789, null, null]);
// nothing written by hand: no 조회수 column at all
expect(quizToRows([{ ...p.items[2]! }], 'duel').rows[0]).not.toContain('조회수');
// 빈 양식: no 조회수 column, the example row reads back with its views left to the server
const t = quizTemplateRows('duel').rows.map((r) => r.map((c) => (c === null ? '' : String(c))));
expect(t[0]).toEqual(['순번', '유튜브 영상 링크', '제목', '가수', '시작(초)', '하이라이트(초)', '길이(초)', '비고']);
expect(parseQuizRows(t, guessColumns(t[0]!), 0, 'duel').items.map((i) => [i.title, i.views])).toEqual([['라일락', null]]);
});
test('재생목록으로 엑셀 만들기: kept songs with 비고, unplayable / missing / repeated videos on 빠진 곡, read back by 파일로 만들기', async () => {
const row = (p: Partial<PlaylistSheetRow> & { n: number }): PlaylistSheetRow => ({
source: { title: `원래 ${p.n}`, artist: '채널' },
title: `곡 ${p.n}`,
artist: `가수 ${p.n}`,
durationSec: 200,
videoId: null,
status: 'video',
note: '',
...p,
});
const list = [
row({ n: 1, videoId: 'goodday0001', status: 'db', note: '서버 DB 곡 (플레이리스트 영상 사용)', title: '좋은 날', artist: '아이유', durationSec: 230, titleAnswers: ['Good Day'], artistAnswers: ['IU'] }),
row({ n: 2, videoId: 'lovedive001', note: '제목·가수 확인 필요 (영상 제목 형식이 달라 채널 이름을 가수로 씀)' }),
row({ n: 3, videoId: 'blocked0001', status: 'blocked', note: '다른 사이트 재생이 막힌 영상' }),
row({ n: 4, videoId: 'goodday0001', status: 'db' }),
row({ n: 5, status: 'missing', note: '유튜브에서 못 찾았어요' }),
row({ n: 6, videoId: 'hypeboy0001', status: 'check', note: '확인 필요: NewJeans - Hype Boy' }),
row({ n: 7, videoId: 'ditto000001', status: 'found', durationSec: null }),
];
const sheets = playlistSheets(list);
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', 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', '채널', '다른 사이트 재생이 막힌 영상'],
[4, 'https://youtu.be/goodday0001', '원래 4', '채널', '재생목록 1번 곡과 같은 영상'],
[5, '', '원래 5', '채널', '유튜브에서 못 찾았어요'],
]);
const duel = playlistSheets(list, 'duel');
expect(duel[0]!.name).toBe('이지선다');
expect(duel[0]!.rows.slice(0, 2)).toEqual([
['순번', '유튜브 영상 링크', '제목', '가수', '조회수', '시작(초)', '하이라이트(초)', '길이(초)', '비고'],
[1, 'https://youtu.be/goodday0001', '좋은 날', '아이유', null, null, null, 230, 'DB 곡'],
]);
// the files as downloaded: 파일로 만들기 finds the columns by name, and the 빠진 곡 sheet gives no songs
const book = await readSheetFile('재생목록.xlsx', writeXlsxSheets(sheets));
expect(book.map((x) => x.name)).toEqual(['퀴즈', '빠진 곡']);
const cols = guessColumns(book[0]!.rows[0]!);
expect(cols).toEqual(['order', 'link', 'answer', 'desc', 'answers', 'descAnswers', 'hint', 'start', 'highlight', 'duration', null]);
expect(parseQuizRows(book[1]!.rows, guessColumns(book[1]!.rows[headerRow(book[1]!.rows)]!), headerRow(book[1]!.rows)).items).toEqual([]);
const normal = parseQuizRows(book[0]!.rows, cols, 0).items;
expect(normal.map((i) => [i.videoId, i.title, i.artist, i.titleAnswers, i.artistAnswers, i.durationSec, i.auto])).toEqual([
['goodday0001', '좋은 날', '아이유', ['Good Day'], ['IU'], 230, true],
['lovedive001', '곡 2', '가수 2', [], [], 200, true],
['hypeboy0001', '곡 6', '가수 6', [], [], 200, true],
['ditto000001', '곡 7', '가수 7', [], [], null, true],
]);
// the 이지선다 file has the (empty) 조회수 column: 파일로 만들기 picks 이지선다 and leaves the views to the server
const duelBook = await readSheetFile('재생목록.xlsx', writeXlsxSheets(duel));
const duelCols = guessColumns(duelBook[0]!.rows[0]!);
expect(duelCols).toContain('views');
expect(parseQuizRows(duelBook[0]!.rows, duelCols, 0, 'duel').items.map((i) => [i.title, i.artist, i.views, i.durationSec])).toEqual([
['좋은 날', '아이유', null, 230],
['곡 2', '가수 2', null, 200],
['곡 6', '가수 6', null, 200],
['곡 7', '가수 7', null, null],
]);
});
test('시작·하이라이트가 빈 곡: 자동 (start 0 + highlight worked out) or 처음부터 (0 / 0); written values are kept either way', () => {
const rows = [
['링크', '정답', '시작(초)', '하이라이트(초)', '길이'],
['iIIjS6yDMQo', '빈 곡', '', '', '3:20'],
['x0-xFqvJ-U8', '하이라이트만', '', '1:05', ''],
['Es6JbQQE79g', '시작만', '12', '', 'abc'],
];
const cols = guessColumns(rows[0]!);
const pos = (blank: 'auto' | 'start') => parseQuizRows(rows, cols, 0, 'normal', blank).items.map((i) => [i.auto, i.startSec, i.highlightSec, i.durationSec]);
expect(pos('auto')).toEqual([
[true, null, null, 200],
[false, 0, 65, null],
[false, 12, null, null],
]);
expect(pos('start')).toEqual([
[false, 0, 0, 200],
[false, 0, 65, null],
[false, 12, null, null],
]);
});