From da500f489b530e2a06963cfa4be7bc8bc4a628a7 Mon Sep 17 00:00:00 2001 From: EJClaw Date: Wed, 4 Nov 2026 16:33:19 +0900 Subject: [PATCH] =?UTF-8?q?=EC=A0=9C=EB=AA=A9=20=EC=A0=95=EB=A6=AC=204?= =?UTF-8?q?=EB=8B=A8=EA=B3=84:=20=EC=84=9C=EB=B2=84=20DB=20=EA=B3=A1=20?= =?UTF-8?q?=EC=A0=9C=EB=AA=A9=20=EC=A0=95=EB=A6=AC=20=EA=B2=80=ED=86=A0=20?= =?UTF-8?q?=E2=80=94=20title=5Freviews(015),=20songs/title-review.ts(?= =?UTF-8?q?=EB=A7=8C=EB=93=A4=EA=B8=B0=C2=B7=EC=A0=81=EC=9A=A9=C2=B7?= =?UTF-8?q?=EA=B1=B4=EB=84=88=EB=9B=B0=EA=B8=B0=C2=B7=EB=AA=A9=EB=A1=9D),?= =?UTF-8?q?=20cli=20clean-titles(--review:=20=EB=AA=A8=EB=91=90=20?= =?UTF-8?q?=EA=B2=80=ED=86=A0=20=EB=AA=A9=EB=A1=9D=20/=20=EA=B8=B0?= =?UTF-8?q?=EB=B3=B8:=20=EC=83=88=20=EA=B3=A1=EC=9D=80=20=EB=B0=94?= =?UTF-8?q?=EB=A1=9C=20=EB=B0=98=EC=98=81,=20=EC=9D=BC=EB=B3=B8=EC=96=B4?= =?UTF-8?q?=C2=B7=ED=99=95=EC=9D=B8=20=ED=95=84=EC=9A=94=EB=A7=8C=20?= =?UTF-8?q?=EA=B2=80=ED=86=A0),=20=EA=B4=80=EB=A6=AC=EC=9E=90=20=E2=86=92?= =?UTF-8?q?=20=EC=88=98=EC=A7=91=EC=97=90=20'=EC=A0=9C=EB=AA=A9=20?= =?UTF-8?q?=EC=A0=95=EB=A6=AC=C2=B7=EC=A0=95=EB=8B=B5=20=EB=A7=8C=EB=93=A4?= =?UTF-8?q?=EA=B8=B0',=20=EA=B4=80=EB=A6=AC=EC=9E=90=20=E2=86=92=20?= =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20=EC=A0=9C=EB=AA=A9=20=EC=A0=95=EB=A6=AC(?= =?UTF-8?q?=EB=AC=B6=EC=9D=8C=EB=B3=84=20=EB=AA=A9=EB=A1=9D,=20=EC=A0=9C?= =?UTF-8?q?=EB=AA=A9=C2=B7=EA=B0=80=EC=88=98=20=EA=B3=A0=EC=B3=90=EC=84=9C?= =?UTF-8?q?=20=EC=A0=81=EC=9A=A9,=20=EA=B1=B4=EB=84=88=EB=9B=B0=EA=B8=B0,?= =?UTF-8?q?=20=EB=AC=B6=EC=9D=8C=20=EC=A0=84=EC=B2=B4=20=EC=A0=81=EC=9A=A9?= =?UTF-8?q?,=20=EC=B2=98=EB=A6=AC=ED=95=9C=20=EA=B2=83).=20=EC=A0=81?= =?UTF-8?q?=EC=9A=A9=ED=95=98=EB=A9=B4=20=EC=A0=9C=EB=AA=A9=C2=B7=EA=B0=80?= =?UTF-8?q?=EC=88=98=EC=99=80=20=EC=83=88=20=EC=A0=95=EB=8B=B5=C2=B7?= =?UTF-8?q?=EC=9B=90=EB=9E=98=20=EC=9D=B4=EB=A6=84(=EB=B3=84=EC=B9=AD),=20?= =?UTF-8?q?match=5Fkey=EB=8A=94=20=EA=B7=B8=EB=8C=80=EB=A1=9C,=20=EA=B7=B8?= =?UTF-8?q?=EC=82=AC=EC=9D=B4=20=EB=B0=94=EB=80=90=20=EA=B3=A1=EC=9D=80=20?= =?UTF-8?q?=EC=A0=81=EC=9A=A9=20=EC=95=88=20=ED=95=A8.=20=EC=98=81?= =?UTF-8?q?=EC=96=B4=20=EB=B0=9C=EC=9D=8C=20=EB=8B=A4=EB=93=AC=EA=B8=B0(?= =?UTF-8?q?=EC=9A=B4=EC=98=81=20=EC=82=AC=EB=B3=B8=20=ED=91=9C=EB=B3=B8?= =?UTF-8?q?=EC=97=90=EC=84=9C):=20=EC=9E=90=EC=9D=8C=20=EB=92=A4=20l(?= =?UTF-8?q?=ED=94=8C=EB=A0=89=EC=8A=A4=C2=B7=EB=B8=94=EB=A3=A8),=20s+w(?= =?UTF-8?q?=EC=8A=A4=EC=9C=84=ED=8A=B8),=20ts(=EB=A0=9B=EC=B8=A0),=20ow+?= =?UTF-8?q?=EB=AA=A8=EC=9D=8C(=ED=94=8C=EB=9D=BC=EC=9B=8C),=20=EC=B2=A0?= =?UTF-8?q?=EC=9E=90=20o=EC=9D=98=20=C9=91=EB=8A=94=20=E3=85=97(=EC=A1=B4?= =?UTF-8?q?=C2=B7=EC=95=84=EC=9D=B4=EC=BD=98),=20=EC=95=BD=EB=AA=A8?= =?UTF-8?q?=EC=9D=8C=EC=9D=80=20=EC=B2=A0=EC=9E=90=EB=8C=80=EB=A1=9C(?= =?UTF-8?q?=ED=94=84=EB=A1=9C=EB=AF=B8=EC=8A=A4=C2=B7=EC=82=AC=EC=9D=B4?= =?UTF-8?q?=EB=A0=8C),=20=EB=8B=A8=EC=96=B4=20=EB=81=9D=20-sle/-zle(?= =?UTF-8?q?=EC=BA=90=EC=8A=AC),=20=EB=8C=80=EB=AC=B8=EC=9E=90=20=ED=95=9C?= =?UTF-8?q?=20=EA=B8=80=EC=9E=90=EB=8A=94=20=EA=B8=80=EC=9E=90=20=EC=9D=B4?= =?UTF-8?q?=EB=A6=84(=EC=95=8C=20=EC=98=A4=20=EB=94=94),=20=EC=95=84?= =?UTF-8?q?=ED=8F=AC=EC=8A=A4=ED=8A=B8=EB=A1=9C=ED=94=BC=EB=8A=94=20's/'t?= =?UTF-8?q?=20=EB=93=B1=EB=A7=8C.=20=EB=8B=A8=EC=9C=84=C2=B7API=20?= =?UTF-8?q?=ED=85=8C=EC=8A=A4=ED=8A=B8,=20e2e=20admin(=EC=A0=9C=EB=AA=A9?= =?UTF-8?q?=20=EC=A0=95=EB=A6=AC),=20docs=2013?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/server/src/answers/answers.test.ts | 16 +- apps/server/src/answers/en-ko.ts | 57 +++-- apps/server/src/collector/cli.ts | 21 +- apps/server/src/collector/control.ts | 1 + .../src/db/migrations/015_title_reviews.sql | 18 ++ apps/server/src/http/admin-catalog.ts | 31 +++ apps/server/src/songs/title-review.ts | 205 ++++++++++++++++ apps/server/src/title-review.test.ts | 94 +++++++ apps/web/src/pages/admin/AdminApp.tsx | 3 + apps/web/src/pages/admin/TitleReviewsPage.tsx | 232 ++++++++++++++++++ docs/13-title-answers.md | 8 +- e2e/admin.e2e.ts | 29 +++ 12 files changed, 694 insertions(+), 21 deletions(-) create mode 100644 apps/server/src/db/migrations/015_title_reviews.sql create mode 100644 apps/server/src/songs/title-review.ts create mode 100644 apps/server/src/title-review.test.ts create mode 100644 apps/web/src/pages/admin/TitleReviewsPage.tsx diff --git a/apps/server/src/answers/answers.test.ts b/apps/server/src/answers/answers.test.ts index 0badb70..df19e27 100644 --- a/apps/server/src/answers/answers.test.ts +++ b/apps/server/src/answers/answers.test.ts @@ -16,7 +16,21 @@ test('영어 → 한글: 외래어 표기 규칙과 흔히 쓰는 표기', () => 'LOVE DIVE': '러브 다이브', 'Hype Boy': '하이프 보이', 'Cheer Up': '치어 업', - 'Blinding Lights': '브라인딩 라이츠', + 'Blinding Lights': '블라인딩 라이츠', + flex: '플렉스', + 'Bye bye my blue': '바이 바이 마이 블루', + 'Salty & Sweet': '솔티 앤드 스위트', + 'Somehow Somewhere': '섬하우 섬웨어', + "Come On, Let's Go": '컴 온 렛츠 고', + 'R.O.D.': '알 오 디', + Flower: '플라워', + Queen: '퀸', + 'John Fogerty': '존 포저티', + iKON: '아이콘', + 'Promise You': '프로미스 유', + 'Outside Castle': '아우트사이드 캐슬', + "BE'O": '베오', + Twist: '트위스트', 'Mr. Simple': '미스터 심플', 'Shape of You': '셰이프 오브 유', 'Hotel California': '호텔 캘리포니아', diff --git a/apps/server/src/answers/en-ko.ts b/apps/server/src/answers/en-ko.ts index 8172b3f..f68169d 100644 --- a/apps/server/src/answers/en-ko.ts +++ b/apps/server/src/answers/en-ko.ts @@ -29,9 +29,21 @@ const W_GLIDE: Record = { ㅏ: 'ㅘ', ㅓ: 'ㅝ', ㅗ: 'ㅝ', const isVowel = (p: string | undefined) => !!p && p in VOWEL; /** ARPAbet ("P R IY0 T EH1 N D ER0") → Hangul ("프리텐더"). */ -export function arpabetToHangul(arpa: string): string { +/** Vowel letters of each vowel sound, when the spelling and the sounds line up (a silent final e dropped). */ +function vowelLetters(word: string, vowels: number): string[] | null { + const groups = word.toLowerCase().replace(/[^a-z]/g, '').match(/[aeiou]+|y(?![aeiou])(?!^)/g) ?? []; + if (groups.length === vowels) return groups; + if (groups.length === vowels + 1 && /e$/.test(word.toLowerCase())) return groups.slice(0, -1); + return null; +} +/** The unstressed vowel (ə) as its spelling says (Promise 프로미스, Photograph 포토그래프, Siren 사이렌). */ +const SCHWA: Record = { a: 'ㅓ', e: 'ㅔ', i: 'ㅣ', o: 'ㅗ', u: 'ㅓ', y: 'ㅣ' }; + +export function arpabetToHangul(arpa: string, spelling?: string): string { const raw = arpa.trim().split(/\s+/); const ph = raw.map((p) => p.replace(/\d$/, '')); + const letters = spelling ? vowelLetters(spelling, ph.filter((p) => isVowel(p)).length) : null; + let vowelNo = -1; const out: Syl[] = []; let onset: string | null = null; let glide: 'Y' | 'W' | null = null; @@ -40,15 +52,21 @@ export function arpabetToHangul(arpa: string): string { const p = ph[i]!; const next = ph[i + 1]; if (isVowel(p)) { - // "simple", "apple", "little": an unstressed vowel before a final l after a stop is not heard (심플, 애플) - if (raw[i] === 'AH0' && next === 'L' && i + 2 === ph.length && onset && ['ㅍ', 'ㅂ', 'ㅋ', 'ㄱ', 'ㅌ', 'ㄷ'].includes(onset) && !glide) { + vowelNo++; + const letter = letters?.[vowelNo]?.[0]; + // "simple", "apple", "castle": an unstressed vowel before a final l after a stop or s/z/f/v is not heard (심플, 캐슬) + if (raw[i] === 'AH0' && next === 'L' && i + 2 === ph.length && onset && ['ㅍ', 'ㅂ', 'ㅋ', 'ㄱ', 'ㅌ', 'ㄷ', 'ㅅ', 'ㅈ'].includes(onset) && !glide) { out.push({ cho: onset, jung: 'ㅡ', jong: 'ㄹ' }); onset = null; i++; continue; } - // a final schwa reads ㅏ ("drama" → 드라마, "sofa" → 소파) - const vs = raw[i] === 'AH0' && i + 1 === ph.length ? ['ㅏ'] : VOWEL[p]!; + // a final schwa reads ㅏ ("drama" → 드라마, "sofa" → 소파); ow before a vowel glides ("flower" → 플라워, "power" → 파워) + const owGlide = p === 'AW' && isVowel(next); + let vs = raw[i] === 'AH0' && i + 1 === ph.length ? ['ㅏ'] : owGlide ? ['ㅏ'] : VOWEL[p]!; + // spelled o, said ɑ: Korean writes ㅗ (John 존, iKON 아이콘); a schwa follows its letter + if (p === 'AA' && letter === 'o') vs = ['ㅗ']; + else if (raw[i] === 'AH0' && i + 1 < ph.length && letter && SCHWA[letter]) vs = [SCHWA[letter]!]; vs.forEach((v, k) => { let jung = v; let cho = k === 0 ? (onset ?? 'ㅇ') : 'ㅇ'; @@ -57,12 +75,13 @@ export function arpabetToHangul(arpa: string): string { out.push({ cho, jung, jong: ' ' }); }); onset = null; - glide = null; + glide = owGlide ? 'W' : null; // ER before a vowel: its r is heard ("Erica" → 에리카) if (p === 'ER' && isVowel(next)) onset = 'ㄹ'; continue; } - const vowelNext = isVowel(next) || ((next === 'Y' || next === 'W') && isVowel(ph[i + 2])); + // y joins the consonant before it (cute 큐트, music 뮤직); w only after k/g (queen 퀸), else it starts its own syllable (swing 스윙) + const vowelNext = isVowel(next) || ((next === 'Y' || (next === 'W' && (p === 'K' || p === 'G'))) && isVowel(ph[i + 2])); if ((p === 'Y' || p === 'W') && isVowel(next)) { glide = p; continue; @@ -76,6 +95,8 @@ export function arpabetToHangul(arpa: string): string { } // l between vowels doubles ("melon" → 멜론); r doesn't if (p === 'L' && i > 0 && lastVowelEnded() && isVowel(ph[i - 1])) out[out.length - 1]!.jong = 'ㄹ'; + // after a consonant too: flex 플렉스, blue 블루, glad 글래드 + else if (p === 'L' && i > 0 && !isVowel(ph[i - 1]) && ph[i - 1] !== 'L' && lastVowelEnded() && out[out.length - 1]!.jung === 'ㅡ') out[out.length - 1]!.jong = 'ㄹ'; onset = ONSET[p] ?? 'ㅇ'; if (p === 'SH') glide = 'Y'; continue; @@ -90,6 +111,13 @@ export function arpabetToHangul(arpa: string): string { out[out.length - 1]!.jong = CODA[p]!; continue; } + // "lights", "let's": ts → 츠 (렛츠 after a short vowel) + if (p === 'T' && next === 'S' && !isVowel(ph[i + 2])) { + if (lastVowelEnded() && SHORT.has(prev ?? '')) out[out.length - 1]!.jong = 'ㅅ'; + out.push({ cho: 'ㅊ', jung: 'ㅡ', jong: ' ' }); + i++; + continue; + } if (STOP_CODA[p] && lastVowelEnded() && SHORT.has(prev ?? '') && (!next || !['L', 'R', 'M', 'N'].includes(next))) { out[out.length - 1]!.jong = STOP_CODA[p]!; continue; @@ -100,12 +128,7 @@ export function arpabetToHangul(arpa: string): string { continue; } if (p === 'R' || p === 'HH' || p === 'Y' || p === 'W') continue; - // "lights", "cats": ts → 츠 - if (p === 'T' && next === 'S' && !isVowel(ph[i + 2])) { - out.push({ cho: 'ㅊ', jung: 'ㅡ', jong: ' ' }); - i++; - continue; - } + if (p === 'NG') { out.push({ cho: 'ㅇ', jung: 'ㅡ', jong: 'ㅇ' }); continue; @@ -134,7 +157,7 @@ const COMMON: Record = { only: '온리', one: '원', once: '원스', two: '투', three: '쓰리', four: '포', five: '파이브', six: '식스', seven: '세븐', eight: '에잇', nine: '나인', ten: '텐', zero: '제로', hundred: '헌드레드', mr: '미스터', mrs: '미세스', ms: '미즈', dr: '닥터', vs: '버서스', feat: '피처링', tv: '티비', dj: '디제이', mc: '엠씨', ost: '오에스티', ufo: '유에프오', - good: '굿', god: '갓', level: '레벨', angel: '엔젤', idol: '아이돌', hotel: '호텔', eleven: '일레븐', new: '뉴', news: '뉴스', rollin: '롤린', + good: '굿', god: '갓', mars: '마스', and: '앤드', fall: '폴', falling: '폴링', rhythm: '리듬', birthday: '버스데이', level: '레벨', angel: '엔젤', idol: '아이돌', hotel: '호텔', eleven: '일레븐', new: '뉴', news: '뉴스', rollin: '롤린', rhapsody: '랩소디', bohemian: '보헤미안', scenario: '시나리오', spirit: '스피릿', someone: '썸원', something: '썸씽', celebrity: '셀러브리티', without: '위드아웃', california: '캘리포니아', supernova: '슈퍼노바', drama: '드라마', banana: '바나나', energy: '에너지', fantasy: '판타지', memory: '메모리', melody: '멜로디', lady: '레이디', tonight: '투나잇', night: '나이트', @@ -154,14 +177,16 @@ export function wordToHangul(raw: string): string | null { const w = raw.normalize('NFKC').replace(/[’‘`]/g, "'").replace(/^[^A-Za-z0-9]+|[^A-Za-z0-9']+$/g, ''); if (!w) return ''; if (/^\d+$/.test(w)) return w; + // one capital letter is said by its name ("R.O.D." → 알 오 디); "A" alone is the article + if (/^[B-Z]$/.test(w)) return LETTER[w.toLowerCase()]!; const low = w.toLowerCase().replace(/'$/, ''); if (COMMON[low]) return COMMON[low]!; // initials: "BTS", "R.O.C.K", "I.O.U" if (/^(?:[A-Z]\.?){1,6}$/.test(w) && (w.length <= 4 || w.includes('.')) && !dictionary[low]) return [...w.replace(/\./g, '').toLowerCase()].map((c) => LETTER[c]).join(''); const arpa = dictionary[low]; - if (arpa) return arpabetToHangul(arpa); + if (arpa) return arpabetToHangul(arpa, low); // "can't"-style words missing from the dictionary: read the part before the apostrophe - if (low.includes("'")) { + if (/'(?:s|t|ll|re|ve|d|m)$/.test(low)) { const head = dictionary[low.split("'")[0]!]; if (head) return arpabetToHangul(head); } diff --git a/apps/server/src/collector/cli.ts b/apps/server/src/collector/cli.ts index 9ce599f..4ed9077 100644 --- a/apps/server/src/collector/cli.ts +++ b/apps/server/src/collector/cli.ts @@ -12,6 +12,7 @@ * bun apps/server/src/collector/cli.ts age-audio [--limit N] [--delay ms] (연령제한 곡: download their audio with the adult-verified cookie, docs/08 §2-1) * bun apps/server/src/collector/cli.ts levels * bun apps/server/src/collector/cli.ts fix-text (one-off: decode `'`/`&` 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 stats * In the container: docker exec music_quiz-app-1 bun apps/server/src/collector/cli.ts … @@ -23,7 +24,7 @@ import { importSta } from './sta'; import { matchYoutube, reconfirmCandidates, researchYoutube } from './match-youtube'; import { pickSearcher } from './ytmusic'; import { catalogStats } from '../songs/store'; -import { currentJob } from './catalog'; +import { currentJob, Job } from './catalog'; import { collectCharts, fillMelonDetails } from './charts'; import { collectHeatmaps } from './heatmap'; import { collectLoudness } from './loudness'; @@ -31,6 +32,8 @@ import { computeLevels } from './levels'; import { collectAgeAudio } from './age-audio'; import { audioDir } from '../songs/audio'; import { dropVersions, fixEntities } from './text'; +import { buildTitleReviews } from '../songs/title-review'; +import { wikiLookup } from '../answers/wiki'; const [cmd, ...rest] = process.argv.slice(2); const flag = (name: string) => { @@ -97,6 +100,20 @@ switch (cmd) { case 'fix-text': console.log(JSON.stringify(fixEntities(db), null, 1)); break; + case 'clean-titles': { + const job = new Job(db, 'clean-titles'); + try { + const r = await buildTitleReviews(db, { review: rest.includes('--review'), limit: flag('limit'), wiki: wikiLookup(), log: (l) => job.log(l) }); + job.progress(r.songs, r.songs); + job.log(`done: ${r.songs} songs, 검토 ${r.pending}, 바로 반영 ${r.auto}, 바뀔 것 없음 ${r.same}`); + job.finish('done'); + } catch (e) { + job.log(`failed: ${(e as Error).message}`); + job.finish('failed'); + throw e; + } + break; + } case 'drop-versions': { const i = rest.indexOf('--keep'); const keep = i >= 0 ? rest[i + 1]!.split(',').map(Number).filter(Number.isFinite) : []; @@ -109,7 +126,7 @@ switch (cmd) { 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|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|stats'); process.exitCode = 1; } db.close(); diff --git a/apps/server/src/collector/control.ts b/apps/server/src/collector/control.ts index c170c81..c5c616a 100644 --- a/apps/server/src/collector/control.ts +++ b/apps/server/src/collector/control.ts @@ -15,6 +15,7 @@ export const COLLECT_KINDS: CollectControl['kinds'] = [ { id: 'loudness', label: '소리 크기 재기 (유튜브가 잰 곡별 크기)', limit: true }, { id: 'age-audio', label: '연령제한 곡 음원 받기 (성인 인증 계정 쿠키)', limit: true }, { id: 'levels', label: '난이도 다시 계산' }, + { id: 'clean-titles', label: '제목 정리·정답 만들기 (새 곡: 바로 반영, 일본어·확인 필요는 제목 정리 검토로)', limit: true }, ]; const CLI = join(import.meta.dir, 'cli.ts'); diff --git a/apps/server/src/db/migrations/015_title_reviews.sql b/apps/server/src/db/migrations/015_title_reviews.sql new file mode 100644 index 0000000..12f64d5 --- /dev/null +++ b/apps/server/src/db/migrations/015_title_reviews.sql @@ -0,0 +1,18 @@ +-- 제목 정리 검토 (docs/13): the cleaned title/artist and generated answers of each DB song, waiting for an admin (pending) +-- or settled (applied / skipped / auto = applied without review / same = nothing to change). One row per song. +CREATE TABLE title_reviews ( + song_id INTEGER PRIMARY KEY REFERENCES songs(id) ON DELETE CASCADE, + kind TEXT NOT NULL CHECK (kind IN ('title', 'answers', 'japanese', 'check')), + status TEXT NOT NULL CHECK (status IN ('pending', 'applied', 'skipped', 'auto', 'same')), + old_title TEXT NOT NULL, + old_artist TEXT NOT NULL, + new_title TEXT NOT NULL, + new_artist TEXT NOT NULL, + title_answers TEXT NOT NULL DEFAULT '[]', + artist_answers TEXT NOT NULL DEFAULT '[]', + note TEXT, + created_at INTEGER NOT NULL, + decided_at INTEGER, + decided_by TEXT +); +CREATE INDEX title_reviews_status ON title_reviews(status, kind); diff --git a/apps/server/src/http/admin-catalog.ts b/apps/server/src/http/admin-catalog.ts index e3e0841..f0ef5aa 100644 --- a/apps/server/src/http/admin-catalog.ts +++ b/apps/server/src/http/admin-catalog.ts @@ -7,6 +7,7 @@ import { z } from 'zod'; import type { Role } from '@mq/shared'; import type { AdminDeps } from './admin'; import { genreList, listSongs, type SongFilter } from '../songs/store'; +import { TITLE_REVIEW_KINDS, applyTitleReviews, listTitleReviews, skipTitleReviews, type TitleReviewKind } from '../songs/title-review'; import { addGenre, bulk, @@ -293,6 +294,36 @@ export function mountCatalogAdmin( return c.json({ ok: true }); }); + // ------------------------------------------------------------ 제목 정리 검토 (docs/13) + const kindIds = TITLE_REVIEW_KINDS.map((k) => k.id) as [TitleReviewKind, ...TitleReviewKind[]]; + app.get('/title-reviews', (c) => { + const kind = kindIds.includes(c.req.query('kind') as TitleReviewKind) ? (c.req.query('kind') as TitleReviewKind) : undefined; + const r = listTitleReviews(d.db, { kind, status: c.req.query('status') === 'done' ? 'done' : 'pending', page: Number(c.req.query('page') ?? 0) || 0 }); + return c.json({ ...r, kinds: TITLE_REVIEW_KINDS }); + }); + app.post('/title-reviews/apply', async (c) => { + const p = z + .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(), + }) + .refine((x) => x.ids?.length || x.kind, '곡이나 묶음을 골라 주세요.') + .safeParse(await h.body(c)); + if (!p.success) return c.json({ error: '곡이나 묶음을 골라 주세요.' }, 400); + const r = applyTitleReviews(d.db, p.data, h.actor(c)); + d.audit.log(h.actor(c), 'title-review.apply', p.data.kind ?? null, null, { ids: p.data.ids?.length ?? null, kind: p.data.kind ?? null, applied: r.applied }); + d.onCatalogChange?.(); + return c.json(r); + }); + app.post('/title-reviews/skip', async (c) => { + const p = z.object({ ids: z.array(z.number().int()).min(1).max(5000) }).safeParse(await h.body(c)); + if (!p.success) return c.json({ error: '곡을 골라 주세요.' }, 400); + const n = skipTitleReviews(d.db, p.data.ids, h.actor(c)); + d.audit.log(h.actor(c), 'title-review.skip', null, null, { ids: p.data.ids.length, skipped: n }); + return c.json({ skipped: n }); + }); + // ------------------------------------------------------------ collect (수집 실행·멈추기·기록) app.get('/collect', (c) => { const jobs = d.db diff --git a/apps/server/src/songs/title-review.ts b/apps/server/src/songs/title-review.ts new file mode 100644 index 0000000..5161494 --- /dev/null +++ b/apps/server/src/songs/title-review.ts @@ -0,0 +1,205 @@ +/** + * 제목 정리 검토 (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). + * 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. + */ +import type { Database } from 'bun:sqlite'; +import { hasJapanese } from '../answers/ja-reading'; +import { songAnswersBatch, type AnswerOptions } from '../answers'; + +export type TitleReviewKind = 'title' | 'answers' | 'japanese' | 'check'; +export const TITLE_REVIEW_KINDS: { id: TitleReviewKind; label: string }[] = [ + { id: 'title', label: '제목·가수 정리' }, + { id: 'answers', label: '정답(한글 발음 등)만 추가' }, + { id: 'japanese', label: '일본어 곡' }, + { id: 'check', label: '확인 필요' }, +]; + +export interface TitleReviewRow { + songId: number; + kind: TitleReviewKind; + status: string; + oldTitle: string; + oldArtist: string; + newTitle: string; + newArtist: string; + titleAnswers: string[]; + artistAnswers: string[]; + note: string | null; +} + +interface SongRow { + id: number; + title: string; + artist: string; +} + +/** Answers the song does not have yet (its aliases and its shown names count as had). */ +function newAnswers(db: Database, songId: number, part: 'title' | 'artist', list: string[], shown: string[]): string[] { + const had = new Set([...db.query<{ alias: string }, [number, string]>('SELECT alias FROM song_aliases WHERE song_id = ? AND part = ?').all(songId, part).map((r) => r.alias.toLowerCase()), ...shown.map((s) => s.toLowerCase())]); + return list.filter((a) => !had.has(a.toLowerCase())); +} + +/** + * Makes review rows for songs that have none yet (or `ids`). Returns counts. Batches of 300: one Japanese reading + * process and one Wikipedia request per 50 Japanese names each. + */ +export async function buildTitleReviews( + db: Database, + opts: AnswerOptions & { review?: boolean; ids?: number[]; limit?: number; log?: (s: string) => void; now?: number } = {}, +): Promise<{ songs: number; same: number; pending: number; auto: number }> { + const now = opts.now ?? Date.now(); + const rows = opts.ids + ? db.query(`SELECT id, title, artist FROM songs WHERE deleted_at IS NULL AND id IN (${opts.ids.map(Number).join(',') || '0'})`).all() + : db + .query( + 'SELECT s.id, s.title, s.artist FROM songs s WHERE s.deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM title_reviews r WHERE r.song_id = s.id) ORDER BY s.id LIMIT ?', + ) + .all(opts.limit ?? 1_000_000); + const out = { songs: rows.length, same: 0, pending: 0, auto: 0 }; + const save = db.query( + `INSERT INTO title_reviews (song_id, kind, status, old_title, old_artist, new_title, new_artist, title_answers, artist_answers, note, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(song_id) DO UPDATE SET kind = excluded.kind, status = excluded.status, old_title = excluded.old_title, old_artist = excluded.old_artist, + new_title = excluded.new_title, new_artist = excluded.new_artist, title_answers = excluded.title_answers, artist_answers = excluded.artist_answers, + note = excluded.note, created_at = excluded.created_at, decided_at = NULL, decided_by = NULL`, + ); + for (let i = 0; i < rows.length; i += 300) { + const chunk = rows.slice(i, i + 300); + const answers = await songAnswersBatch( + db, + chunk.map((s) => ({ title: s.title, artist: s.artist, songId: s.id })), + { korean: true, wiki: opts.wiki, read: opts.read }, + ); + db.transaction(() => { + chunk.forEach((s, k) => { + const a = answers[k]!; + 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) { + 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' : hasJapanese(s.title) || hasJapanese(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') { + applyOne(db, s.id, null, 'auto', now); + out.auto++; + } else out.pending++; + }); + })(); + opts.log?.(`제목 정리 ${Math.min(i + 300, rows.length)}/${rows.length}: 검토 ${out.pending}, 바로 반영 ${out.auto}, 바뀔 것 없음 ${out.same}`); + } + return out; +} + +const parse = (s: string) => JSON.parse(s) as 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 { + 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 = ?', + ) + .get(songId); + if (!r) return '검토 항목이 없어요'; + const s = db.query<{ title: string; artist: string; deleted_at: number | null }, [number]>('SELECT title, artist, deleted_at FROM songs WHERE id = ?').get(songId); + if (!s || s.deleted_at) return '지워진 곡이에요'; + if (s.title !== r.old_title || s.artist !== r.old_artist) return '그사이 제목·가수가 바뀐 곡이에요 (다시 만들기로 새로 확인해 주세요)'; + const title = edit?.title?.trim() || r.new_title; + const artist = edit?.artist?.trim() || r.new_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)); + db.query('UPDATE title_reviews SET status = ?, new_title = ?, new_artist = ?, decided_at = ?, decided_by = ? WHERE song_id = ?').run( + by === 'auto' ? 'auto' : 'applied', + title, + artist, + now, + by, + songId, + ); + return null; +} + +/** 적용: 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 }[] }, + by: string, + now = Date.now(), +): { applied: number; failed: { id: number; why: string }[] } { + const ids = p.ids?.length + ? p.ids + : p.kind + ? db.query<{ song_id: number }, [string]>("SELECT song_id FROM title_reviews WHERE status = 'pending' AND kind = ?").all(p.kind).map((r) => r.song_id) + : []; + const edits = new Map((p.edits ?? []).map((e) => [e.id, e])); + const failed: { id: number; why: string }[] = []; + let applied = 0; + db.transaction(() => { + for (const id of ids) { + const st = db.query<{ status: string }, [number]>('SELECT status FROM title_reviews WHERE song_id = ?').get(id)?.status; + if (st !== 'pending') { + failed.push({ id, why: '검토를 기다리는 곡이 아니에요' }); + continue; + } + const why = applyOne(db, id, edits.get(id) ?? null, by, now); + if (why) failed.push({ id, why }); + else applied++; + } + })(); + return { applied, failed }; +} + +export function skipTitleReviews(db: Database, ids: number[], by: string, now = Date.now()): number { + if (!ids.length) return 0; + return db + .query(`UPDATE title_reviews SET status = 'skipped', decided_at = ?, decided_by = ? WHERE status = 'pending' AND song_id IN (${ids.map(() => '?').join(',')})`) + .run(now, by, ...ids).changes; +} + +/** The list for 관리자 → 제목 정리 (pending by default), with counts per kind. */ +export function listTitleReviews(db: Database, f: { kind?: TitleReviewKind; status?: 'pending' | 'done'; page?: number; size?: number }) { + const size = Math.min(200, f.size ?? 100); + const status = f.status === 'done' ? "r.status IN ('applied','skipped','auto')" : "r.status = 'pending'"; + const where = `${status} AND s.deleted_at IS NULL${f.kind ? ' AND r.kind = ?' : ''}`; + const args = f.kind ? [f.kind] : []; + const rows = db + .query, (string | number)[]>( + `SELECT r.* FROM title_reviews r JOIN songs s ON s.id = r.song_id WHERE ${where} ORDER BY r.song_id LIMIT ? OFFSET ?`, + ) + .all(...args, size, (f.page ?? 0) * size) + .map( + (r): TitleReviewRow => ({ + songId: r.song_id as number, + kind: r.kind as TitleReviewKind, + status: r.status as string, + oldTitle: r.old_title as string, + oldArtist: r.old_artist as string, + newTitle: r.new_title as string, + newArtist: r.new_artist as string, + titleAnswers: parse(r.title_answers as string), + artistAnswers: parse(r.artist_answers as string), + note: (r.note as string | null) ?? null, + }), + ); + const counts = Object.fromEntries( + db + .query<{ kind: string; n: number }, []>(`SELECT r.kind, COUNT(*) n FROM title_reviews r JOIN songs s ON s.id = r.song_id WHERE ${status} AND s.deleted_at IS NULL GROUP BY r.kind`) + .all() + .map((x) => [x.kind, x.n]), + ); + const total = db.query<{ n: number }, (string | number)[]>(`SELECT COUNT(*) n FROM title_reviews r JOIN songs s ON s.id = r.song_id WHERE ${where}`).get(...args)!.n; + return { rows, counts, total }; +} diff --git a/apps/server/src/title-review.test.ts b/apps/server/src/title-review.test.ts new file mode 100644 index 0000000..ce6e301 --- /dev/null +++ b/apps/server/src/title-review.test.ts @@ -0,0 +1,94 @@ +/** 제목 정리 검토 (docs/13): DB songs get cleaned names and generated answers — reviewed first, new songs at once. */ +import { expect, test } from 'bun:test'; +import { openDb } from './db'; +import { tempDbPath, boot, api, discordLogin, guest, TEST_SUPERADMINS } from './test-utils'; +import { Catalog } from './collector/catalog'; +import { applyTitleReviews, buildTitleReviews, listTitleReviews, skipTitleReviews } from './songs/title-review'; +import { isCorrect } from '@mq/shared'; +import { quizSong } from './songs/quiz'; + +const wiki = async (names: string[]) => new Map(names.flatMap((n): [string, string][] => (n === '夜に駆ける' ? [[n, '밤을 달리다']] : n === 'YOASOBI' ? [] : []))); + +function seed() { + const db = openDb(tempDbPath()); + const c = new Catalog(db); + const add = (title: string, artist: string) => c.upsert({ title, artists: [{ name: artist }], source: 't', ref: title })[0]!; + return { + db, + ids: { + bracket: add('사랑을 했다(LOVE SCENARIO)', '아이콘'), + feat: add('Finesse (Feat. Cardi B)', 'Bruno Mars'), + english: add('Pretender', 'Official髭男dism'), + ja: add('夜に駆ける', 'YOASOBI'), + plain: add('좋은 날', '아이유'), + }, + }; +} + +test('first run (--review): everything that would change waits; nothing is written to the songs yet', async () => { + const { db, ids } = seed(); + const r = await buildTitleReviews(db, { review: true, wiki }); + expect(r).toEqual({ songs: 5, same: 1, pending: 4, auto: 0 }); + 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.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: '확인 필요' }); + expect(row(ids.ja)).toMatchObject({ kind: 'japanese', newTitle: '밤을 달리다', newArtist: 'YOASOBI' }); + expect(list.counts).toEqual({ title: 2, japanese: 1, check: 1 }); + expect(db.query<{ title: string }, [number]>('SELECT title FROM songs WHERE id = ?').get(ids.bracket)!.title).toBe('사랑을 했다(LOVE SCENARIO)'); + // a second run does not ask again + expect((await buildTitleReviews(db, { review: true, wiki })).songs).toBe(0); +}); + +test('적용: names and answers written (the old name stays an answer), the game accepts them; 건너뛰기; edited songs are not applied', async () => { + const { db, ids } = seed(); + await buildTitleReviews(db, { review: true, wiki }); + // an admin renamed this one meanwhile + db.query("UPDATE songs SET title = 'Finesse!' WHERE id = ?").run(ids.feat); + const r = applyTitleReviews(db, { kind: 'title' }, 'admin'); + expect(r).toEqual({ applied: 1, failed: [{ id: ids.feat, why: '그사이 제목·가수가 바뀐 곡이에요 (다시 만들기로 새로 확인해 주세요)' }] }); + const song = quizSong(db, ids.bracket)!; + expect(song.title).toBe('사랑을 했다'); + const st = { space: false, number: true, symbol: false }; + for (const t of ['사랑을 했다', 'love scenario', '러브 시나리오', '사랑을 했다(LOVE SCENARIO)']) expect([t, isCorrect(t, song, 'title', st)]).toEqual([t, true]); + // the Japanese song with an admin's edit of the shown title + expect(applyTitleReviews(db, { ids: [ids.ja], edits: [{ id: ids.ja, title: '밤을 달리다!' }] }, 'admin').applied).toBe(1); + const ja = quizSong(db, ids.ja)!; + expect(ja.title).toBe('밤을 달리다!'); + for (const t of ['夜に駆ける', '요루니 카케루', '밤을 달리다']) expect([t, isCorrect(t, ja, 'title', st)]).toEqual([t, true]); + expect(skipTitleReviews(db, [ids.english], 'admin')).toBe(1); + // only the song renamed meanwhile still waits + expect(listTitleReviews(db, {}).rows.map((x) => x.songId)).toEqual([ids.feat]); + expect(listTitleReviews(db, { status: 'done' }).total).toBe(3); +}); + +test('new songs (no --review): applied at once, Japanese and 확인 필요 ones wait', async () => { + const { db, ids } = seed(); + const r = await buildTitleReviews(db, { wiki }); + expect(r).toEqual({ songs: 5, same: 1, pending: 2, auto: 2 }); + expect(db.query<{ title: string }, [number]>('SELECT title FROM songs WHERE id = ?').get(ids.feat)!.title).toBe('Finesse'); + expect(listTitleReviews(db, {}).rows.map((x) => x.songId).sort()).toEqual([ids.english, ids.ja].sort()); +}); + +test('관리자 API: list, apply a kind, skip; guests may not', async () => { + const s = boot({ discordExchange: async (code: string) => ({ id: code, username: 'u', global_name: '관리', avatar: null }) }, { DISCORD_CLIENT_ID: 'cid', DISCORD_CLIENT_SECRET: 'sec' }); + try { + const c = new Catalog(s.db); + const [id] = c.upsert({ title: 'Seven (feat. Latto) - Clean Ver.', artists: [{ name: '정국' }], source: 't', ref: '1' }); + await buildTitleReviews(s.db, { review: true, wiki }); + const cookie = (await discordLogin(s.base, TEST_SUPERADMINS[0])).cookie!; + const list = await api(s.base, '/api/admin/title-reviews', { cookie }); + expect(list.body.counts).toEqual({ title: 1 }); + expect(list.body.rows[0]).toMatchObject({ songId: id, newTitle: 'Seven', titleAnswers: ['세븐'] }); + const r = await api(s.base, '/api/admin/title-reviews/apply', { method: 'POST', cookie, body: JSON.stringify({ kind: 'title' }) }); + expect(r.body).toEqual({ applied: 1, failed: [] }); + expect((await api(s.base, '/api/admin/title-reviews/skip', { method: 'POST', cookie, body: JSON.stringify({ ids: [id] }) })).body).toEqual({ skipped: 0 }); + const g = await guest(s.base, '손님'); + expect((await api(s.base, '/api/admin/title-reviews', { cookie: g.cookie })).res.status).toBe(403); + } finally { + await s.stop(); + } +}); diff --git a/apps/web/src/pages/admin/AdminApp.tsx b/apps/web/src/pages/admin/AdminApp.tsx index 84d6ebc..683b7f6 100644 --- a/apps/web/src/pages/admin/AdminApp.tsx +++ b/apps/web/src/pages/admin/AdminApp.tsx @@ -12,6 +12,7 @@ import { SongsPage } from './SongsPage'; import { YoutubePage } from './YoutubePage'; import { QuizEditor, QuizzesPage } from './QuizzesPage'; import { ReviewsPage } from './ReviewsPage'; +import { TitleReviewsPage } from './TitleReviewsPage'; import { useReviewCount } from './reviewCount'; import { ArtistsPage, CollectPage, GenresPage, RoomsPage, StatsPage } from './AdminMore'; import { RoomSettings, type CatalogMeta } from '../../components/RoomSettings'; @@ -82,6 +83,7 @@ function AdminShell({ role, isSuper }: { role: Role; isSuper: boolean }) { 🎤 가수 🏷 장르 📥 수집 + ✏️ 제목 정리 📈 통계
퀴즈
📋 퀴즈 @@ -101,6 +103,7 @@ function AdminShell({ role, isSuper }: { role: Role; isSuper: boolean }) { } /> } /> } /> + } /> } /> } /> } /> diff --git a/apps/web/src/pages/admin/TitleReviewsPage.tsx b/apps/web/src/pages/admin/TitleReviewsPage.tsx new file mode 100644 index 0000000..9b80478 --- /dev/null +++ b/apps/web/src/pages/admin/TitleReviewsPage.tsx @@ -0,0 +1,232 @@ +/** + * 관리자 → 제목 정리 (docs/13): DB songs whose shown title/artist would be cleaned (brackets, feat., version marks, + * J-POP Korean names) or that get new answers (한글 발음, 일본어 원어·읽는 소리). Grouped by kind; each row can be edited, + * applied or skipped, and a whole group applied at once. The list is made by 관리자 → 수집 → 제목 정리·정답 만들기. + */ +import { useCallback, useEffect, useState } from 'react'; +import { apiCall } from '../../net/api'; +import { toast } from '../../store/toast'; +import { ConfirmSheet } from '../../components/ui'; + +type Kind = 'title' | 'answers' | 'japanese' | 'check'; +interface Row { + songId: number; + kind: Kind; + status: string; + oldTitle: string; + oldArtist: string; + newTitle: string; + newArtist: string; + titleAnswers: string[]; + artistAnswers: string[]; + note: string | null; +} +interface ListResp { + rows: Row[]; + counts: Partial>; + total: number; + kinds: { id: Kind; label: string }[]; +} +const STATUS: Record = { applied: '적용', skipped: '건너뜀', auto: '바로 반영' }; + +export function TitleReviewsPage() { + const [kind, setKind] = useState('title'); + const [done, setDone] = useState(false); + const [page, setPage] = useState(0); + const [data, setData] = useState(null); + const [pick, setPick] = useState>(new Set()); + const [edits, setEdits] = useState>({}); + const [busy, setBusy] = useState(false); + const [confirmAll, setConfirmAll] = useState(false); + const load = useCallback(() => { + apiCall('GET', `/api/admin/title-reviews?kind=${kind}&page=${page}${done ? '&status=done' : ''}`) + .then((r) => { + setData(r); + setPick(new Set()); + }) + .catch((e: Error) => toast(e.message, 'error')); + }, [kind, page, done]); + useEffect(load, [load]); + const act = async (path: 'apply' | 'skip', body: Record) => { + setBusy(true); + try { + const r = await apiCall<{ applied?: number; skipped?: number; failed?: { id: number; why: string }[] }>('POST', `/api/admin/title-reviews/${path}`, body); + if (path === 'apply') toast(`${r.applied}곡에 적용했어요${r.failed?.length ? ` (${r.failed.length}곡은 못 함: ${r.failed[0]!.why})` : ''}.`, r.failed?.length ? 'error' : undefined); + else toast(`${r.skipped}곡을 건너뛰었어요.`); + setEdits({}); + load(); + } catch (e) { + toast((e as Error).message, 'error'); + } finally { + setBusy(false); + } + }; + const rows = data?.rows ?? []; + const chosen = [...pick]; + const editList = (ids: number[]) => ids.filter((id) => edits[id]).map((id) => ({ id, ...edits[id] })); + const label = (k: Kind) => data?.kinds.find((x) => x.id === k)?.label ?? k; + const pages = Math.ceil((data?.total ?? 0) / 100); + return ( + <> +

제목 정리

+

+ 서버 노래 DB 곡의 제목에서 괄호·feat.·버전 표시를 지우고, 한글 발음·일본어 원어 같은 정답을 더해요. 적용하면 바뀐 제목·가수가 보이고, 원래 이름과 새 정답은 모두 + 정답으로 인정돼요. 목록은 수집 → 제목 정리·정답 만들기로 만들어요(새 곡은 바로 반영되고 일본어·확인 필요 곡만 여기로 와요). +

+
+ {(data?.kinds ?? []).map((k) => ( + + ))} + +
+ {!done && rows.length > 0 && ( +
+ + + +
+ )} + {data && rows.length === 0 &&

{done ? '아직 처리한 곡이 없어요.' : '이 묶음에는 검토할 곡이 없어요.'}

} + {rows.length > 0 && ( +
+ + + + {!done && ( + + )} + + + + + + + + {rows.map((r) => ( + + {!done && ( + + )} + + + + + + ))} + +
+ 0 && rows.every((r) => pick.has(r.songId))} + onChange={(e) => setPick(e.target.checked ? new Set(rows.map((r) => r.songId)) : new Set())} + /> + 지금바뀔 제목 · 가수더해질 정답{done ? '처리' : '비고'}
+ + setPick((cur) => { + const n = new Set(cur); + if (e.target.checked) n.add(r.songId); + else n.delete(r.songId); + return n; + }) + } + /> + + {r.oldTitle} +
{r.oldArtist}
+
+ {done ? ( + <> + {r.newTitle} +
{r.newArtist}
+ + ) : ( +
+ setEdits((cur) => ({ ...cur, [r.songId]: { ...cur[r.songId], title: e.target.value } }))} + /> + setEdits((cur) => ({ ...cur, [r.songId]: { ...cur[r.songId], artist: e.target.value } }))} + /> +
+ )} +
+ {r.titleAnswers.length > 0 &&
제목: {r.titleAnswers.join(', ')}
} + {r.artistAnswers.length > 0 &&
가수: {r.artistAnswers.join(', ')}
} + {!r.titleAnswers.length && !r.artistAnswers.length && -} +
+ {done ? ( + {STATUS[r.status] ?? r.status} + ) : ( +
+ {r.note && {r.note}} +
+ + +
+
+ )} +
+
+ )} + {pages > 1 && ( +
+ + + {page + 1} / {pages} + + +
+ )} + {confirmAll && ( + setConfirmAll(false)} + onConfirm={() => { + setConfirmAll(false); + void act('apply', { kind, edits: editList(rows.map((r) => r.songId)) }); + }} + /> + )} + + ); +} diff --git a/docs/13-title-answers.md b/docs/13-title-answers.md index f77a21c..edfc652 100644 --- a/docs/13-title-answers.md +++ b/docs/13-title-answers.md @@ -31,8 +31,12 @@ - wiki.ts: 일본어 위키백과 → 한국어 문서 이름(50개씩, 넘겨주기 따라감) - index.ts songAnswersBatch: `korean` 옵션이면 일본어 제목·가수를 한글 이름으로 보여 줌(위키백과 → 괄호 안 한글 → 읽는 소리 '한글 이름 자동 변환' → '확인 필요') - 플레이리스트 가져오기·재생목록 엑셀: korean + 위키백과, 파일 정답 채우기: 이름은 그대로 두고 정답만 -4. [ ] 적용: 플레이리스트 가져오기·재생목록 엑셀·수집(새 곡)·서버 DB 정리 검토 목록(관리자) -5. [ ] 배포: DB 백업 → `drop-versions --dry-run --keep 7985,9066` 확인 → 실행 → 제목 정리 검토 목록 +4. [x] 서버 DB 적용: 제목 정리 검토 (`songs/title-review.ts`, 015 마이그레이션 `title_reviews`, 관리자 → ✏️ 제목 정리 `/admin/titles`) + - `cli.ts clean-titles --review`: 처음 한 번, 바뀔 곡 전부 검토 목록(묶음: 제목·가수 정리 / 정답만 추가 / 일본어 곡 / 확인 필요) + - `cli.ts clean-titles`(관리자 → 수집 버튼, cron): 아직 안 본 곡(새 곡)만 — 바로 반영, 일본어·확인 필요만 검토 목록 + - 적용: 제목·가수 바꾸고 새 정답과 원래 이름을 song_aliases(source auto)로, match_key는 그대로(차트가 원래 이름으로 찾음). 그사이 바뀐 곡은 적용 안 함 + - 운영 사본(10,762곡) 결과: 제목·가수 정리 614, 정답만 3,641, 일본어 7, 확인 필요 2, 그대로 6,498 — 약 6초 +5. [ ] 배포: DB 백업 → 배포 → `drop-versions --dry-run --keep 7985,9066` 확인 → 실행 → `clean-titles --review` → cron에 `clean-titles`(차트 02:00 뒤, 02:50) ## 운영 DB에서 확인한 숫자 (2026-11-04 사본) - 10,762곡, 제목이 바뀌는 곡 617곡 diff --git a/e2e/admin.e2e.ts b/e2e/admin.e2e.ts index c9e95c3..eb1e63d 100644 --- a/e2e/admin.e2e.ts +++ b/e2e/admin.e2e.ts @@ -10,6 +10,7 @@ import { join } from 'node:path'; import { loadConfig } from '../apps/server/src/config'; import { startServer } from '../apps/server/src/server'; import { Catalog } from '../apps/server/src/collector/catalog'; +import { buildTitleReviews } from '../apps/server/src/songs/title-review'; import type { CookieStatus } from '../apps/server/src/collector/cookie-keeper'; const PORT = Number(process.env.E2E_PORT ?? 4623); @@ -326,6 +327,34 @@ try { db.query("UPDATE collect_jobs SET status = 'done', finished_at = ? WHERE kind = 'match-youtube' AND status = 'running'").run(Date.now()); }); + await step('제목 정리: 묶음별 목록 → 제목 고쳐서 적용, 건너뛰기, 한 묶음 전체 적용 → DB 제목·정답 반영', async () => { + const c = new Catalog(db); + const add = (t: string, a: string) => c.upsert({ title: t, artists: [{ name: a }], source: 'e2e', ref: `tr-${t}` })[0]!; + const ids = [add('사랑을 했다(LOVE SCENARIO)', '아이콘'), add('Finesse (Feat. Cardi B)', 'Bruno Mars'), add('Seven (feat. Latto) - Clean Ver.', '정국'), add('Pretender', '오피셜히게단디즘')]; + await buildTitleReviews(db, { review: true, ids, wiki: async () => new Map() }); + await p.goto(ORIGIN + '/admin/titles'); + await p.getByRole('tab', { name: /제목·가수 정리 \(3\)/ }).waitFor(); + await p.getByRole('tab', { name: /정답\(한글 발음 등\)만 추가 \(1\)/ }).waitFor(); + await p.screenshot({ path: join(SHOTS, 'title-reviews.png'), fullPage: true }); + // edit one before applying, skip another + await p.getByLabel('사랑을 했다(LOVE SCENARIO) 바뀔 제목').fill('사랑을 했다!'); + await p.locator('tr', { hasText: '사랑을 했다(LOVE SCENARIO)' }).getByRole('button', { name: '적용' }).click(); + await p.getByText('1곡에 적용했어요').waitFor(); + await p.locator('tr', { hasText: 'Finesse (Feat. Cardi B)' }).getByRole('button', { name: '건너뛰기' }).click(); + await p.getByText('1곡을 건너뛰었어요').waitFor(); + // the 정답만 group, all at once + await p.getByRole('tab', { name: /정답\(한글 발음 등\)만 추가/ }).click(); + await p.getByRole('button', { name: /전체 적용 \(1곡\)/ }).click(); + await p.getByRole('button', { name: '모두 적용' }).click(); + await p.getByText('이 묶음에는 검토할 곡이 없어요.').waitFor(); + const title = (id: number) => db.query<{ title: string }, [number]>('SELECT title FROM songs WHERE id = ?').get(id)!.title; + const aliases = (id: number) => db.query<{ alias: string }, [number]>("SELECT alias FROM song_aliases WHERE song_id = ? AND part = 'title' ORDER BY alias").all(id).map((r) => r.alias); + expect(title(ids[0]!) === '사랑을 했다!' && aliases(ids[0]!).includes('LOVE SCENARIO') && aliases(ids[0]!).includes('사랑을 했다(LOVE SCENARIO)'), `적용: ${title(ids[0]!)} ${aliases(ids[0]!)}`); + expect(title(ids[1]!) === 'Finesse (Feat. Cardi B)', `건너뛴 곡이 바뀜: ${title(ids[1]!)}`); + expect(title(ids[2]!) === 'Seven (feat. Latto) - Clean Ver.', '다른 묶음 곡이 바뀜'); + expect(aliases(ids[3]!).includes('프리텐더'), `발음 정답: ${aliases(ids[3]!)}`); + }); + await p.goto(ORIGIN + '/admin/songs'); await p.locator('.data-table tbody tr').first().waitFor(); await p.screenshot({ path: join(SHOTS, 'stage8-songs.png'), fullPage: true });