v1.3.8: 녹음 파일 이름을 날짜_시각_말한사람_게임_모드_맵_라운드_발화ID.ogg 로
- 저장 직후 이름 붙이기(경기 중엔 지금 라운드), 경기 상세 · 표시 이름이 바뀌면 다시 맞춤, 예전 파일도 바꿈 - 음성 인식이 읽는 중이면 끝난 뒤 바꿈, 기록 zip · 사이트 다운로드도 같은 이름 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -8,7 +8,7 @@
|
||||
- 설계·계획: [`docs/gemnoki-project-plan.pdf`](docs/gemnoki-project-plan.pdf), 개발 구조·인터페이스: [`docs/dev/ARCHITECTURE.md`](docs/dev/ARCHITECTURE.md)
|
||||
- 범인찾기 · 리플레이 동기화 계획서 v1.2 (결정 반영): [`docs/culprit-finder-plan.pdf`](docs/culprit-finder-plan.pdf) · 원본 · 비용 계산 · 프롬프트 초안: `docs/report/culprit/` (실제로 쓰는 프롬프트는 `site/server/prompt/`)
|
||||
- **제작 완료 보고서 (M0~M8)**: [`docs/gemnoki-final-report.pdf`](docs/gemnoki-final-report.pdf) · 단계별 테스트 기록: [`docs/dev/test-results.md`](docs/dev/test-results.md)
|
||||
- Windows 실행 파일: Gitea 릴리스 [v1.3.7](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.3.7) (`GameVoiceRecorder-1.3.7-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.3.7-portable.exe`) · 바뀐 점 보고서 [`docs/gemnoki-v1.3.7-report.pdf`](docs/gemnoki-v1.3.7-report.pdf) · 처음 버전 [v1.0.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.0.0)
|
||||
- Windows 실행 파일: Gitea 릴리스 [v1.3.8](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.3.8) (`GameVoiceRecorder-1.3.8-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.3.8-portable.exe`) · 바뀐 점 보고서 [`docs/gemnoki-v1.3.7-report.pdf`](docs/gemnoki-v1.3.7-report.pdf) · 처음 버전 [v1.0.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.0.0)
|
||||
|
||||
## 로그인 · 관리자 (v1.2.0~)
|
||||
|
||||
@@ -19,6 +19,13 @@
|
||||
- 앱은 시작할 때와 10분마다 등록 여부를 다시 확인한다. 등록이 해제되면 바로 잠그고 봇 · 녹음 · 사이트 연결을 멈춘다. 사이트 서버에 못 붙으면 마지막 확인 뒤 3일까지는 그대로 쓴다.
|
||||
- 서버 쪽: `site/server/src/app-auth.ts` (`/auth/app/*`, `/app/me`, `/app/admin/users`), 앱 쪽: `app/src/core/auth.ts`, 권한 목록: `app/src/core/roles.ts`. 로그인 E2E: `app/scripts/login-e2e.mts`.
|
||||
|
||||
## v1.3.8 바뀐 점
|
||||
|
||||
- **녹음 파일 이름**: `날짜_시각_말한사람_게임_모드_맵_라운드_발화ID.ogg` (예: `2026-10-16_04-03-16_사금향_발로란트_경쟁전_어센트_R7_0mv9….ogg`, 롤은 라운드 대신 게임 시간 `12분30초`, 경기 밖은 `…_사금향_경기밖_….ogg`). 시각은 게임 PC 시각, Windows 에서 못 쓰는 글자는 뺀다. `app/src/core/audio-names.ts`
|
||||
- 녹음이 끝나면 바로 이 이름으로 저장하고(경기 중에는 지금 라운드), 경기가 끝나 경기 상세(정확한 라운드)가 오거나 표시 이름이 바뀌면 다시 맞춘다. 예전 파일도 처음 켤 때 바꾼다
|
||||
- 음성 인식이 그 파일을 읽는 중이거나 대기열에 있으면 바꾸지 않고, 변환이 끝난 뒤 바꾼다. 다른 프로그램이 파일을 열고 있으면 다음에 다시 한다
|
||||
- 기록 zip 안 `audio/` 도 같은 이름, 사이트 ogg 다운로드 · 자세한 정보도 같은 이름 (v1.3.7 zip 의 `audio/<발화ID>.ogg` 도 그대로 받는다)
|
||||
|
||||
## v1.3.7 바뀐 점
|
||||
|
||||
- **기록 관리** (사이트 "기록" 탭, `site/web/src/pages/RecordsPage.tsx`): 기록을 경기 하나 = 묶음 하나로 보고, 경기 밖 대화는 녹음 세션 안에서 경기 사이마다 묶는다. 다음 경기가 30분 안에 시작하면 "경기 전 대화", 지난 경기가 30분 안에 끝났으면 "경기 후 대화", 아니면 "게임 밖 대화". 묶음을 골라 한 번에 zip 내려받기 · 지우기(관리자) · zip 받아오기(관리자). 앱 `app/src/core/bundles.ts`, API `GET /api/bundles` · `GET /api/bundles/export?ids=` · `POST /api/bundles/delete` · `POST /api/bundles/import`
|
||||
|
||||
8
app/package-lock.json
generated
8
app/package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "gvr-app",
|
||||
"version": "1.3.7",
|
||||
"version": "1.3.8",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "gvr-app",
|
||||
"version": "1.3.7",
|
||||
"version": "1.3.8",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"@discordjs/voice": "^0.19.2",
|
||||
@@ -4677,7 +4677,7 @@
|
||||
}
|
||||
},
|
||||
"node_modules/prism-media": {
|
||||
"version": "1.3.7",
|
||||
"version": "1.3.8",
|
||||
"resolved": "https://registry.npmjs.org/prism-media/-/prism-media-1.3.5.tgz",
|
||||
"integrity": "sha512-IQdl0Q01m4LrkN1EGIE9lphov5Hy7WWlH6ulf5QdGePLlPas9p2mhgddTEHrlaXYjjFToM1/rWuwF37VF4taaA==",
|
||||
"peerDependencies": {
|
||||
@@ -4782,7 +4782,7 @@
|
||||
}
|
||||
},
|
||||
"node_modules/pvtsutils": {
|
||||
"version": "1.3.7",
|
||||
"version": "1.3.8",
|
||||
"resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz",
|
||||
"integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==",
|
||||
"dev": true,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "gvr-app",
|
||||
"productName": "겜녹이",
|
||||
"version": "1.3.7",
|
||||
"version": "1.3.8",
|
||||
"description": "겜녹이 (Game Voice Recorder) - 게임 연동 디스코드 음성 기록",
|
||||
"private": true,
|
||||
"main": "dist/main.cjs",
|
||||
|
||||
156
app/src/core/audio-names.ts
Normal file
156
app/src/core/audio-names.ts
Normal file
@@ -0,0 +1,156 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { MatchRow, Store, UtteranceRow } from './db/db.js';
|
||||
import type { GameManager } from './games/manager.js';
|
||||
import { valNoRounds } from './games/modes.js';
|
||||
import { logger } from './util/log.js';
|
||||
|
||||
const log = logger('audio');
|
||||
|
||||
/**
|
||||
* 녹음 파일 이름 (v1.3.8): 파일만 봐도 무슨 녹음인지 알 수 있게
|
||||
* 2026-10-16_04-03-16_사금향_발로란트_경쟁전_어센트_R7_<발화ID>.ogg
|
||||
* 2026-10-16_21-10-05_하늘_롤_솔로랭크_12분30초_<발화ID>.ogg
|
||||
* 2026-10-16_03-58-56_사금향_경기밖_<발화ID>.ogg
|
||||
* 날짜 · 시각은 이 PC 시각, 끝의 발화 ID 로 이름이 겹치지 않는다. 경기가 끝나 라운드가 정확해지면 이름을 다시 맞춘다.
|
||||
*/
|
||||
export interface NameInfo {
|
||||
id: string;
|
||||
startedAt: number;
|
||||
speaker: string;
|
||||
/** 경기 밖이면 null */
|
||||
game: 'valorant' | 'lol' | null;
|
||||
mode?: string | null;
|
||||
map?: string | null;
|
||||
round?: number | null;
|
||||
/** 롤: 경기 시작부터 지난 시간 */
|
||||
gameTimeMs?: number | null;
|
||||
}
|
||||
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
|
||||
/** 파일 이름에 못 쓰는 글자(Windows) · 공백을 뺀다 */
|
||||
export function safePart(s: string | null | undefined, max = 24): string {
|
||||
return String(s ?? '')
|
||||
.replace(/[\\/:*?"<>|\x00-\x1f]/g, '')
|
||||
.replace(/[\s_]+/g, '')
|
||||
.replace(/\.+$/, '')
|
||||
.slice(0, max);
|
||||
}
|
||||
|
||||
export function audioFileName(o: NameInfo): string {
|
||||
const d = new Date(o.startedAt);
|
||||
const when = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}_${pad(d.getHours())}-${pad(d.getMinutes())}-${pad(d.getSeconds())}`;
|
||||
const parts = [when, safePart(o.speaker) || '알수없음'];
|
||||
if (!o.game) parts.push('경기밖');
|
||||
else {
|
||||
parts.push(o.game === 'valorant' ? '발로란트' : '롤');
|
||||
const mode = safePart(o.mode);
|
||||
const map = safePart(o.map);
|
||||
if (mode) parts.push(mode);
|
||||
if (map && map !== mode) parts.push(map);
|
||||
if (o.game === 'valorant' && o.round) parts.push(`R${o.round}`);
|
||||
if (o.game === 'lol' && o.gameTimeMs != null && o.gameTimeMs >= 0) {
|
||||
const s = Math.floor(o.gameTimeMs / 1000);
|
||||
parts.push(`${Math.floor(s / 60)}분${pad(s % 60)}초`);
|
||||
}
|
||||
}
|
||||
parts.push(o.id);
|
||||
return `${parts.join('_')}.ogg`;
|
||||
}
|
||||
|
||||
export class AudioNamer {
|
||||
constructor(
|
||||
private store: Store,
|
||||
private games: GameManager,
|
||||
/** STT 가 이 발화를 읽는 중이거나 대기열에 있으면 true (이름을 바꾸면 워커가 파일을 못 찾는다) */
|
||||
private busy: (id: string) => boolean,
|
||||
) {}
|
||||
|
||||
private matchCache = new Map<string, { m: MatchRow; mode: string; map: string; at: number }>();
|
||||
|
||||
private matchInfo(id: string) {
|
||||
const c = this.matchCache.get(id);
|
||||
if (c && Date.now() - c.at < 5000) return c;
|
||||
const m = this.store.getMatch(id);
|
||||
if (!m) return null;
|
||||
const sum = this.games.summary(m);
|
||||
const v = { m, mode: sum.mode, map: sum.map.name, at: Date.now() };
|
||||
this.matchCache.set(id, v);
|
||||
return v;
|
||||
}
|
||||
|
||||
info(u: UtteranceRow): NameInfo {
|
||||
const speaker = this.store.getUser(u.user_id)?.name ?? u.user_id;
|
||||
const mi = u.match_id ? this.matchInfo(u.match_id) : null;
|
||||
if (!mi) return { id: u.id, startedAt: u.started_at, speaker, game: null };
|
||||
const { m } = mi;
|
||||
const gameTs = u.started_at - m.clock_offset;
|
||||
let round: number | null = null;
|
||||
if (m.game === 'valorant' && !valNoRounds(m.queue)) {
|
||||
const rounds = this.store.rounds(m.id);
|
||||
round = rounds.find((r) => gameTs >= r.started_at && gameTs <= r.ended_at)?.num ?? rounds.find((r) => gameTs < r.started_at)?.num ?? null;
|
||||
// 경기 중에는 라운드 표가 아직 없다: 지금 라운드를 쓴다 (경기 뒤 정확한 값으로 다시 맞춤)
|
||||
if (!rounds.length) round = this.games.liveRound(m.id);
|
||||
}
|
||||
return {
|
||||
id: u.id,
|
||||
startedAt: u.started_at,
|
||||
speaker,
|
||||
game: m.game as 'valorant' | 'lol',
|
||||
mode: mi.mode,
|
||||
map: m.game === 'lol' ? null : mi.map,
|
||||
round,
|
||||
gameTimeMs: m.game === 'lol' ? gameTs - m.started_at : null,
|
||||
};
|
||||
}
|
||||
|
||||
/** 발화 하나의 파일 이름을 맞춘다. 바꿨으면 true */
|
||||
refresh(id: string): boolean {
|
||||
const u = this.store.getUtterance(id);
|
||||
if (!u || !u.audio_path || u.audio_deleted || this.busy(id)) return false;
|
||||
const want = audioFileName(this.info(u));
|
||||
const cur = u.audio_path;
|
||||
const dir = path.dirname(cur);
|
||||
if (path.basename(cur) === want) return false;
|
||||
const next = path.join(dir, want);
|
||||
try {
|
||||
if (!fs.existsSync(cur) || fs.existsSync(next)) return false;
|
||||
fs.renameSync(cur, next);
|
||||
} catch (e: any) {
|
||||
// 다른 프로그램이 파일을 열고 있으면(Windows) 다음에 다시 한다
|
||||
log.debug(`파일 이름 바꾸기 실패 ${path.basename(cur)}: ${e?.code ?? e?.message}`);
|
||||
return false;
|
||||
}
|
||||
this.store.db.prepare('UPDATE utterances SET audio_path=? WHERE id=?').run(next, id);
|
||||
return true;
|
||||
}
|
||||
|
||||
refreshMatch(matchId: string): number {
|
||||
this.matchCache.delete(matchId);
|
||||
const ids = this.store.db.prepare('SELECT id FROM utterances WHERE match_id=? AND audio_deleted=0').all(matchId) as { id: string }[];
|
||||
let n = 0;
|
||||
for (const { id } of ids) if (this.refresh(id)) n++;
|
||||
if (n) log.info(`경기 ${matchId}: 녹음 파일 ${n}개 이름 맞춤`);
|
||||
return n;
|
||||
}
|
||||
|
||||
private allRunning = false;
|
||||
/** 모든 녹음 파일 이름을 맞춘다 (예전 이름 · 표시 이름 바뀜). 50개씩 나눠서 */
|
||||
refreshAll(skip?: (u: { id: string; created_at: number }) => boolean): void {
|
||||
if (this.allRunning) return;
|
||||
this.allRunning = true;
|
||||
this.matchCache.clear();
|
||||
const rows = this.store.db.prepare('SELECT id, created_at FROM utterances WHERE audio_deleted=0 AND audio_path IS NOT NULL ORDER BY started_at').all() as { id: string; created_at: number }[];
|
||||
let i = 0;
|
||||
let n = 0;
|
||||
const step = () => {
|
||||
for (const r of rows.slice(i, i + 50)) if (!skip?.(r) && this.refresh(r.id)) n++;
|
||||
i += 50;
|
||||
if (i < rows.length) return void setTimeout(step, 0);
|
||||
this.allRunning = false;
|
||||
if (n) log.info(`녹음 파일 ${n}개 이름을 바꿈 (날짜 · 시각 · 말한 사람 · 게임 · 라운드)`);
|
||||
};
|
||||
step();
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,8 @@ export class Bundles {
|
||||
private games: GameManager,
|
||||
private audioDir: () => string,
|
||||
private version: string,
|
||||
/** 받아온 발화들 (녹음 파일 이름 맞추기) */
|
||||
private afterImport?: (ids: string[]) => void,
|
||||
) {}
|
||||
|
||||
private groups(): Group[] {
|
||||
@@ -231,7 +233,8 @@ export class Bundles {
|
||||
delete (rest as any).rowid;
|
||||
let audio: string | null = null;
|
||||
if (audio_path && !u.audio_deleted && fs.existsSync(audio_path)) {
|
||||
audio = `audio/${u.id}.ogg`;
|
||||
// zip 안에서도 알아볼 수 있게 녹음 파일 이름 그대로 (날짜 · 시각 · 말한 사람 · 게임 · 라운드 · 발화 ID)
|
||||
audio = `audio/${path.basename(audio_path)}`;
|
||||
entries.push({ name: audio, data: fs.readFileSync(audio_path) });
|
||||
}
|
||||
return { ...rest, audio };
|
||||
@@ -298,6 +301,7 @@ export class Bundles {
|
||||
const now = Date.now();
|
||||
const res: BundleImportResult = { bundles: manifest.bundles.map((b: any) => String(b.label ?? b.id)), added: { utterances: 0, audio: 0, matches: 0, events: 0, users: 0 }, skipped: 0 };
|
||||
const written: string[] = [];
|
||||
const addedIds: string[] = [];
|
||||
try {
|
||||
db.transaction(() => {
|
||||
for (const u of data.users) {
|
||||
@@ -359,6 +363,7 @@ export class Bundles {
|
||||
);
|
||||
db.prepare('INSERT OR REPLACE INTO utterance_imports(id, imported_at) VALUES(?,?)').run(u.id, now);
|
||||
res.added.utterances++;
|
||||
addedIds.push(u.id);
|
||||
}
|
||||
})();
|
||||
} catch (e) {
|
||||
@@ -366,6 +371,11 @@ export class Bundles {
|
||||
for (const f of written) fs.rmSync(f, { force: true });
|
||||
throw e instanceof BundleError ? e : new BundleError(`받아오기 실패: 기록을 저장하지 못했습니다 (${(e as Error).message})`, 'import_failed');
|
||||
}
|
||||
try {
|
||||
this.afterImport?.(addedIds);
|
||||
} catch (e) {
|
||||
log.warn('받아온 녹음 파일 이름 맞추기 실패', e);
|
||||
}
|
||||
log.info(`기록 묶음 받아오기: ${res.bundles.join(', ')} (발화 ${res.added.utterances}개 추가, 음성 ${res.added.audio}개, 이미 있음 ${res.skipped}개)`);
|
||||
return res;
|
||||
}
|
||||
@@ -417,6 +427,7 @@ export function validate(files: Map<string, Buffer>, store?: Store): { manifest:
|
||||
}
|
||||
for (const r of data.rounds ?? []) if (!matchIds.has(r?.match_id) || !num(r?.num) || !num(r?.started_at) || !num(r?.combat_at) || !num(r?.ended_at)) fail('라운드 기록에 꼭 필요한 값이 없습니다');
|
||||
const seen = new Set<string>();
|
||||
const audioSeen = new Set<string>();
|
||||
for (const u of data.utterances) {
|
||||
if (typeof u?.id !== 'string' || !SAFE_ID.test(u.id)) fail('발화 ID 가 잘못되었습니다');
|
||||
if (seen.has(u.id)) fail(`발화 ${u.id} 가 두 번 들어 있습니다`);
|
||||
@@ -426,7 +437,10 @@ export function validate(files: Map<string, Buffer>, store?: Store): { manifest:
|
||||
if (!num(u.started_at) || !num(u.ended_at) || u.ended_at < u.started_at) fail(`발화 ${u.id} 의 시각이 잘못되었습니다`);
|
||||
if (u.match_id && !matchIds.has(u.match_id) && !store?.getMatch(u.match_id)) fail(`발화 ${u.id} 의 경기(${u.match_id})가 없습니다`);
|
||||
if (u.audio) {
|
||||
if (u.audio !== `audio/${u.id}.ogg`) fail(`발화 ${u.id} 의 음성 파일 이름이 잘못되었습니다`);
|
||||
// v1.3.7: audio/<발화ID>.ogg, v1.3.8~: audio/<날짜_시각_말한사람_…_발화ID>.ogg
|
||||
if (typeof u.audio !== 'string' || !/^audio\/[^/\\]{1,200}\.ogg$/.test(u.audio) || u.audio.includes('..')) fail(`발화 ${u.id} 의 음성 파일 이름이 잘못되었습니다`);
|
||||
if (audioSeen.has(u.audio)) fail(`음성 파일 ${u.audio} 를 두 발화가 같이 씁니다`);
|
||||
audioSeen.add(u.audio);
|
||||
const a = files.get(u.audio);
|
||||
if (!a) fail(`음성 파일 ${u.audio} 가 zip 안에 없습니다`);
|
||||
if (a!.length < 4 || a!.toString('ascii', 0, 4) !== 'OggS') fail(`음성 파일 ${u.audio} 가 ogg 가 아닙니다`);
|
||||
|
||||
@@ -19,6 +19,8 @@ export interface RecorderOptions {
|
||||
skip: (userId: string) => boolean;
|
||||
/** ts 시점 진행 중인 경기 ID */
|
||||
matchAt: (ts: number) => string | null;
|
||||
/** 저장 직후 (녹음 파일 이름을 날짜 · 말한 사람 · 게임 · 라운드로 바꾼다) */
|
||||
onSaved?: (id: string) => void;
|
||||
}
|
||||
|
||||
/** RTP 시각 (48kHz 샘플 단위 타임스탬프 + 순번) */
|
||||
@@ -198,7 +200,7 @@ export class Recorder {
|
||||
}
|
||||
const endedAt = u.startedAt + dur;
|
||||
const matchId = this.opts.matchAt(u.startedAt);
|
||||
const row = this.store.insertUtterance({
|
||||
let row = this.store.insertUtterance({
|
||||
id: u.id,
|
||||
session_id: this.sessionId,
|
||||
user_id: userId,
|
||||
@@ -207,6 +209,12 @@ export class Recorder {
|
||||
audio_path: u.writer.path,
|
||||
match_id: matchId,
|
||||
});
|
||||
try {
|
||||
this.opts.onSaved?.(row.id);
|
||||
row = this.store.getUtterance(row.id) ?? row;
|
||||
} catch (e) {
|
||||
log.warn('녹음 파일 이름 바꾸기 실패', e);
|
||||
}
|
||||
this.bus.live({ type: 'utterance.created', data: this.timeline.utteranceItem(row) });
|
||||
this.stt.enqueue(row.id, 'realtime');
|
||||
log.debug(`발화 저장 ${userId} ${dur}ms ${u.writer.bytes}B`);
|
||||
|
||||
@@ -18,6 +18,13 @@ const log = logger('games');
|
||||
/** 게임 어댑터들을 묶고, 경기 시작·종료를 녹음/STT/타임라인에 반영한다 */
|
||||
export class GameManager implements AdapterHost {
|
||||
adapters: GameAdapter[];
|
||||
/** 경기 정보가 바뀌어 녹음 파일 이름을 다시 맞출 때 (경기 끝 · 경기 상세 적용) */
|
||||
onMatchFiles: ((matchId: string) => void) | null = null;
|
||||
|
||||
/** 진행 중인 발로란트 경기의 지금 라운드 (경기 중 녹음 파일 이름용) */
|
||||
liveRound(matchId: string): number | null {
|
||||
return this.live().find((g) => g.matchId === matchId && g.inMatch)?.round ?? null;
|
||||
}
|
||||
|
||||
constructor(
|
||||
readonly store: Store,
|
||||
@@ -107,6 +114,7 @@ export class GameManager implements AdapterHost {
|
||||
const n = this.store.assignMatch(id, m.started_at + m.clock_offset - 2000, (m.ended_at ?? Date.now()) + 1000);
|
||||
log.info(`경기 ${id}: 발화 ${n}개 연결`);
|
||||
this.bus.live({ type: 'users.updated', data: [] });
|
||||
this.onMatchFiles?.(id);
|
||||
}
|
||||
this.emitMatch(id);
|
||||
}
|
||||
@@ -117,7 +125,7 @@ export class GameManager implements AdapterHost {
|
||||
this.store.upsertMatch({ id, game: cur.game, started_at: cur.started_at, ended_at: endedAt, status: 'pending_detail' });
|
||||
this.store.assignMatch(id, cur.started_at, endedAt);
|
||||
this.timeline.invalidate(id);
|
||||
void this.stt.onMatchEnd(cur.started_at, endedAt);
|
||||
void this.stt.onMatchEnd(cur.started_at, endedAt).finally(() => this.onMatchFiles?.(id));
|
||||
this.emitMatch(id);
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import path from 'node:path';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { buildApi, toUser } from './api/server.js';
|
||||
import { Bundles } from './bundles.js';
|
||||
import { AudioNamer } from './audio-names.js';
|
||||
import { Culprit } from './culprit.js';
|
||||
import { Store } from './db/db.js';
|
||||
import { Dictionary } from './dict/dictionary.js';
|
||||
@@ -68,6 +69,7 @@ export async function startCore(opts: CoreOptions) {
|
||||
const stt = new SttPipeline(worker, store, dict, timeline, bus, S);
|
||||
const assets = new GameAssets(path.join(opts.dataDir, 'cache'));
|
||||
const games = new GameManager(store, assets, worker, stt, timeline, bus, S, () => S().discord.followUserId);
|
||||
const audioNames = new AudioNamer(store, games, (id) => stt.isBusy(id));
|
||||
const recorder: Recorder = new Recorder(store, stt, timeline, bus, {
|
||||
audioDir: () => paths().audio,
|
||||
silenceMs: () => S().audio.silenceMs,
|
||||
@@ -79,6 +81,7 @@ export async function startCore(opts: CoreOptions) {
|
||||
return process.env.GVR_RECORD_BOTS !== '1' && bot.isBot(uid);
|
||||
},
|
||||
matchAt: (ts) => games.liveMatchAt(ts),
|
||||
onSaved: (id) => audioNames.refresh(id),
|
||||
});
|
||||
const announcer = new Announcer(paths().tts, opts.resourcesDir, async (src, dst, tempo) => {
|
||||
await worker.request('tempo', { src, dst, tempo }, 120000);
|
||||
@@ -98,7 +101,7 @@ export async function startCore(opts: CoreOptions) {
|
||||
settings: S,
|
||||
trainingDir: () => paths().training,
|
||||
version: opts.version,
|
||||
bundles: new Bundles(store, games, () => paths().audio, opts.version),
|
||||
bundles: new Bundles(store, games, () => paths().audio, opts.version, (ids) => ids.forEach((id) => audioNames.refresh(id))),
|
||||
overviewExtra: () => ({
|
||||
guild: bot.state.guild,
|
||||
recording: {
|
||||
@@ -123,6 +126,15 @@ export async function startCore(opts: CoreOptions) {
|
||||
worker.start();
|
||||
stt.resumePending();
|
||||
games.start();
|
||||
// 녹음 파일 이름 (날짜 · 시각 · 말한 사람 · 게임 · 라운드): 변환이 끝난 발화, 경기가 끝난 경기, 시작할 때 전체를 맞춘다
|
||||
stt.onDone = (id) => audioNames.refresh(id);
|
||||
games.onMatchFiles = (id) => audioNames.refreshMatch(id);
|
||||
const renameAll = () => {
|
||||
const before = stt.repairPendingBefore();
|
||||
audioNames.refreshAll(before ? (u) => u.created_at < before : undefined);
|
||||
};
|
||||
stt.onRepairDone = renameAll;
|
||||
renameAll();
|
||||
void assets.refresh().then(() => dict.syncGameNames(assets.names())).catch(() => undefined);
|
||||
retention.start();
|
||||
relay.start();
|
||||
@@ -176,5 +188,5 @@ export async function startCore(opts: CoreOptions) {
|
||||
store.close();
|
||||
};
|
||||
|
||||
return { settings, store, bus, timeline, dict, worker, stt, assets, games, recorder, bot, api, relay, retention, paths, startBot, stop, version: opts.version, resourcesDir: opts.resourcesDir };
|
||||
return { settings, store, bus, timeline, dict, worker, stt, assets, games, audioNames, recorder, bot, api, relay, retention, paths, startBot, stop, version: opts.version, resourcesDir: opts.resourcesDir };
|
||||
}
|
||||
|
||||
@@ -46,6 +46,22 @@ export class SttPipeline {
|
||||
private queued = new Set<string>();
|
||||
private busy = false;
|
||||
private processing: string | null = null;
|
||||
/** 한 발화의 변환이 끝났을 때 (녹음 파일 이름 맞추기) */
|
||||
onDone: ((id: string) => void) | null = null;
|
||||
/** 예전 녹음 고치기가 끝났을 때 */
|
||||
onRepairDone: (() => void) | null = null;
|
||||
|
||||
/** 이 발화를 변환 중이거나 대기열에 있는가 (그동안은 파일 이름을 바꾸지 않는다) */
|
||||
isBusy(id: string): boolean {
|
||||
return this.processing === id || this.queued.has(`realtime:${id}`) || this.queued.has(`precise:${id}`);
|
||||
}
|
||||
|
||||
/** 예전 녹음 고치기가 아직 남았는가 (끝나기 전에는 그 녹음들의 이름을 바꾸지 않는다) */
|
||||
repairPendingBefore(): number | null {
|
||||
if (this.store.meta('audio_repair_v136')) return null;
|
||||
const c = this.store.meta('audio_repair_v136_before');
|
||||
return c ? Number(c) : null;
|
||||
}
|
||||
private inMatch = false;
|
||||
/** 두 모델을 동시에 올릴 VRAM 이 되는가 (워커 추천값) */
|
||||
private bothFit = true;
|
||||
@@ -202,6 +218,11 @@ export class SttPipeline {
|
||||
this.busy = false;
|
||||
this.processing = null;
|
||||
this.status.processing = null;
|
||||
try {
|
||||
if (!this.isBusy(job.id)) this.onDone?.(job.id);
|
||||
} catch (e) {
|
||||
log.warn('변환 뒤 처리 실패', e);
|
||||
}
|
||||
setImmediate(() => this.pump());
|
||||
});
|
||||
}
|
||||
@@ -358,6 +379,7 @@ export class SttPipeline {
|
||||
i += 20;
|
||||
if (i < rows.length) return void setTimeout(step, 0);
|
||||
this.store.setMeta(KEY, String(Date.now()));
|
||||
this.onRepairDone?.();
|
||||
if (fixed) log.info(`예전 녹음 ${fixed}개에서 말 중간에 끼운 무음을 빼고 정밀 모델로 다시 변환`);
|
||||
};
|
||||
step();
|
||||
|
||||
@@ -277,7 +277,11 @@ async function syncNames(): Promise<void> {
|
||||
if (!c || !auth?.ok) return;
|
||||
try {
|
||||
const names = await auth.displayNames();
|
||||
if (core === c) c.store.setDisplayNames(names);
|
||||
if (core === c) {
|
||||
c.store.setDisplayNames(names);
|
||||
// 녹음 파일 이름에도 표시 이름을 쓴다
|
||||
c.audioNames.refreshAll();
|
||||
}
|
||||
} catch (e: any) {
|
||||
log.warn(`표시 이름을 받지 못했습니다: ${e?.message ?? e}`);
|
||||
}
|
||||
|
||||
76
app/test/audio-names.test.ts
Normal file
76
app/test/audio-names.test.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { Store } from '../src/core/db/db.ts';
|
||||
import { AudioNamer, audioFileName, safePart } from '../src/core/audio-names.ts';
|
||||
import { Bundles } from '../src/core/bundles.ts';
|
||||
import { readZip } from '../src/core/util/zip.ts';
|
||||
|
||||
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-names-'));
|
||||
const at = (h: number, m: number, s: number) => new Date(2026, 9, 16, h, m, s).getTime();
|
||||
|
||||
test('녹음 파일 이름: 날짜 · 시각 · 말한 사람 · 게임 · 모드 · 맵 · 라운드 · 발화 ID', () => {
|
||||
assert.equal(
|
||||
audioFileName({ id: 'u1', startedAt: at(4, 3, 16), speaker: '사금향', game: 'valorant', mode: '경쟁전', map: '어센트', round: 7 }),
|
||||
'2026-10-16_04-03-16_사금향_발로란트_경쟁전_어센트_R7_u1.ogg',
|
||||
);
|
||||
assert.equal(audioFileName({ id: 'u2', startedAt: at(21, 10, 5), speaker: '하늘', game: 'lol', mode: '솔로 랭크', gameTimeMs: 750_400 }), '2026-10-16_21-10-05_하늘_롤_솔로랭크_12분30초_u2.ogg');
|
||||
assert.equal(audioFileName({ id: 'u3', startedAt: at(3, 58, 56), speaker: '사금향', game: null }), '2026-10-16_03-58-56_사금향_경기밖_u3.ogg');
|
||||
// Windows 에서 못 쓰는 글자는 뺀다
|
||||
assert.equal(safePart('a/b:c*d?"e<f>g|h i_j.'), 'abcdefghij');
|
||||
assert.equal(audioFileName({ id: 'u4', startedAt: at(1, 2, 3), speaker: '', game: null }), '2026-10-16_01-02-03_알수없음_경기밖_u4.ogg');
|
||||
});
|
||||
|
||||
test('녹음 파일 이름: 실제 파일을 바꾸고, 경기 뒤 라운드 · 표시 이름이 바뀌면 다시 맞추고, zip 에도 그 이름으로 넣는다', () => {
|
||||
const dir = tmp();
|
||||
const audio = path.join(dir, 'audio');
|
||||
const store = new Store(path.join(dir, 'db.sqlite'));
|
||||
store.upsertUser({ id: 'u1', name: '하늘', avatar: null });
|
||||
const games: any = { summary: (m: any) => ({ mode: m.game === 'lol' ? '솔로 랭크' : '경쟁전', map: { name: m.game === 'lol' ? '소환사의 협곡' : '어센트' } }), liveRound: () => 3 };
|
||||
const busy = new Set<string>();
|
||||
const namer = new AudioNamer(store, games, (id) => busy.has(id));
|
||||
const S = at(4, 0, 0);
|
||||
store.upsertMatch({ id: 'val-1', game: 'valorant', started_at: S, ended_at: S + 40 * 60000, map: 'Ascent', queue: 'competitive', status: 'live' });
|
||||
const mk = (id: string, ts: number, match: string | null) => {
|
||||
const f = path.join(audio, 'day', `${id}.ogg`);
|
||||
fs.mkdirSync(path.dirname(f), { recursive: true });
|
||||
fs.writeFileSync(f, Buffer.concat([Buffer.from('OggS'), Buffer.alloc(50)]));
|
||||
store.insertUtterance({ id, session_id: null, user_id: 'u1', started_at: ts, ended_at: ts + 1000, audio_path: f, match_id: match });
|
||||
store.updateUtteranceResult(id, { text: `말 ${id}`, raw_text: null, words: [], noise: false, noise_reason: null, confidence: 1, lufs: -20, gain_db: 0, model: 'm', status: 'precise' });
|
||||
};
|
||||
mk('a1', S + 5 * 60000, 'val-1');
|
||||
mk('a2', S - 60000, null);
|
||||
// 경기 중: 라운드 표가 없어서 지금 라운드(3)를 쓴다
|
||||
assert.equal(namer.refresh('a1'), true);
|
||||
assert.equal(path.basename(store.getUtterance('a1')!.audio_path!), '2026-10-16_04-05-00_하늘_발로란트_경쟁전_어센트_R3_a1.ogg');
|
||||
assert.ok(fs.existsSync(store.getUtterance('a1')!.audio_path!));
|
||||
assert.ok(!fs.existsSync(path.join(audio, 'day', 'a1.ogg')));
|
||||
// 경기 뒤 라운드 표가 생기면 정확한 라운드로 다시 맞춘다 (음성 인식 중인 발화는 건드리지 않음)
|
||||
store.replaceRounds('val-1', [
|
||||
{ match_id: 'val-1', num: 1, started_at: S, combat_at: S + 30000, ended_at: S + 2 * 60000, win: 1, result: null, ally_score: 1, enemy_score: 0, economy: '{}' },
|
||||
{ match_id: 'val-1', num: 2, started_at: S + 2 * 60000, combat_at: S + 150000, ended_at: S + 6 * 60000, win: 1, result: null, ally_score: 2, enemy_score: 0, economy: '{}' },
|
||||
]);
|
||||
busy.add('a1');
|
||||
assert.equal(namer.refreshMatch('val-1'), 0);
|
||||
busy.delete('a1');
|
||||
assert.equal(namer.refreshMatch('val-1'), 1);
|
||||
assert.match(store.getUtterance('a1')!.audio_path!, /_R2_a1\.ogg$/);
|
||||
// 표시 이름이 바뀌면 전체를 다시 맞춘다
|
||||
store.setDisplayNames({ u1: '사금향' });
|
||||
namer.refreshAll();
|
||||
assert.match(path.basename(store.getUtterance('a2')!.audio_path!), /^2026-10-16_03-59-00_사금향_경기밖_a2\.ogg$/);
|
||||
assert.match(path.basename(store.getUtterance('a1')!.audio_path!), /_사금향_발로란트_/);
|
||||
// zip 안에도 같은 이름, 받아오면 받은 PC 에서도 같은 규칙으로
|
||||
const b = new Bundles(store, { summary: (m: any) => ({ ...games.summary(m), score: null, win: null }) } as any, () => audio, 'test', (ids) => ids.forEach((id) => namer.refresh(id)));
|
||||
const id = b.list().find((x) => x.kind === 'match')!.id;
|
||||
store.db.prepare(`UPDATE matches SET status='complete' WHERE id='val-1'`).run();
|
||||
const { zip } = b.export([id]);
|
||||
assert.ok([...readZip(zip).keys()].includes('audio/2026-10-16_04-05-00_사금향_발로란트_경쟁전_어센트_R2_a1.ogg'));
|
||||
b.delete([id]);
|
||||
assert.equal(b.import(zip).added.utterances, 1);
|
||||
assert.equal(path.basename(store.getUtterance('a1')!.audio_path!), '2026-10-16_04-05-00_사금향_발로란트_경쟁전_어센트_R2_a1.ogg');
|
||||
assert.ok(fs.existsSync(store.getUtterance('a1')!.audio_path!));
|
||||
store.close();
|
||||
});
|
||||
@@ -73,9 +73,12 @@ test('E2E: 발화 → STT 워커 → DB → 실시간 이벤트 → 기록 API',
|
||||
assert.deepEqual(page.items.map((i: any) => i.id).sort(), ['quiet', 'speech']);
|
||||
// 우클릭 → 자세한 정보: 원본 ogg 이름 · 경로
|
||||
const info = (await core.api.inject({ method: 'GET', url: '/api/utterances/speech/info' })).json();
|
||||
assert.equal(info.fileName, 'speech.ogg');
|
||||
assert.equal(info.path, sp.audio_path);
|
||||
assert.equal(info.folder, path.dirname(sp.audio_path!));
|
||||
// 변환이 끝나면 녹음 파일 이름을 날짜 · 시각 · 말한 사람 · 경기 밖 · 발화 ID 로 바꾼다
|
||||
assert.match(info.fileName, /^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}_하늘_경기밖_speech\.ogg$/);
|
||||
const sp2 = core.store.getUtterance('speech')!;
|
||||
assert.equal(info.path, sp2.audio_path);
|
||||
assert.ok(fs.existsSync(sp2.audio_path!));
|
||||
assert.equal(info.folder, path.dirname(sp2.audio_path!));
|
||||
assert.ok(info.sizeBytes > 1000);
|
||||
assert.equal(info.deleted, null);
|
||||
assert.equal((await core.api.inject({ method: 'GET', url: '/api/utterances/keys/info' })).json().deleted, 'noise');
|
||||
|
||||
@@ -222,3 +222,9 @@ VOICE E2E PASS
|
||||
- 그 밖: 브라우저 오류 로그에 검색어가 남던 것, 경기 끝 직후 늦게 끝난 실시간 변환의 잡음 파일을 정밀 확인 전에 지우던 것, 많이 골랐을 때 내려받기 주소가 너무 길던 것(본문으로 보냄), zip 풀기 메모리 한도 600MB, 날짜 묶음이 "10월"로만 나오던 것(경기 · 기록 목록)
|
||||
- 테스트: 앱 53 · 사이트 서버 16 · 워커 42 통과, 타입 검사 통과
|
||||
- 배포: 사이트 서버 다시 배포 (`/api/%62undles/delete` 로그인 없이 401), Windows CI (5d494eb, full) 7개 모두 PASS · 앱 버전 1.3.7 → Gitea 릴리스 v1.3.7 (v1.3.6 에 새 버전 안내) · 보고서 `docs/gemnoki-v1.3.7-report.pdf`
|
||||
|
||||
## v1.3.8 — 녹음 파일 이름 (2026-10-16)
|
||||
|
||||
- 이름 규칙 `날짜_시각_말한사람_게임_모드_맵_라운드_발화ID.ogg` (롤은 게임 시간, 경기 밖은 `경기밖`). 테스트 `audio-names.test.ts`: 이름 만들기 · Windows 금지 글자, 실제 파일 바꾸기, 경기 중 지금 라운드 → 경기 뒤 라운드 표로 다시 맞춤, 음성 인식 중이면 건드리지 않음, 표시 이름 바뀌면 전체 다시, zip 안 이름 · 받아오기 뒤 이름
|
||||
- 실제 STT 워커 E2E: 변환이 끝난 뒤 파일 이름이 `…_하늘_경기밖_speech.ogg` 로 바뀌고 자세한 정보 경로도 같음
|
||||
- 사용자 데이터 사본: 21개 이름 바꿈 (`2026-10-16_04-05-52_사금향_발로란트_데스매치_어비스_0mv9wsvgh48a56ebde5.ogg`, 데스매치는 라운드 없음, 경기 전후는 `경기밖`)
|
||||
|
||||
@@ -39,6 +39,8 @@ function closeInfo(): void {
|
||||
|
||||
/** 녹음 원본(.ogg)을 내려받는다. 게임 PC → 사이트 서버 중계로 받은 파일을 그대로 저장 */
|
||||
export async function downloadAudio(item: UtteranceItem, fileName?: string | null): Promise<void> {
|
||||
// 파일 이름: 게임 PC 의 녹음 파일 이름 그대로 (날짜 · 시각 · 말한 사람 · 게임 · 라운드). 예전 앱이면 발화 ID
|
||||
if (!fileName) fileName = await api.utteranceInfo(item.id).then((i) => i.fileName).catch(() => null);
|
||||
const res = await fetch(`/api/audio/${encodeURIComponent(item.id)}`, { credentials: 'include' });
|
||||
if (!res.ok) throw new Error(res.status === 410 ? '음성 파일이 삭제되었습니다' : `받지 못했습니다 (${res.status})`);
|
||||
const blob = await res.blob();
|
||||
|
||||
Reference in New Issue
Block a user