제목 정리 4단계: 서버 DB 곡 제목 정리 검토 — title_reviews(015), songs/title-review.ts(만들기·적용·건너뛰기·목록), cli clean-titles(--review: 모두 검토 목록 / 기본: 새 곡은 바로 반영, 일본어·확인 필요만 검토), 관리자 → 수집에 '제목 정리·정답 만들기', 관리자 → ✏️ 제목 정리(묶음별 목록, 제목·가수 고쳐서 적용, 건너뛰기, 묶음 전체 적용, 처리한 것). 적용하면 제목·가수와 새 정답·원래 이름(별칭), match_key는 그대로, 그사이 바뀐 곡은 적용 안 함. 영어 발음 다듬기(운영 사본 표본에서): 자음 뒤 l(플렉스·블루), s+w(스위트), ts(렛츠), ow+모음(플라워), 철자 o의 ɑ는 ㅗ(존·아이콘), 약모음은 철자대로(프로미스·사이렌), 단어 끝 -sle/-zle(캐슬), 대문자 한 글자는 글자 이름(알 오 디), 아포스트로피는 's/'t 등만. 단위·API 테스트, e2e admin(제목 정리), docs 13
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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': '호텔 캘리포니아',
|
||||
|
||||
@@ -29,9 +29,21 @@ const W_GLIDE: Record<string, string> = { ㅏ: 'ㅘ', ㅓ: 'ㅝ', ㅗ: 'ㅝ',
|
||||
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<string, string> = { 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<string, string> = {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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');
|
||||
|
||||
18
apps/server/src/db/migrations/015_title_reviews.sql
Normal file
18
apps/server/src/db/migrations/015_title_reviews.sql
Normal file
@@ -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);
|
||||
@@ -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
|
||||
|
||||
205
apps/server/src/songs/title-review.ts
Normal file
205
apps/server/src/songs/title-review.ts
Normal file
@@ -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<SongRow, []>(`SELECT id, title, artist FROM songs WHERE deleted_at IS NULL AND id IN (${opts.ids.map(Number).join(',') || '0'})`).all()
|
||||
: db
|
||||
.query<SongRow, [number]>(
|
||||
'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<Record<string, string | number | null>, (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 };
|
||||
}
|
||||
94
apps/server/src/title-review.test.ts
Normal file
94
apps/server/src/title-review.test.ts
Normal file
@@ -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<string, string>(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();
|
||||
}
|
||||
});
|
||||
@@ -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 }) {
|
||||
<NavLink to="/admin/artists">🎤 가수</NavLink>
|
||||
<NavLink to="/admin/genres">🏷 장르</NavLink>
|
||||
<NavLink to="/admin/collect">📥 수집</NavLink>
|
||||
<NavLink to="/admin/titles">✏️ 제목 정리</NavLink>
|
||||
<NavLink to="/admin/stats">📈 통계</NavLink>
|
||||
<div className="sep">퀴즈</div>
|
||||
<NavLink to="/admin/quizzes">📋 퀴즈</NavLink>
|
||||
@@ -101,6 +103,7 @@ function AdminShell({ role, isSuper }: { role: Role; isSuper: boolean }) {
|
||||
<Route path="songs" element={<SongsPage />} />
|
||||
<Route path="youtube" element={<YoutubePage />} />
|
||||
<Route path="collect" element={<CollectPage />} />
|
||||
<Route path="titles" element={<TitleReviewsPage />} />
|
||||
<Route path="artists" element={<ArtistsPage />} />
|
||||
<Route path="genres" element={<GenresPage />} />
|
||||
<Route path="stats" element={<StatsPage />} />
|
||||
|
||||
232
apps/web/src/pages/admin/TitleReviewsPage.tsx
Normal file
232
apps/web/src/pages/admin/TitleReviewsPage.tsx
Normal file
@@ -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<Record<Kind, number>>;
|
||||
total: number;
|
||||
kinds: { id: Kind; label: string }[];
|
||||
}
|
||||
const STATUS: Record<string, string> = { applied: '적용', skipped: '건너뜀', auto: '바로 반영' };
|
||||
|
||||
export function TitleReviewsPage() {
|
||||
const [kind, setKind] = useState<Kind>('title');
|
||||
const [done, setDone] = useState(false);
|
||||
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 }>>({});
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [confirmAll, setConfirmAll] = useState(false);
|
||||
const load = useCallback(() => {
|
||||
apiCall<ListResp>('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<string, unknown>) => {
|
||||
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 (
|
||||
<>
|
||||
<h1>제목 정리</h1>
|
||||
<p className="muted">
|
||||
서버 노래 DB 곡의 제목에서 괄호·feat.·버전 표시를 지우고, 한글 발음·일본어 원어 같은 정답을 더해요. 적용하면 바뀐 제목·가수가 보이고, 원래 이름과 새 정답은 모두
|
||||
정답으로 인정돼요. 목록은 <b>수집 → 제목 정리·정답 만들기</b>로 만들어요(새 곡은 바로 반영되고 일본어·확인 필요 곡만 여기로 와요).
|
||||
</p>
|
||||
<div className="seg" role="tablist" style={{ maxWidth: 760 }}>
|
||||
{(data?.kinds ?? []).map((k) => (
|
||||
<button
|
||||
key={k.id}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={!done && kind === k.id}
|
||||
className={!done && kind === k.id ? 'on' : ''}
|
||||
onClick={() => (setDone(false), setKind(k.id), setPage(0))}
|
||||
>
|
||||
{k.label} {data && !done ? `(${data.counts[k.id] ?? 0})` : ''}
|
||||
</button>
|
||||
))}
|
||||
<button type="button" role="tab" aria-selected={done} className={done ? 'on' : ''} onClick={() => (setDone(true), setPage(0))}>
|
||||
처리한 것
|
||||
</button>
|
||||
</div>
|
||||
{!done && rows.length > 0 && (
|
||||
<div className="row" style={{ margin: '10px 0' }}>
|
||||
<button type="button" className="btn btn-primary" disabled={busy || !chosen.length} onClick={() => void act('apply', { ids: chosen, edits: editList(chosen) })}>
|
||||
고른 {chosen.length}곡 적용
|
||||
</button>
|
||||
<button type="button" className="btn" disabled={busy || !chosen.length} onClick={() => void act('skip', { ids: chosen })}>
|
||||
고른 곡 건너뛰기
|
||||
</button>
|
||||
<button type="button" className="btn" disabled={busy} onClick={() => setConfirmAll(true)}>
|
||||
'{label(kind)}' 전체 적용 ({data?.total ?? 0}곡)
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{data && rows.length === 0 && <p className="muted">{done ? '아직 처리한 곡이 없어요.' : '이 묶음에는 검토할 곡이 없어요.'}</p>}
|
||||
{rows.length > 0 && (
|
||||
<div className="table-wrap">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
{!done && (
|
||||
<th style={{ width: 36 }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label="이 쪽 모두 고르기"
|
||||
checked={rows.length > 0 && rows.every((r) => pick.has(r.songId))}
|
||||
onChange={(e) => setPick(e.target.checked ? new Set(rows.map((r) => r.songId)) : new Set())}
|
||||
/>
|
||||
</th>
|
||||
)}
|
||||
<th>지금</th>
|
||||
<th>바뀔 제목 · 가수</th>
|
||||
<th>더해질 정답</th>
|
||||
<th>{done ? '처리' : '비고'}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((r) => (
|
||||
<tr key={r.songId}>
|
||||
{!done && (
|
||||
<td>
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label={`${r.oldTitle} 고르기`}
|
||||
checked={pick.has(r.songId)}
|
||||
onChange={(e) =>
|
||||
setPick((cur) => {
|
||||
const n = new Set(cur);
|
||||
if (e.target.checked) n.add(r.songId);
|
||||
else n.delete(r.songId);
|
||||
return n;
|
||||
})
|
||||
}
|
||||
/>
|
||||
</td>
|
||||
)}
|
||||
<td className="small">
|
||||
<b>{r.oldTitle}</b>
|
||||
<div className="muted">{r.oldArtist}</div>
|
||||
</td>
|
||||
<td className="small">
|
||||
{done ? (
|
||||
<>
|
||||
<b>{r.newTitle}</b>
|
||||
<div className="muted">{r.newArtist}</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="stack" style={{ gap: 4, minWidth: 220 }}>
|
||||
<input
|
||||
className="input sm"
|
||||
style={{ width: '100%', minWidth: 200 }}
|
||||
aria-label={`${r.oldTitle} 바뀔 제목`}
|
||||
value={edits[r.songId]?.title ?? r.newTitle}
|
||||
onChange={(e) => setEdits((cur) => ({ ...cur, [r.songId]: { ...cur[r.songId], title: e.target.value } }))}
|
||||
/>
|
||||
<input
|
||||
className="input sm"
|
||||
style={{ width: '100%', minWidth: 200 }}
|
||||
aria-label={`${r.oldTitle} 바뀔 가수`}
|
||||
value={edits[r.songId]?.artist ?? r.newArtist}
|
||||
onChange={(e) => setEdits((cur) => ({ ...cur, [r.songId]: { ...cur[r.songId], artist: e.target.value } }))}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<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>}
|
||||
</td>
|
||||
<td className="small">
|
||||
{done ? (
|
||||
<span className={`badge ${r.status === 'skipped' ? '' : 'ok'}`}>{STATUS[r.status] ?? r.status}</span>
|
||||
) : (
|
||||
<div className="stack" style={{ gap: 4 }}>
|
||||
{r.note && <span className={r.kind === 'check' ? 'warn-text' : 'muted'}>{r.note}</span>}
|
||||
<div className="row">
|
||||
<button type="button" className="btn btn-sm btn-primary" disabled={busy} onClick={() => void act('apply', { ids: [r.songId], edits: editList([r.songId]) })}>
|
||||
적용
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm" disabled={busy} onClick={() => void act('skip', { ids: [r.songId] })}>
|
||||
건너뛰기
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
{pages > 1 && (
|
||||
<div className="row" style={{ marginTop: 10 }}>
|
||||
<button type="button" className="btn btn-sm" disabled={page === 0} onClick={() => setPage(page - 1)}>
|
||||
이전
|
||||
</button>
|
||||
<span className="small muted">
|
||||
{page + 1} / {pages}
|
||||
</span>
|
||||
<button type="button" className="btn btn-sm" disabled={page + 1 >= pages} onClick={() => setPage(page + 1)}>
|
||||
다음
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{confirmAll && (
|
||||
<ConfirmSheet
|
||||
title={`'${label(kind)}' ${data?.total ?? 0}곡을 모두 적용할까요?`}
|
||||
body="이 쪽에서 고친 칸도 함께 적용돼요. 다른 쪽 곡은 서버가 만든 제목·정답 그대로 들어가요. 원래 이름은 정답으로 남아요."
|
||||
confirm="모두 적용"
|
||||
onClose={() => setConfirmAll(false)}
|
||||
onConfirm={() => {
|
||||
setConfirmAll(false);
|
||||
void act('apply', { kind, edits: editList(rows.map((r) => r.songId)) });
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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곡
|
||||
|
||||
@@ -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 });
|
||||
|
||||
Reference in New Issue
Block a user