v1.3.7: 기록 관리(경기 · 경기 전후 대화 묶음, 한 번에 지우기 · zip 내보내기/받아오기) · 검토로 찾은 오류 고침

- 기록 묶음 API · zip 형식(gvr-bundle v1) · 받아오기 검사(꼭 필요한 내용이 없으면 실패, 아무것도 넣지 않음)
- 사이트 기록 탭, 큰 zip 조각 중계
- 관리자 확인 %인코딩 우회, 큰 전송 중 연결 끊김, 진행 중 경기 지우기, 예전 녹음 고치기 덮어쓰기,
  타임라인 끼워 넣기, 숫자 반복 줄이기, TTS 반쪽 파일 등

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-16 05:34:39 +09:00
parent c397bacf8c
commit 5d494eb8e8
36 changed files with 246 additions and 72 deletions

View File

@@ -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.6](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.3.6) (`GameVoiceRecorder-1.3.6-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.3.6-portable.exe`) · 처음 버전 [v1.0.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.0.0)
- 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)
## 로그인 · 관리자 (v1.2.0~)
@@ -19,6 +19,12 @@
- 앱은 시작할 때와 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.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`
- **zip 형식** `gvr-bundle` v1: `manifest.json`(형식 · 묶음 · 개수), `data.json`(유저 · 세션 · 경기 · 라운드 · 이벤트 · 범인 분석 · 발화), `audio/<발화ID>.ogg`, `대화.txt`. 받아오기는 형식 · 버전 · 발화 ID · 말한 사람 · 시각 · 경기 연결 · 음성 파일(ogg 머리) · 개수를 모두 확인하고 하나라도 빠지면 아무것도 넣지 않고 "받아오기 실패: (이유)"로 끝낸다. 이미 있는 발화는 건너뛴다. 받아온 녹음의 보관 기간은 받아온 날부터 센다 (`utterance_imports`)
- 사이트 ↔ 게임 PC 중계: 큰 zip 을 1MB 조각으로 주고받는다 (사이트 서버 → 앱 요청 본문, 앱 → 사이트 서버 응답 모두)
## v1.3.6 바뀐 점
- **목소리 깨짐**: 녹음기가 디스코드 패킷이 "도착한 간격"으로 말 사이 쉼을 채웠다. 게임 중(CPU 부하)에는 패킷이 2~3개씩 몰려 와서 말 중간에 20ms 무음이 계속 끼었다 (사용자 파일: 실제 7.0초 발화가 8.5초, 패킷 3개 중 1개가 무음). 이제 RTP 타임스탬프로 패킷 자리를 정한다 (`recorder.ts` `tapRtp` · `Utterance.place`). 예전 녹음은 처음 켤 때 한 번 끼운 무음을 빼고 다시 변환한다 (`ogg.ts` `removeInsertedSilence`)

8
app/package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "gvr-app",
"version": "1.3.6",
"version": "1.3.7",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "gvr-app",
"version": "1.3.6",
"version": "1.3.7",
"license": "UNLICENSED",
"dependencies": {
"@discordjs/voice": "^0.19.2",
@@ -4677,7 +4677,7 @@
}
},
"node_modules/prism-media": {
"version": "1.3.6",
"version": "1.3.7",
"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.6",
"version": "1.3.7",
"resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz",
"integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==",
"dev": true,

View File

@@ -1,7 +1,7 @@
{
"name": "gvr-app",
"productName": "겜녹이",
"version": "1.3.6",
"version": "1.3.7",
"description": "겜녹이 (Game Voice Recorder) - 게임 연동 디스코드 음성 기록",
"private": true,
"main": "dist/main.cjs",

View File

@@ -161,15 +161,27 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
// zip 은 사이트 서버가 조각으로 나눠 보낸다. 300MB 까지
app.addContentTypeParser('application/zip', { parseAs: 'buffer', bodyLimit: 300 * 1024 * 1024 }, (_req, body, done) => done(null, body));
const bundleErr = (reply: any, e: unknown) => {
if (e instanceof BundleError) return reply.code(e.code === 'not_found' ? 404 : 400).send({ error: e.code, message: e.message });
if (e instanceof BundleError) return reply.code(e.code === 'not_found' ? 404 : e.code === 'busy' ? 409 : e.code === 'too_large' ? 413 : 400).send({ error: e.code, message: e.message });
throw e;
};
/** 사이트 중계로 온 요청이면 사이트 서버가 붙인 역할이 관리자여야 한다 (이 PC 안에서 부른 것은 그대로) */
const adminOnly = (req: any, reply: any): boolean => {
if (!req.headers['x-gvr-user']) return true;
if (req.headers['x-gvr-role'] === 'admin') return true;
reply.code(403).send({ error: 'forbidden', message: '기록 지우기 · 받아오기는 관리자만 할 수 있습니다' });
return false;
};
const exportZip = (reply: any, ids: string[]) => {
const { zip, fileName } = d.bundles!.export(ids);
return reply.header('content-type', 'application/zip').header('content-disposition', `attachment; filename="${fileName}"`).header('cache-control', 'no-store').send(zip);
};
app.get('/api/bundles', async (_req, reply) => {
if (!d.bundles) return reply.code(404).send({ error: 'not_found' });
return { bundles: d.bundles.list() };
});
app.post<{ Body: { ids?: string[] } }>('/api/bundles/delete', async (req, reply) => {
if (!d.bundles) return reply.code(404).send({ error: 'not_found' });
if (!adminOnly(req, reply)) return;
try {
const ids = Array.isArray(req.body?.ids) ? req.body.ids.map(String) : [];
const r = d.bundles.delete(ids);
@@ -183,14 +195,23 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
app.get<{ Querystring: { ids?: string } }>('/api/bundles/export', async (req, reply) => {
if (!d.bundles) return reply.code(404).send({ error: 'not_found' });
try {
const { zip, fileName } = d.bundles.export(String(req.query.ids ?? '').split(',').filter(Boolean));
return reply.header('content-type', 'application/zip').header('content-disposition', `attachment; filename="${fileName}"`).header('cache-control', 'no-store').send(zip);
return exportZip(reply, String(req.query.ids ?? '').split(',').filter(Boolean));
} catch (e) {
return bundleErr(reply, e);
}
});
// 많이 고르면 주소가 너무 길어진다: 본문으로 받는 것도 둔다
app.post<{ Body: { ids?: string[] } }>('/api/bundles/export', async (req, reply) => {
if (!d.bundles) return reply.code(404).send({ error: 'not_found' });
try {
return exportZip(reply, Array.isArray(req.body?.ids) ? req.body.ids.map(String) : []);
} catch (e) {
return bundleErr(reply, e);
}
});
app.post('/api/bundles/import', async (req, reply) => {
if (!d.bundles) return reply.code(404).send({ error: 'not_found' });
if (!adminOnly(req, reply)) return;
if (!Buffer.isBuffer(req.body)) return reply.code(400).send({ error: 'invalid_bundle', message: '받아오기 실패: zip 파일을 보내 주세요' });
try {
const r = d.bundles.import(req.body);

View File

@@ -17,6 +17,8 @@ const NEAR_MS = 30 * 60000;
/** 세션 없는 대화를 나누는 쉼 */
const TALK_GAP_MS = 30 * 60000;
const SAFE_ID = /^[\w.-]{1,80}$/;
/** 내보내기 음성 합계 한도 (받아오기 한도 300MB 안에 들어가게) */
export const EXPORT_MAX = 280 * 1024 * 1024;
export class BundleError extends Error {
constructor(
@@ -75,11 +77,9 @@ export class Bundles {
const label = `${m.game === 'valorant' ? '발로란트' : '롤'} · ${sum.mode} · ${sum.map.name}`;
const score = sum.score ? ` ${sum.score.ally}:${sum.score.enemy}` : '';
const result = sum.win === true ? '승리' : sum.win === false ? '패배' : null;
out.push({
info: this.info(`match-${m.id}`, 'match', label, [result, score.trim()].filter(Boolean).join(' ') || null, m.game, m.id, Math.min(mStart(m), ...list.map((r) => r.started_at)), Math.max(mEnd(m), ...list.map((r) => r.ended_at)), list, evCount.get(m.id) ?? 0),
ids: list.map((r) => r.id),
match: m,
});
const mi = this.info(`match-${m.id}`, 'match', label, [result, score.trim()].filter(Boolean).join(' ') || null, m.game, m.id, Math.min(mStart(m), ...list.map((r) => r.started_at)), Math.max(mEnd(m), ...list.map((r) => r.ended_at)), list, evCount.get(m.id) ?? 0);
mi.live = m.status === 'live';
out.push({ info: mi, ids: list.map((r) => r.id), match: m });
}
// 경기 밖 대화: 세션이 바뀌거나, 사이에 경기가 시작했거나, 30분 넘게 쉬면 새 묶음
const starts = matches.map(mStart).sort((a, b) => a - b);
@@ -140,6 +140,7 @@ export class Bundles {
events,
talkMs: shown.reduce((n, r) => n + (r.ended_at - r.started_at), 0),
users: [...new Set(shown.map((r) => r.user_id))],
live: false,
};
}
@@ -162,6 +163,9 @@ export class Bundles {
// ------------------------------------------------------------------ 지우기
delete(ids: string[]): { bundles: number; utterances: number; files: number } {
const groups = this.pick(ids);
// 진행 중인 경기는 지우지 않는다 (경기가 끝날 때 녹음 · 음성 인식 · 경기 상세가 이 경기를 찾는다)
const live = groups.find((g) => g.match && g.match.status === 'live');
if (live) throw new BundleError(`진행 중인 경기는 지울 수 없습니다: ${live.info.label} (경기가 끝난 뒤 지워 주세요)`, 'busy');
const db = this.store.db;
const uttIds = groups.flatMap((g) => g.ids);
const matchIds = groups.flatMap((g) => (g.match ? [g.match.id] : []));
@@ -203,7 +207,8 @@ export class Bundles {
const groups = this.pick(ids);
const db = this.store.db;
const uttIds = new Set(groups.flatMap((g) => g.ids));
const utts = [...uttIds].map((id) => this.store.getUtterance(id)!).filter(Boolean);
// 잡음 발화(사람이 고치지 않은 것)는 내보내지 않는다
const utts = [...uttIds].map((id) => this.store.getUtterance(id)!).filter((u) => u && (!u.noise || u.corrected));
const matches = groups.flatMap((g) => (g.match ? [g.match] : []));
const userIds = new Set(utts.map((u) => u.user_id));
const users = this.store.listUsers().filter((u) => userIds.has(u.id));
@@ -211,6 +216,15 @@ export class Bundles {
const sessIds = [...new Set(utts.map((u) => u.session_id).filter((s): s is string => !!s))];
const sessions = sessIds.map((s) => db.prepare('SELECT * FROM sessions WHERE id=?').get(s)).filter(Boolean);
const culprit = !!db.prepare(`SELECT 1 FROM sqlite_master WHERE type='table' AND name='culprit_analyses'`).get();
// 받아오기 한도(300MB)보다 크면 다시 넣을 수 없으니 나눠 받게 한다
const total = utts.reduce((n, u) => {
try {
return n + (u.audio_path && !u.audio_deleted ? fs.statSync(u.audio_path).size : 0);
} catch {
return n;
}
}, 0);
if (total > EXPORT_MAX) throw new BundleError(`한 번에 내려받기에는 너무 큽니다 (음성 ${Math.round(total / 1048576)}MB). 받아오기 한도가 ${EXPORT_MAX / 1048576}MB 라서, 묶음을 나눠서 골라 주세요`, 'too_large');
const entries: ZipEntry[] = [];
const outUtts = utts.map((u) => {
const { audio_path, ...rest } = u as UtteranceRow & { rowid?: number };
@@ -275,7 +289,7 @@ export class Bundles {
import(buf: Buffer): BundleImportResult {
let files: Map<string, Buffer>;
try {
files = readZip(buf);
files = readZip(buf, 600 * 1024 * 1024);
} catch (e) {
throw new BundleError(`받아오기 실패: ${e instanceof ZipError ? e.message : 'zip 파일을 읽지 못했습니다'}`);
}

View File

@@ -92,6 +92,8 @@ export class RelayClient {
}, 5000);
});
ws.on('message', (data, isBinary) => {
// 큰 zip 을 받는 동안에는 pong 이 조각 뒤에 밀린다. 무엇이든 받으면 살아 있는 것으로 본다
this.lastPong = Date.now();
if (isBinary) return this.onBinary(data as Buffer);
let msg: RelayToDevice;
try {
@@ -149,7 +151,7 @@ export class RelayClient {
}
try {
const headers: Record<string, string> = {};
for (const k of ['range', 'content-type', 'accept', 'x-gvr-internal']) if (req.headers[k]) headers[k] = req.headers[k];
for (const k of ['range', 'content-type', 'accept', 'x-gvr-internal', 'x-gvr-role']) if (req.headers[k]) headers[k] = req.headers[k];
if (req.user) headers['x-gvr-user'] = encodeURIComponent(JSON.stringify(req.user));
const res = await this.api.inject({ method: req.method as any, url: req.path, headers, payload: bin ?? req.body ?? undefined });
const outHeaders: Record<string, string> = {};
@@ -165,7 +167,13 @@ export class RelayClient {
head.writeUInt32BE(idBuf.length, 0);
// 사이트 서버는 한 메시지에 16MB 까지만 받는다. 1MB 씩 나눠 보낸다 (zip 내보내기)
const raw = res.rawPayload;
for (let i = 0; i < raw.length || i === 0; i += RELAY_CHUNK) this.ws?.send(Buffer.concat([head, idBuf, raw.subarray(i, i + RELAY_CHUNK)]), { binary: true });
const ws = this.ws;
for (let i = 0; i < raw.length || i === 0; i += RELAY_CHUNK) {
// 보낼 것이 4MB 넘게 쌓이면 잠깐 기다린다 (ping 이 밀려 연결이 끊기지 않게)
while (ws && ws.readyState === WebSocket.OPEN && ws.bufferedAmount > 4 * RELAY_CHUNK) await new Promise((r) => setTimeout(r, 20));
if (!ws || ws.readyState !== WebSocket.OPEN) break;
ws.send(Buffer.concat([head, idBuf, raw.subarray(i, i + RELAY_CHUNK)]), { binary: true });
}
this.send({ t: 'res_end', id: req.id });
} else {
this.send({ t: 'res', id: req.id, status: res.statusCode, headers: outHeaders, body: res.payload });

View File

@@ -23,6 +23,8 @@ interface Job {
slot: Slot;
/** 낮을수록 먼저 */
prio: number;
/** 예전 녹음 고친 뒤 다시 변환: 잡음으로 나오면 이전 결과를 지키고, 정밀 결과로만 덮는다 */
repair?: boolean;
}
export interface SttStatus {
@@ -147,11 +149,11 @@ export class SttPipeline {
for (const r of rows) this.enqueue(r.id, 'realtime', 5);
}
enqueue(id: string, slot: Slot, prio = slot === 'realtime' ? 1 : 10): void {
enqueue(id: string, slot: Slot, prio = slot === 'realtime' ? 1 : 10, repair = false): void {
const key = `${slot}:${id}`;
if (this.queued.has(key)) return;
this.queued.add(key);
this.queue.push({ id, slot, prio });
this.queue.push({ id, slot, prio, ...(repair ? { repair } : {}) });
this.queue.sort((a, b) => a.prio - b.prio);
this.status.queue = this.queue.length;
this.pump();
@@ -234,7 +236,7 @@ export class SttPipeline {
this.store.markUtteranceFailed(u.id);
return;
}
if (job.slot === 'precise' && (u.corrected || u.status === 'precise')) return;
if (job.slot === 'precise' && (u.corrected || (u.status === 'precise' && !job.repair))) return;
const s = this.settings();
const ctx = this.dictContext(u);
const user = this.store.getUser(u.user_id);
@@ -268,6 +270,10 @@ export class SttPipeline {
} else this.enqueue(u.id, job.slot, job.prio + 2);
return;
}
if (job.repair && r.noise) {
log.info(`예전 녹음 다시 변환: ${u.id} 는 잡음으로 나와 이전 결과를 그대로 둠`);
return;
}
this.store.updateUtteranceResult(u.id, {
text: r.text,
raw_text: r.raw_text,
@@ -292,7 +298,8 @@ export class SttPipeline {
*/
private onNoise(u: UtteranceRow, r: TranscribeResult, slot: Slot): void {
const s = this.settings().stt;
const recheck = slot === 'realtime' && r.noise_reason !== 'vad' && this.inMatch && s.reprocessAfterMatch && s.preciseModel !== s.realtimeModel;
// 경기 중이거나 경기 뒤 정밀 변환이 이미 대기열에 있으면(실시간 변환이 늦게 끝난 경우) 그때까지 파일을 남긴다
const recheck = slot === 'realtime' && r.noise_reason !== 'vad' && (this.inMatch || this.queued.has(`precise:${u.id}`)) && s.reprocessAfterMatch && s.preciseModel !== s.realtimeModel;
const name = this.store.getUser(u.user_id)?.name ?? u.user_id;
const dur = ((u.ended_at - u.started_at) / 1000).toFixed(1);
const why = NOISE_REASON[r.noise_reason ?? ''] ?? r.noise_reason ?? '?';
@@ -323,25 +330,37 @@ export class SttPipeline {
*/
private repairOldAudio(): void {
const KEY = 'audio_repair_v136';
const CUT = 'audio_repair_v136_before';
if (this.store.meta(KEY)) return;
this.store.setMeta(KEY, String(Date.now()));
// 이 시각 전에 만든 녹음만 고친다 (새 녹음기는 진짜 쉼만 채우므로 건드리면 안 됨). 중간에 꺼져도 다음에 이어서
if (!this.store.meta(CUT)) this.store.setMeta(CUT, String(Date.now()));
const before = Number(this.store.meta(CUT));
const rows = this.store.db
.prepare(`SELECT rowid,* FROM utterances WHERE audio_deleted=0 AND audio_path IS NOT NULL AND noise=0 ORDER BY started_at`)
.all() as UtteranceRow[];
.prepare(`SELECT rowid,* FROM utterances WHERE audio_deleted=0 AND audio_path IS NOT NULL AND noise=0 AND created_at<? ORDER BY started_at`)
.all(before) as UtteranceRow[];
let fixed = 0;
for (const u of rows) {
if (!u.audio_path || !fs.existsSync(u.audio_path)) continue;
try {
const removed = removeInsertedSilence(u.audio_path);
if (!removed) continue;
fixed++;
this.store.db.prepare('UPDATE utterances SET ended_at=ended_at-? WHERE id=?').run(removed * 20, u.id);
if (!u.corrected) this.enqueue(u.id, 'realtime', 20);
} catch (e) {
log.warn(`예전 녹음 고치기 실패 ${u.id}`, e);
let i = 0;
// 한 번에 20개씩 (시작할 때 화면 · 녹음이 멈추지 않게)
const step = () => {
for (const u of rows.slice(i, i + 20)) {
if (!u.audio_path || !fs.existsSync(u.audio_path)) continue;
try {
const removed = removeInsertedSilence(u.audio_path);
if (!removed) continue;
fixed++;
this.store.db.prepare('UPDATE utterances SET ended_at=ended_at-? WHERE id=?').run(removed * 20, u.id);
// 정밀 모델로만 다시 변환한다 (실시간 모델로 정밀 결과를 덮지 않게)
if (!u.corrected) this.enqueue(u.id, 'precise', 20, true);
} catch (e) {
log.warn(`예전 녹음 고치기 실패 ${u.id}`, e);
}
}
}
if (fixed) log.info(`예전 녹음 ${fixed}개에서 말 중간에 끼운 무음을 빼고 다시 변환`);
i += 20;
if (i < rows.length) return void setTimeout(step, 0);
this.store.setMeta(KEY, String(Date.now()));
if (fixed) log.info(`예전 녹음 ${fixed}개에서 말 중간에 끼운 무음을 빼고 정밀 모델로 다시 변환`);
};
step();
}
/** v1.3.5 이하에서 잡음으로 판정된 발화의 남은 파일 정리 */

View File

@@ -94,7 +94,7 @@ test('기록 묶음: zip 내보내기 → 지우기 → 받아오기로 그대
assert.equal(b.list().length, 1);
// 받아오기
const imp = b.import(zip);
assert.equal(imp.added.utterances, 6);
assert.equal(imp.added.utterances, 5, '잡음 발화는 내보내지 않는다');
assert.equal(imp.added.matches, 1);
assert.equal(imp.added.events, 1);
assert.equal(imp.skipped, 0);
@@ -103,7 +103,7 @@ test('기록 묶음: zip 내보내기 → 지우기 → 받아오기로 그대
assert.ok(fs.existsSync(store.getUtterance('in1')!.audio_path!));
assert.equal(store.rounds('val-1').length, 1);
// 같은 zip 을 또 받으면 건너뛴다
assert.equal(b.import(zip).skipped, 6);
assert.equal(b.import(zip).skipped, 5);
// 받아온 녹음은 보관 기간을 받아온 날부터 센다 (녹음 날짜가 오래돼도 바로 지우지 않음)
const ret = new Retention(store, () => 7, () => audio).run(Date.now());
assert.equal(ret.deleted, 1, '받아오지 않은 다른 날 발화만 지운다');
@@ -111,6 +111,16 @@ test('기록 묶음: zip 내보내기 → 지우기 → 받아오기로 그대
store.close();
});
test('기록 묶음: 진행 중인 경기는 지우지 않는다', () => {
const { store, b } = seed(tmp());
store.db.prepare(`UPDATE matches SET status='live' WHERE id='val-1'`).run();
const m = b.list().find((x) => x.kind === 'match')!;
assert.equal(m.live, true);
assert.throws(() => b.delete([m.id]), (e: any) => e instanceof BundleError && e.code === 'busy');
assert.ok(store.getMatch('val-1'));
store.close();
});
test('기록 묶음: 다른 프로그램으로 다시 압축한(deflate) zip 도 받는다', () => {
const dir = tmp();
const { store, b } = seed(dir);

View File

@@ -96,6 +96,10 @@ test('E2E: 발화 → STT 워커 → DB → 실시간 이벤트 → 기록 API',
const ex = await core.api.inject({ method: 'GET', url: `/api/bundles/export?ids=${bl[0].id}` });
assert.equal(ex.headers['content-type'], 'application/zip');
assert.match(String(ex.headers['content-disposition']), /attachment; filename="gvr-talk-\d{8}-\d{4}\.zip"/);
// 사이트 중계로 온 요청은 사이트 서버가 붙인 역할이 관리자여야 한다
const user = encodeURIComponent(JSON.stringify({ id: 'm1', name: 'x', avatar: null }));
assert.equal((await core.api.inject({ method: 'POST', url: '/api/bundles/delete', headers: { 'x-gvr-user': user, 'x-gvr-role': 'member' }, payload: { ids: [bl[0].id] } })).statusCode, 403);
assert.equal((await core.api.inject({ method: 'POST', url: '/api/bundles/delete', headers: { 'x-gvr-user': user }, payload: { ids: [bl[0].id] } })).statusCode, 403);
const del = (await core.api.inject({ method: 'POST', url: '/api/bundles/delete', payload: { ids: [bl[0].id] } })).json();
assert.equal(del.utterances, 3);
assert.equal((await core.api.inject({ method: 'GET', url: '/api/timeline' })).json().items.length, 0);
@@ -103,7 +107,7 @@ test('E2E: 발화 → STT 워커 → DB → 실시간 이벤트 → 기록 API',
assert.equal(bad.statusCode, 400);
assert.match(bad.json().message, /^받아오기 실패/);
const imp = (await core.api.inject({ method: 'POST', url: '/api/bundles/import', headers: { 'content-type': 'application/zip' }, payload: ex.rawPayload })).json();
assert.equal(imp.added.utterances, 3);
assert.equal(imp.added.utterances, 2, '잡음(keys)은 내보내지 않는다');
assert.equal((await core.api.inject({ method: 'GET', url: '/api/timeline' })).json().items.length, 2);
assert.ok(live.some((e) => e.type === 'records.changed'));
} finally {

View File

@@ -204,3 +204,20 @@ VOICE E2E PASS
- 데스매치: 실시간 점수(킬)를 라운드로 착각 → "R10 · R22 · R36 · R48 · R63" 가짜 라운드, 경기 상세는 344킬이 "라운드 1" 하나라 에이스 11개. 경기 상세의 선수 이름이 비어 와서 "주인 계정 자동 연결: #"
- 테스트: 앱 48 · 사이트 서버 16 · 워커 42 통과, 앱 · 화면 타입 검사 통과. 실제 STT 워커 E2E 에서 잡음 파일 삭제 · `/api/utterances/:id/info` 확인. 사이트 서버 테스트에서 게임 PC 끊긴 뒤 관리자만 로그를 보고 내려받는 것 확인
- 배포: 사이트 서버 다시 배포 (`data/logs/site-날짜.log` 생성 · `[discord]` · `[http]` 줄 확인, `/site/logs` 로그인 없이 401), Windows CI (fa6126e, full) 7개 모두 PASS (zip 안 워커에 `av/filter` 포함) · 앱 버전 1.3.6 → Gitea 릴리스 v1.3.6 (v1.3.5 에 새 버전 안내)
## v1.3.7 — 기록 관리(경기별 묶음 · zip 내보내기/받아오기) · 검토로 찾은 오류 고침 (2026-10-16)
- 기록 묶음: 경기 = 묶음 하나, 경기 밖 대화는 녹음 세션 안에서 경기 사이마다 묶고 30분 기준으로 "경기 전 대화" · "경기 후 대화" · "게임 밖 대화". 사용자 실제 데이터(사본)로 확인: 경기 전 대화 7개 → 데스매치 11개 → 경기 후 대화 3개, 3묶음 zip 1.0MB
- 테스트 `bundles.test.ts`: 나누기, 내보내기 → 지우기 → 받아오기 그대로 복원(경기 · 라운드 · 이벤트 · 음성), 같은 zip 다시 받기는 건너뜀, 받아온 녹음은 보관 기간을 받아온 날부터, 다른 프로그램으로 다시 압축(deflate)한 zip, 받아오기 실패 9가지(zip 아님 · manifest · data 없음 · 음성 없음 · ogg 아님 · 다른 형식 · 말한 사람 없음 · 경기 기록 없음 · 발화 수 다름 → 아무것도 넣지 않음), 진행 중인 경기는 지우지 않음
- 사이트 서버 테스트: 20MB zip 내보내기 · 받아오기가 1MB 조각으로 그대로 오가는 것, 지우기 · 받아오기는 관리자만 (`/api/%62undles/delete` 같은 우회도 403)
- 전체 검토(v1.3.6 · v1.3.7 변경 3,600줄)로 찾아 고친 오류:
1. 기록 지우기 관리자 확인을 주소 %인코딩으로 우회 가능 → 주소를 풀어서 확인, 앱도 사이트가 붙인 역할로 한 번 더 확인
2. 큰 zip 을 주고받는 동안 앱이 pong 을 못 받아 사이트 연결을 스스로 끊음 → 무엇이든 받으면 살아 있는 것으로, 보낼 것이 4MB 넘게 쌓이면 기다림
3. 진행 중인 경기를 지우면 경기 끝 처리(정밀 변환 등)가 멈춤 → 진행 중인 경기는 지울 수 없음
4. 내보낸 zip 이 받아오기 한도(300MB)보다 클 수 있음 → 280MB 넘으면 나눠 받게 안내
5. 예전 녹음 고치기가 정밀 결과를 실시간 모델 결과로 덮고, 잡음으로 나오면 파일을 지울 수 있었음 · 시작할 때 한꺼번에 처리 → 정밀 모델로만, 잡음이면 이전 결과 유지, 20개씩, 중간에 꺼져도 이어서 (업그레이드 전에 만든 녹음만)
6. 타임라인 최신순에서 오래된 발화가 고쳐지면 맨 아래에 붙음 → 더 불러올 페이지가 남아 있으면 넣지 않음
7. 반복 줄이기가 숫자를 망가뜨림 ("1000원 줘 줘 줘" → "10원 줘") → 숫자 · 붙은 한 글자 반복은 그대로
8. TTS 속도 바꾸기가 중간에 죽으면 반쪽 파일이 계속 쓰임 → 다 만든 뒤 이름 바꾸기
- 그 밖: 브라우저 오류 로그에 검색어가 남던 것, 경기 끝 직후 늦게 끝난 실시간 변환의 잡음 파일을 정밀 확인 전에 지우던 것, 많이 골랐을 때 내려받기 주소가 너무 길던 것(본문으로 보냄), zip 풀기 메모리 한도 600MB, 날짜 묶음이 "10월"로만 나오던 것(경기 · 기록 목록)
- 테스트: 앱 53 · 사이트 서버 16 · 워커 42 통과, 타입 검사 통과

Binary file not shown.

After

Width:  |  Height:  |  Size: 153 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 142 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 159 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 609 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View File

@@ -300,6 +300,8 @@ export interface BundleInfo {
events: number;
talkMs: number;
users: string[];
/** 진행 중인 경기 (지울 수 없음) */
live: boolean;
}
export interface BundleImportResult {

View File

@@ -244,11 +244,19 @@ export async function buildServer(
if (origin && origin !== cfg.publicUrl) return reply.code(403).send({ error: 'bad_origin' });
}
// 기록 묶음 지우기 · 받아오기는 관리자만 (보기 · zip 내려받기는 서버 멤버 누구나)
const p = req.url.split('?')[0];
// 주소는 풀어서(%62undles 같은 우회 막기) 소문자로 본다. 앱도 역할 헤더로 한 번 더 막는다
let p: string;
try {
p = decodeURIComponent(req.url.split('?')[0]).toLowerCase();
} catch {
return reply.code(400).send({ error: 'bad_path' });
}
const bundles = p.startsWith('/api/bundles');
if (bundles && req.method !== 'GET' && !canViewLogs(s.user.id)) return reply.code(403).send({ error: 'forbidden', message: '기록 지우기 · 받아오기는 관리자만 할 수 있습니다' });
const admin = canViewLogs(s.user.id);
if (bundles && p !== '/api/bundles' && p !== '/api/bundles/export' && !admin) return reply.code(403).send({ error: 'forbidden', message: '기록 지우기 · 받아오기는 관리자만 할 수 있습니다' });
const headers: Record<string, string> = {};
for (const k of ['range', 'content-type', 'accept']) if (req.headers[k]) headers[k] = String(req.headers[k]);
headers['x-gvr-role'] = admin ? 'admin' : 'member';
const body = req.body === undefined || req.body === null ? null : Buffer.isBuffer(req.body) || typeof req.body === 'string' ? req.body : JSON.stringify(req.body);
try {
// zip 만들기 · 받아오기는 오래 걸릴 수 있다

View File

@@ -201,14 +201,21 @@ export class RelayHub {
}, timeoutMs);
this.pending.set(id, { resolve, reject, timer, chunks: [] });
if (Buffer.isBuffer(body)) {
// 바이너리 본문(zip 받아오기): 1MB 조각으로 먼저 보내고 요청을 보낸다 (앱은 한 메시지 8MB 까지)
// 바이너리 본문(zip 받아오기): 1MB 조각으로 먼저 보내고 요청을 보낸다 (앱은 한 메시지 8MB 까지).
// 보낼 것이 4MB 넘게 쌓이면 기다려서 ping · pong 이 너무 밀리지 않게 한다
const idBuf = Buffer.from(id, 'utf8');
const head = Buffer.alloc(4);
head.writeUInt32BE(idBuf.length, 0);
const CH = 1024 * 1024;
for (let i = 0; i < body.length; i += CH) dev.ws.send(Buffer.concat([head, idBuf, body.subarray(i, i + CH)]), { binary: true });
const msg: RelayToDevice = { t: 'req', id, method, path, headers, user, body: null, bin: true };
dev.ws.send(JSON.stringify(msg));
void (async () => {
for (let i = 0; i < body.length; i += CH) {
while (dev.ws.readyState === WebSocket.OPEN && dev.ws.bufferedAmount > 4 * CH) await new Promise((r) => setTimeout(r, 20));
if (dev.ws.readyState !== WebSocket.OPEN) return;
dev.ws.send(Buffer.concat([head, idBuf, body.subarray(i, i + CH)]), { binary: true });
}
const msg: RelayToDevice = { t: 'req', id, method, path, headers, user, body: null, bin: true };
dev.ws.send(JSON.stringify(msg));
})();
return;
}
const msg: RelayToDevice = { t: 'req', id, method, path, headers, user, body };

View File

@@ -131,7 +131,9 @@ test('사이트 서버: 로그인 → 기기 등록·연결 → 중계(JSON·음
const ex = await fetch(base + '/api/bundles/export?ids=match-1', { headers: { cookie: sid } });
assert.equal(ex.headers.get('content-disposition'), 'attachment; filename="gvr-test.zip"');
assert.ok(Buffer.from(await ex.arrayBuffer()).equals(big));
// 받아오기는 관리자만
// 받아오기 · 지우기는 관리자만 (주소를 %인코딩해 돌아가도 막힌다)
for (const u of ['/api/bundles/delete', '/api/%62undles/delete', '/api/BUNDLES/delete', '/api/bundles%2Fdelete'])
assert.equal((await fetch(base + u, { method: 'POST', headers: { cookie: sid, 'content-type': 'application/json', origin: cfg.publicUrl }, body: '{"ids":["x"]}' })).status, 403, u);
assert.equal((await fetch(base + '/api/bundles/import', { method: 'POST', headers: { cookie: sid, 'content-type': 'application/zip', origin: cfg.publicUrl }, body: big })).status, 403);
store.upsertAppUser({ id: 'member1', name: '하늘', avatar: null, role: 'admin', addedBy: 'test' });
const im = (await (await fetch(base + '/api/bundles/import', { method: 'POST', headers: { cookie: sid, 'content-type': 'application/zip', origin: cfg.publicUrl }, body: big })).json()) as any;

View File

@@ -268,7 +268,7 @@ async function handle(req, res) {
const out = [];
for (const mt of db.matches) {
const us = db.utterances.filter((u) => u.game?.matchId === mt.id);
out.push({ id: `match-${mt.id}`, kind: 'match', label: `${mt.game === 'valorant' ? '발로란트' : '롤'} · ${mt.mode} · ${mt.map.name}`, sub: mt.score ? `${mt.win ? '승리' : '패배'} ${mt.score.ally}:${mt.score.enemy}` : null, game: mt.game, matchId: mt.id, from: mt.startedAt, to: mt.endedAt ?? mt.startedAt, utterances: us.length, audio: us.filter((u) => u.audio).length, audioBytes: us.length * 41230, events: mt.events.length, talkMs: us.reduce((n, u) => n + u.endTs - u.ts, 0), users: [...new Set(us.map((u) => u.userId))] });
out.push({ id: `match-${mt.id}`, kind: 'match', label: `${mt.game === 'valorant' ? '발로란트' : '롤'} · ${mt.mode} · ${mt.map.name}`, sub: mt.score ? `${mt.win ? '승리' : '패배'} ${mt.score.ally}:${mt.score.enemy}` : null, game: mt.game, matchId: mt.id, from: mt.startedAt, to: mt.endedAt ?? mt.startedAt, utterances: us.length, audio: us.filter((u) => u.audio).length, audioBytes: us.length * 41230, events: mt.events.length, talkMs: us.reduce((n, u) => n + u.endTs - u.ts, 0), users: [...new Set(us.map((u) => u.userId))], live: false });
}
const talk = db.utterances.filter((u) => !u.game && !u.noise).sort((a, b) => a.ts - b.ts);
const runs = [];
@@ -281,11 +281,16 @@ async function handle(req, res) {
const from = r[0].ts, to = r[r.length - 1].endTs;
const next = db.matches.find((mt) => mt.startedAt >= to && mt.startedAt - to < 30 * 60000);
const prev = db.matches.find((mt) => (mt.endedAt ?? 0) <= from && from - (mt.endedAt ?? 0) < 30 * 60000);
out.push({ id: `talk-${r[0].id}`, kind: 'talk', label: next ? '경기 전 대화' : prev ? '경기 후 대화' : '게임 밖 대화', sub: next ? `다음 경기: ${next.map.name}` : prev ? `지난 경기: ${prev.map.name}` : null, game: null, matchId: null, from, to, utterances: r.length, audio: r.filter((u) => u.audio).length, audioBytes: r.length * 41230, events: 0, talkMs: r.reduce((n, u) => n + u.endTs - u.ts, 0), users: [...new Set(r.map((u) => u.userId))] });
out.push({ id: `talk-${r[0].id}`, kind: 'talk', label: next ? '경기 전 대화' : prev ? '경기 후 대화' : '게임 밖 대화', sub: next ? `다음 경기: ${next.map.name}` : prev ? `지난 경기: ${prev.map.name}` : null, game: null, matchId: null, from, to, utterances: r.length, audio: r.filter((u) => u.audio).length, audioBytes: r.length * 41230, events: 0, talkMs: r.reduce((n, u) => n + u.endTs - u.ts, 0), users: [...new Set(r.map((u) => u.userId))], live: false });
}
return json(res, 200, { bundles: out.sort((a, b) => b.from - a.from) });
}
if (p === '/api/bundles/delete' && req.method === 'POST') return json(res, 200, { bundles: 1, utterances: 12, files: 12 });
if (p === '/api/bundles/export' && req.method === 'POST') {
req.resume();
res.writeHead(200, { 'content-type': 'application/zip', 'content-disposition': 'attachment; filename="gvr-valorant-20261016-0430.zip"' });
return res.end(Buffer.from('PK\x05\x06' + '\0'.repeat(18)));
}
if (p === '/api/bundles/import' && req.method === 'POST') {
req.resume();
return json(res, 400, { error: 'invalid_bundle', message: '받아오기 실패: manifest.json 이 없습니다 (겜녹이에서 내보낸 기록 zip 이 아닙니다)' });

View File

@@ -164,7 +164,17 @@ export const api = {
/** 기록 묶음 (v1.3.7~ 앱) */
bundles: () => request<{ bundles: BundleInfo[] }>('/api/bundles').then((r) => r.bundles),
deleteBundles: (ids: string[]) => request<{ bundles: number; utterances: number; files: number }>('/api/bundles/delete', { method: 'POST', body: JSON.stringify({ ids }) }),
bundleExportUrl: (ids: string[]) => `/api/bundles/export?ids=${ids.map(encodeURIComponent).join(',')}`,
/** zip 내려받기 (많이 골라도 되게 본문으로 보낸다). 파일 이름은 앱이 정한 것 */
exportBundles: async (ids: string[]): Promise<{ blob: Blob; fileName: string }> => {
const res = await fetch('/api/bundles/export', { method: 'POST', credentials: 'include', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ ids }) });
if (!res.ok) {
const b = await res.json().catch(() => ({}));
if (res.status === 503) emit('device_offline');
throw new Error(b.message ?? `zip 을 받지 못했습니다 (${res.status})`);
}
const cd = res.headers.get('content-disposition') ?? '';
return { blob: await res.blob(), fileName: /filename="([^"]+)"/.exec(cd)?.[1] ?? 'gvr-records.zip' };
},
/** zip 받아오기. 실패하면 서버가 준 이유("받아오기 실패: …")를 담은 Error */
importBundle: async (file: Blob): Promise<BundleImportResult> => {
let res: Response;

View File

@@ -11,7 +11,7 @@ export function reportClient(level: 'warn' | 'error', message: string, detail?:
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ level, message: message.slice(0, 500), detail: detail?.slice(0, 2000), page: location.pathname + location.search }),
body: JSON.stringify({ level, message: message.slice(0, 500), detail: detail?.slice(0, 2000), page: location.pathname /* 검색어 등 쿼리는 남기지 않는다 */ }),
keepalive: true,
}).catch(() => undefined);
}

View File

@@ -60,15 +60,26 @@ export function RecordsPage() {
const picked = (list ?? []).filter((b) => sel.has(b.id));
const toggle = (id: string) => setSel((s) => (s.has(id) ? new Set([...s].filter((x) => x !== id)) : new Set([...s, id])));
const download = (ids: string[]) => {
const download = async (ids: string[]) => {
sfx('click');
const a = document.createElement('a');
a.href = api.bundleExportUrl(ids);
a.download = '';
document.body.appendChild(a);
a.click();
a.remove();
setMsg({ ok: true, text: `zip 을 만드는 중입니다. 묶음이 크면 내려받기가 시작될 때까지 조금 걸립니다.` });
setBusy('export');
setMsg({ ok: true, text: 'zip 을 만들어 받는 중입니다. 묶음이 크면 조금 걸립니다…' });
try {
const { blob, fileName } = await api.exportBundles(ids);
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = fileName;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 30000);
setMsg({ ok: true, text: `${fileName} (${fmtMB(blob.size)}) 내려받기를 시작했습니다` });
} catch (e) {
setMsg({ ok: false, text: (e as Error).message });
} finally {
setBusy(null);
}
};
const doDelete = async (bs: BundleInfo[]) => {
setBusy('delete');
@@ -79,7 +90,7 @@ export function RecordsPage() {
setConfirm(null);
load();
} catch (e) {
setMsg({ ok: false, text: e instanceof ApiError && e.status === 403 ? '지우기는 관리자만 할 수 있습니다' : '지우지 못했습니다' });
setMsg({ ok: false, text: e instanceof ApiError && e.status === 403 ? '지우기는 관리자만 할 수 있습니다' : e instanceof ApiError && e.status === 409 ? '진행 중인 경기는 지울 수 없습니다 (경기가 끝난 뒤 지워 주세요)' : '지우지 못했습니다' });
} finally {
setBusy(null);
}
@@ -155,11 +166,11 @@ export function RecordsPage() {
<span className="dim">
발화 {picked.reduce((n, b) => n + b.utterances, 0)}개 · 음성 {fmtMB(picked.reduce((n, b) => n + b.audioBytes, 0))}
</span>
<button className="chip on" onClick={() => download(picked.map((b) => b.id))}>
<button className="chip on" disabled={busy === 'export'} onClick={() => void download(picked.map((b) => b.id))}>
<IDownload width={14} height={14} /> 한 번에 zip
</button>
{admin && (
<button className="chip danger" onClick={() => setConfirm(picked)}>
<button className="chip danger" disabled={picked.some((b) => b.live)} title={picked.some((b) => b.live) ? '진행 중인 경기는 지울 수 없습니다' : undefined} onClick={() => setConfirm(picked)}>
🗑 한 번에 지우기
</button>
)}
@@ -184,7 +195,7 @@ export function RecordsPage() {
</label>
</h4>
{bs.map((b) => (
<BundleRow key={b.id} b={b} on={sel.has(b.id)} admin={admin} onToggle={() => toggle(b.id)} onView={() => view(b)} onZip={() => download([b.id])} onDelete={() => setConfirm([b])} />
<BundleRow key={b.id} b={b} on={sel.has(b.id)} admin={admin} busy={busy === 'export'} onToggle={() => toggle(b.id)} onView={() => view(b)} onZip={() => void download([b.id])} onDelete={() => setConfirm([b])} />
))}
</section>
))}
@@ -203,7 +214,7 @@ export function RecordsPage() {
</ul>
<p className="dim small">발화 · 음성 파일 · 경기 기록(킬 · 라운드 · 범인 분석)이 게임 PC 에서 지워지고 되돌릴 수 없습니다. 먼저 zip 으로 받아 두면 "받아오기"로 다시 넣을 수 있습니다.</p>
<div className="ctx-foot">
<button className="chip" onClick={() => download(confirm.map((b) => b.id))}>
<button className="chip" disabled={busy === 'export'} onClick={() => void download(confirm.map((b) => b.id))}>
<IDownload width={14} height={14} /> 먼저 zip 받기
</button>
<button className="chip danger" disabled={busy === 'delete'} onClick={() => void doDelete(confirm)}>
@@ -220,7 +231,7 @@ export function RecordsPage() {
);
}
function BundleRow({ b, on, admin, onToggle, onView, onZip, onDelete }: { b: BundleInfo; on: boolean; admin: boolean; onToggle: () => void; onView: () => void; onZip: () => void; onDelete: () => void }) {
function BundleRow({ b, on, admin, busy, onToggle, onView, onZip, onDelete }: { b: BundleInfo; on: boolean; admin: boolean; busy: boolean; onToggle: () => void; onView: () => void; onZip: () => void; onDelete: () => void }) {
const { userById } = useData();
const icon = b.kind === 'match' ? (b.game === 'lol' ? '🏆' : '🎯') : '💬';
return (
@@ -230,6 +241,7 @@ function BundleRow({ b, on, admin, onToggle, onView, onZip, onDelete }: { b: Bun
<div className="rec-main" onClick={onView} role="button" title="기록 보기">
<div className="rec-title">
<b>{b.label}</b>
{b.live && <span className="rec-live">● 진행 중</span>}
{b.sub && <span className="dim">· {b.sub}</span>}
</div>
<div className="rec-meta dim">
@@ -249,11 +261,11 @@ function BundleRow({ b, on, admin, onToggle, onView, onZip, onDelete }: { b: Bun
<button className="chip" onClick={onView}>
기록 보기
</button>
<button className="chip" onClick={onZip} title="이 묶음을 zip 으로 내려받기 (음성 ogg · 대화.txt 포함)">
<button className="chip" disabled={busy} onClick={onZip} title="이 묶음을 zip 으로 내려받기 (음성 ogg · 대화.txt 포함)">
<IDownload width={14} height={14} /> zip
</button>
{admin && (
<button className="chip danger" onClick={onDelete} title="이 묶음 지우기">
<button className="chip danger" disabled={b.live} onClick={onDelete} title={b.live ? '진행 중인 경기는 끝난 뒤 지울 수 있습니다' : '이 묶음 지우기'}>
🗑
</button>
)}

View File

@@ -317,7 +317,8 @@ export function TimelinePage() {
setItems((prev) => {
if (prev.some((p) => p.id === it.id)) return prev.map((p) => (p.id === it.id ? it : p));
const i = prev.findIndex((p) => (order === 'desc' ? p.ts < it.ts : p.ts > it.ts));
if (i < 0) return order === 'asc' && next ? prev : [...prev, it];
// 불러온 것보다 오래된(또는 시간순에서 뒤의) 항목: 더 불러올 페이지가 남아 있으면 그때 나온다
if (i < 0) return next ? prev : [...prev, it];
return [...prev.slice(0, i), it, ...prev.slice(i)];
});
}

View File

@@ -3875,3 +3875,12 @@ button.match:hover {
display: none;
}
}
.rec-live {
color: var(--accent);
font-size: 12px;
font-weight: 700;
}
.chip:disabled {
opacity: 0.45;
cursor: default;
}

View File

@@ -183,14 +183,25 @@ def judge_repetition(text: str, segs: list[SegInfo], sensitivity: float) -> bool
return any(s.compression_ratio > t.compression + 0.4 for s in segs) and len(norm) >= 12
_REPEAT_RE = re.compile(r"(.{1,10}?)(?:\s*\1){2,}")
_REPEAT_RE = re.compile(r"(\S{1,10}?)((?:\s*\1){2,})")
def _collapse_one(m: re.Match[str]) -> str:
unit, rest = m.group(1), m.group(2)
# 숫자는 줄이지 않는다 ("1000원" → "10원" 이 되면 안 됨)
if any(ch.isdigit() for ch in unit):
return m.group(0)
# 한 글자 반복은 띄어 쓴 경우("아 아 아")만 고리로 본다 ("www", "ㅋㅋㅋ" 같은 한 덩어리는 그대로)
if len(unit) == 1 and not rest[:1].isspace():
return m.group(0)
return unit
def collapse_repetition(text: str) -> str:
"""Whisper 반복 고리("페이스페이스페이스…", "아 아 아 아")를 한 번으로 줄인다."""
"""Whisper 반복 고리("페이스페이스페이스…", "아 아 아 아")를 한 번으로 줄인다. 숫자 · 붙어 있는 한 글자 반복은 그대로."""
out = text.strip()
for _ in range(3):
nxt = _REPEAT_RE.sub(lambda m: m.group(1), out)
nxt = _REPEAT_RE.sub(_collapse_one, out)
if nxt == out:
break
out = nxt

View File

@@ -6,6 +6,7 @@ Edge TTS 는 말 속도를 0.5배까지만 늦춘다. 그보다 느리게(0.1~0.
from __future__ import annotations
import os
from fractions import Fraction
from .protocol import WorkerError
@@ -29,7 +30,9 @@ def change_tempo(src: str, dst: str, tempo: float) -> dict[str, float]:
import av.filter
chain = atempo_chain(tempo)
with av.open(src) as inp, av.open(dst, "w", format="ogg") as out:
# 다 만든 뒤에만 이름을 바꾼다 (중간에 죽어도 반쪽 파일이 안내 음성으로 남지 않게)
tmp = f"{dst}.part"
with av.open(src) as inp, av.open(tmp, "w", format="ogg") as out:
ist = inp.streams.audio[0]
ost = out.add_stream("libopus", rate=48000)
ost.layout = "mono"
@@ -66,4 +69,5 @@ def change_tempo(src: str, dst: str, tempo: float) -> dict[str, float]:
drain()
for p in ost.encode(None):
out.mux(p)
os.replace(tmp, dst)
return {"duration_s": round(dur, 3), "stages": len(chain)}

View File

@@ -47,3 +47,7 @@ def test_collapse_repetition() -> None:
assert collapse_repetition("아 아 아 아 아 아 아 아") == "아"
assert collapse_repetition("가자 가자") == "가자 가자"
assert collapse_repetition("레이즈 궁 빠졌어") == "레이즈 궁 빠졌어"
# 숫자 · 붙어 있는 한 글자 반복은 줄이지 않는다
assert collapse_repetition("1000원 줘 줘 줘 줘 줘") == "1000원 줘"
assert collapse_repetition("그래 그래 그래 2000 원") == "그래 2000 원"
assert collapse_repetition("www 다시") == "www 다시"