Author SHA1 Message Date
csbaeandClaude Opus 5 b115663ecf feat: 서버 STT 재전사 — 오디오 원본에서 확정 전사문을 뽑는다
#18이 오디오를 남기게 했다면, 이 PR은 그 오디오를 실제로 쓴다.
Web Speech 포착률 7~10%를 끌어올리는 유일한 방법은 인식 엔진 교체다.

## 두 경로가 하나로 만난다

    실시간 녹음 ─┐
                 ├→ recordingId → /api/transcribe → 확정 전사문
    파일 업로드 ─┘

`/api/upload`는 파일을 디스크에 떨궈만 두고 "실시간 녹음 탭에서 하세요"라고
안내하던 막다른 길이었다. 이제 녹음 저장소에 넣고 recordingId를 돌려주므로
브라우저 녹음과 완전히 같은 파이프라인을 탄다.

## 실제 타임스탬프

Whisper `verbose_json`이 구간별 실제 오디오 시각을 준다. Web Speech 경로가 쓰던
`결과 이벤트 시각 − 2초` 추정값과 달리 구간 재생·화자 분리에 그대로 쓸 수 있다.
이 값이 있어야 PR #17의 diarization 화자 배정이 비로소 의미를 갖는다.

verbose_json을 지원하지 않는 모델(gpt-4o-transcribe 등)은 400을 주므로 `json`
으로 한 번 더 시도해 텍스트만이라도 받는다.

## 프로바이더별 지원

| 프로바이더 | webm 녹음 | 업로드 파일 | 기본 모델 |
|---|:---:|:---:|---|
| OpenAI · OrcaRouter · 로컬 whisper | O | O | whisper-1 |
| Gemini | X | O | gemini-3.6-flash |

Gemini가 문서로 밝힌 오디오 형식에 webm이 없다. 조용히 실패시키지 않고
"OpenAI 호환 프로바이더를 쓰라"고 명시적으로 안내하며, 설정 화면에도 경고를 띄운다.

## 비트레이트 128k → 32k

이 오디오는 감상용이 아니라 STT 입력이다. 128kbps면 46분 회의가 44MB가 되어
Whisper 상한(25MB)도 Gemini inline 상한도 넘긴다. 32kbps mono Opus는 음성
인식 정확도에 영향이 없으면서 46분을 11MB로 줄인다.

## 참석자·용어 힌트

홈 화면에 입력란을 두고 전사 요청의 어휘 힌트로 보낸다. 실측 transcript에서
"계명대동산병원 → 저희 키스해 주셔서", "양식대로 → 양복점" 같은 고유명사
붕괴가 심했던 부분이다.

## 검증

가짜 Whisper 서버를 세워 종단간 확인:
- 업로드 → recordingId → 전사 → `[00:00]/[00:03]/[00:12]` 전사문
- multipart 필드 검증: model · response_format=verbose_json · language=ko ·
  prompt(어휘 힌트) · Bearer 인증 · 파일 바이트 정확히 일치
- webm 녹음도 Whisper로 정상 전사 (5000 bytes 그대로 전달)
- Gemini+webm 거부 / 미설정 400 / 경로조작 400 / 없는 녹음 404

테스트 206 → 229 통과, 신규 타입 에러 0, 린트 baseline과 동일, 빌드 성공.

### 검증하지 못한 것

실제 Whisper·Gemini API를 호출하지 못했다(키 없음). 모든 프로바이더 코드는
목 fetch와 가짜 서버로만 검증했다. 요청 형식은 문서를 따랐으나 실제 응답에
대한 확인이 필요하다.

포착률이 실제로 얼마나 오르는지도 아직 모른다. 다음 회의에서 같은 오디오로
Web Speech와 STT를 나란히 놓고 재야 한다.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzAH7GPWSYTe2AoBV6CZDP
2026-09-09 15:19:49 +09:00
csbaeandClaude Opus 5 cf3ce3f40c feat: 회의 오디오 원본 보관 — 전사가 놓친 발화를 되살릴 수 있게
46분 대면 회의 실측에서 Web Speech 포착률이 7~10%에 그쳤다(489어절 /
분당 10.6어절, 30초 이상 공백 26곳 26분 29초). 빈 텍스트 청크 19개는
Chrome이 `isFinal: true`에 `transcript: ""`를 준 것으로, 소리는 감지했으나
인식에 실패했다는 신호다.

지금까지는 오디오를 어디에도 남기지 않아 놓친 발화를 복구할 수도, 얼마나
놓쳤는지 잴 수도 없었다. 전사와 독립적으로 원음을 파일로 남긴다.

## 유실 방지 설계

메모리에 모았다가 종료 시 한 번에 쓰지 않는다. 그러면 탭이나 서버가 죽는
순간 회의 전체가 사라진다. 15초 조각마다 디스크에 append 하므로 어느
시점에 중단되든 그때까지의 오디오는 남는다.

- 서버 업로드가 실패해도 녹음을 멈추지 않고 브라우저 사본으로 회수한다
- 조각이 3회 재시도 후에도 실패하면 뒤를 이어 붙이지 않고 멈춘다.
  중간이 빈 파일은 짧은 파일보다 나쁘다 — 재생도 전사도 안 된다
- 한 조각도 못 받았으면 "보관됨"이라고 하지 않고 오류를 띄운다
- 서버 사본이 로컬보다 짧으면 경고한다

## 캡처 제약 변경

`noiseSuppression: false, echoCancellation: false, autoGainControl: true`.
브라우저 기본값은 전화 통화용 튜닝이라 멀리 앉은 화자를 노이즈로 지운다.
AGC는 조용한 화자를 끌어올려 주므로 남긴다. 실측으로 검증할 가설이며
회귀 방지 테스트를 걸어 뒀다.

## 검증

- 서버 파이프라인: 184조각 755KB 업로드 → 다운로드 SHA256 바이트 일치
- 클라이언트 전 경로: 합성 스트림으로 48초 녹음 → 로컬·서버 크기 일치,
  서버 파일이 decodeAudioData로 48.12초 실제 오디오로 디코딩됨
- 경로 조작 400 / 없는 세션 404 / 빈 조각 400 / 미허용 mimeType 400
- 테스트 162 → 206 통과, 신규 타입 에러 0, 린트 baseline과 동일

실제 마이크 경로는 테스트하지 못했다. Web Speech와 getUserMedia가 같은
마이크를 두고 경합하는지 실사용 확인이 필요하다.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzAH7GPWSYTe2AoBV6CZDP
2026-09-09 15:04:04 +09:00
31 changed files with 3028 additions and 29 deletions

No files matched your search

+17
View File
@@ -51,3 +51,20 @@ GEMINI_API_KEY=
# LLM_BASE_URL= # LLM_BASE_URL=
# LLM_MODEL= # LLM_MODEL=
# LLM_API_KEY= # LLM_API_KEY=
# ─────────────────────────────────────────────────────────────
# 회의 오디오 녹음 저장 위치 (선택)
# ─────────────────────────────────────────────────────────────
# 기본값은 <프로젝트>/uploads/recordings 입니다.
# Docker Compose에서는 uploads 볼륨에 저장되어 컨테이너를 재시작해도 남습니다.
#
# ⚠️ 녹음 파일에는 회의 원음이 그대로 들어 있습니다. 디스크 암호화된 위치에
# 두고, 필요 없어진 녹음은 직접 삭제하세요. SECURITY.md 참고.
# RECORDINGS_DIR=
# 음성 전사(STT) 모델 (선택)
# 비우면 프로바이더 기본값: OpenAI 호환 → whisper-1, Gemini → gemini-3.6-flash
#
# ⚠️ 전사는 회의 원음을 프로바이더 서버로 보냅니다. 텍스트보다 훨씬 민감합니다.
# 외부로 내보내고 싶지 않다면 로컬 whisper 서버를 LLM_BASE_URL로 지정하세요.
# LLM_STT_MODEL=
+62 -2
View File
@@ -51,10 +51,67 @@ docker compose up -d
**특징** **특징**
- 즉시 시작 — 별도 STT 서버나 키 없이 작동 - 즉시 시작 — 별도 STT 서버나 키 없이 작동
- **오디오 원본 동시 녹음** — 전사와 무관하게 회의 원음을 파일로 보관
- **자동 재연결** — 네트워크 끊김 시 최대 8회 재시도, 누적 transcript 보존 - **자동 재연결** — 네트워크 끊김 시 최대 8회 재시도, 누적 transcript 보존
- 확정 전 텍스트는 회색 이탤릭 + 깜빡이는 커서로 시각화 - 확정 전 텍스트는 회색 이탤릭 + 깜빡이는 커서로 시각화
- 녹음 중 `🔴 N단어 · M개 구간` 실시간 카운터 - 녹음 중 `🔴 N단어 · M개 구간` 실시간 카운터
> ⚠️ **Web Speech API는 발화를 상당량 놓칩니다.** 원거리·다인 대면 회의에서
> 실측 포착률이 10% 안팎이었습니다(46분 회의 / 489어절). 회의 전사용으로
> 설계된 엔진이 아니라 근접 음성 명령용입니다. 그래서 **오디오 원본을 반드시
> 함께 남깁니다** — 놓친 발화는 나중에 서버 STT로 다시 살릴 수 있습니다.
### 🎧 오디오 원본 보관
녹음을 시작하면 전사와 **별개로** 마이크 입력을 오디오 파일로 저장합니다.
- 15초마다 조각을 서버에 이어 붙여 **탭이나 서버가 죽어도 그때까지의 오디오는 남습니다**
- 서버 저장이 실패해도 녹음은 중단되지 않고, 브라우저 사본을 **⬇️ 내려받기**로 회수할 수 있습니다
- 한 조각도 못 받았으면 "보관됨"이라고 하지 않고 오류를 띄웁니다
- 저장 위치: `uploads/recordings/` (Docker에서는 `uploads` 볼륨 → 재시작해도 유지)
**캡처 설정** — 브라우저 기본값은 전화 통화용 튜닝이라 멀리 앉은 화자를
노이즈로 지워버립니다. 그래서 노이즈 억제·에코 제거를 끄고 AGC만 남깁니다
(`src/lib/recording.ts`의 `RECORDING_AUDIO_CONSTRAINTS`).
**비트레이트** — 32kbps mono Opus. 감상용이 아니라 STT 입력이므로 인식 정확도를
해치지 않는 선에서 최대한 작게 잡았습니다. 46분 회의가 약 11MB로, 전사 API에
통째로 넣을 수 있습니다.
---
### 🔤 서버 STT 재전사 (정확도의 본선)
보관된 오디오를 Whisper / Gemini로 다시 전사합니다. **Web Speech가 놓친 발화를
되살리는 경로이며, 이 앱의 전사 정확도는 사실상 여기서 결정됩니다.**
**쓰는 법**
- 실시간 녹음 → 종료 → **🔤 원본 오디오로 다시 전사**
- 또는 파일 업로드 탭 → 파일 선택 → **🔤 전사 시작**
두 경로 모두 같은 파이프라인(`/api/transcribe`)을 씁니다.
**실제 타임스탬프** — Whisper의 `verbose_json`은 구간별 실제 오디오 시각을 줍니다.
Web Speech 경로가 쓰던 *"결과 이벤트 시각 − 2초"* 추정값과 달리, 구간 재생이나
화자 분리에 그대로 쓸 수 있는 진짜 타임라인입니다.
**참석자 · 용어 힌트** — 홈 화면의 입력란에 이름·제품명·사내 용어를 적어두면
전사 요청의 어휘 힌트로 전달되어 고유명사 오인식이 크게 줍니다.
**프로바이더별 지원**
| 프로바이더 | 브라우저 녹음(webm) | 업로드 파일 | 기본 모델 |
|---|:---:|:---:|---|
| OpenAI / OrcaRouter / 로컬 whisper | ✅ | ✅ | `whisper-1` |
| Google Gemini | ❌ | ✅ (mp3·wav·flac·m4a·ogg) | `gemini-3.6-flash` |
Gemini는 webm 오디오를 받지 않습니다. **실시간 녹음을 전사하려면 OpenAI 호환
프로바이더를 선택해야 합니다.** 설정 화면에서 이 경고를 함께 안내합니다.
> 🔴 **전사는 회의 원음을 프로바이더 서버로 보냅니다.** 텍스트보다 훨씬 민감한
> 데이터입니다. 외부 전송이 곤란하면 로컬 whisper 서버를 `base URL`로 지정하세요.
> 자세한 내용은 [SECURITY.md](SECURITY.md)를 참고하세요.
**사용** **사용**
1. 홈에서 **🎤 녹음 시작** 클릭 1. 홈에서 **🎤 녹음 시작** 클릭
2. 마이크 권한 허용 2. 마이크 권한 허용
@@ -483,8 +540,11 @@ prisma/
| 제약 | 설명 | 대응 | | 제약 | 설명 | 대응 |
|---|---|---| |---|---|---|
| **Chrome 전용** | Web Speech API는 비표준 — Safari / Firefox는 제한적 | Phase 4에서 서버 사이드 전사 검토 | | **Chrome 전용** | Web Speech API는 비표준 — Safari / Firefox는 제한적 | 서버 사이드 STT 전환 예정 |
| **화자 구분 없음** | 의도적 비지원 (Non-goal) | — | | **Web Speech 포착률 낮음** | 원거리·다인 대면 회의 실측 10% 안팎 | 종료 후 **서버 STT 재전사**로 해결 |
| **Gemini는 webm 전사 불가** | Gemini가 받는 오디오 형식에 webm이 없음 | 녹음 전사는 OpenAI 호환 프로바이더 사용 |
| **긴 회의 전사 상한** | Whisper 25MB(≈1시간 40분) / Gemini inline 14MB(≈1시간) | 초과 시 오류 안내. 분할 전사는 후속 |
| **화자 구분 없음** | 미구현 (PR #16 / #17 검토 중) | — |
| **Gemini 무료 등급 한도** | 15 RPM / 1000 RPD | 한도 초과 시 자동 쿨다운, 단순 변환 폴백 | | **Gemini 무료 등급 한도** | 15 RPM / 1000 RPD | 한도 초과 시 자동 쿨다운, 단순 변환 폴백 |
| **단일 사용자** | 인증 없음, 데이터 격리 없음 | 1인 1인스턴스로 운용 | | **단일 사용자** | 인증 없음, 데이터 격리 없음 | 1인 1인스턴스로 운용 |
| **마크다운 검색** | PostgreSQL `ILIKE` (수천 건 이상에서 느려질 수 있음) | 필요 시 `tsvector` 인덱스 추가 | | **마크다운 검색** | PostgreSQL `ILIKE` (수천 건 이상에서 느려질 수 있음) | 필요 시 `tsvector` 인덱스 추가 |
+41
View File
@@ -63,6 +63,27 @@ Chrome의 `SpeechRecognition` API는 **음성 데이터를 Google 서버로 전
이 경우 **파일 업로드 탭**도 같은 한계가 있으므로(현재 업로드 후 전사는 미구현, Phase 4에서 자체 STT 검토 예정), 이 도구의 사용을 보류하는 것을 권장합니다. 이 경우 **파일 업로드 탭**도 같은 한계가 있으므로(현재 업로드 후 전사는 미구현, Phase 4에서 자체 STT 검토 예정), 이 도구의 사용을 보류하는 것을 권장합니다.
### 🔴 주의: 서버 전사(STT)는 회의 **원음**을 외부로 보냅니다
"원본 오디오로 다시 전사" 또는 파일 업로드 전사를 실행하면, 회의 오디오 파일이
**통째로** 선택한 프로바이더 서버로 전송됩니다.
이것은 이 앱에서 가장 민감도가 높은 데이터 흐름입니다. 전사 텍스트는 Web Speech가
대부분 놓치지만, **오디오에는 회의에서 오간 모든 말과 목소리가 그대로 담겨 있습니다.**
| 프로바이더 | 오디오가 가는 곳 |
|---|---|
| Gemini | Google 서버 |
| OpenAI | OpenAI 서버 |
| OrcaRouter 등 중계 | 중계사 → 실제 모델 제공사 (2단계) |
| **로컬 whisper** | **나가지 않음** (whisper.cpp / faster-whisper 등을 `LLM_BASE_URL`로 지정) |
**외부 전송이 곤란한 회의라면 로컬 whisper 서버를 쓰세요.** 설정 → 프로바이더에서
"로컬 모델"을 고르고 base URL을 로컬 whisper 엔드포인트로 지정하면 오디오가
머신 밖으로 나가지 않습니다.
전사는 사용자가 버튼을 눌러야만 실행됩니다. 녹음만으로는 오디오가 전송되지 않습니다.
### ⚠️ 주의: AI 프로바이더 선택에 따른 전송 경로 ### ⚠️ 주의: AI 프로바이더 선택에 따른 전송 경로
`/settings`에서 고른 프로바이더에 따라 **회의 전문이 지나가는 회사가 달라집니다.** `/settings`에서 고른 프로바이더에 따라 **회의 전문이 지나가는 회사가 달라집니다.**
@@ -132,6 +153,26 @@ OpenAI 호환 프리셋의 base URL은 브라우저가 아니라 **Next.js Route
- 추가 보호가 필요하면 reverse proxy(nginx, Caddy)에 Basic Auth 추가 - 추가 보호가 필요하면 reverse proxy(nginx, Caddy)에 Basic Auth 추가
- 회사 환경에서는 SSO 통합이 필요하지만 현재 비목표 - 회사 환경에서는 SSO 통합이 필요하지만 현재 비목표
### MEDIUM — 회의 원음이 디스크에 평문으로 남습니다
**현황**: 실시간 녹음을 시작하면 회의 오디오 원본이 `uploads/recordings/`에 저장됩니다
(Docker에서는 `uploads` 볼륨). 암호화하지 않은 평문 오디오이며, 회의에서 오간
말이 그대로 들어 있습니다. **전사 텍스트보다 민감도가 높습니다** — 텍스트는
Web Speech가 대부분 놓치지만 오디오에는 전부 남습니다.
이 저장은 의도된 설계입니다. Web Speech의 포착률이 낮아(실측 10% 안팎) 원음을
남기지 않으면 놓친 발화를 복구할 방법이 없습니다.
**완화**:
- 디스크 암호화(FileVault / BitLocker)가 켜진 머신에서 운용
- 불필요해진 녹음은 `uploads/recordings/`에서 직접 삭제
- `RECORDINGS_DIR` 환경변수로 저장 위치를 별도 암호화 볼륨으로 지정 가능
- 녹음 파일 자동 만료/삭제는 **미구현** — 수동 관리가 필요합니다
**세션 ID 추측**: 녹음 조회·추가 API는 128비트 난수 ID만으로 접근을 가릅니다.
인증이 없으므로, 같은 머신에서 앱에 접근 가능한 주체는 ID를 알면 오디오를
내려받을 수 있습니다. 단일 사용자 로컬 실행 전제입니다.
### MEDIUM — 파일 업로드 매직 바이트 미검증 ### MEDIUM — 파일 업로드 매직 바이트 미검증
**현황**: `audio-validation.ts`는 `file.type`(클라이언트 제공)과 파일명 확장자만 검사. 매직 바이트 검증 없음. **현황**: `audio-validation.ts`는 `file.type`(클라이언트 제공)과 파일명 확장자만 검사. 매직 바이트 검증 없음.
+64 -1
View File
@@ -155,6 +155,70 @@
--- ---
## 🔴 실사용 진단 (2026-09-08 대면 회의)
46분 대면 회의를 실제로 녹음해 본 결과다. 로드맵의 우선순위를 바꾼 근거.
| 지표 | 값 |
|---|---|
| 회의 길이 | 46분 6초 |
| 총 청크 | 122개 |
| 총 어절 | **489** |
| 분당 어절 | **10.6** (한국어 대화 통상 100~150) |
| 추정 포착률 | **7~10%** |
| 30초 이상 공백 | 26곳 / 합계 26분 29초 (회의의 57%) |
| 빈 텍스트 청크 | 19개 (16%) |
**빈 청크 19개가 결정적 증거다.** Chrome이 `isFinal: true`에 `transcript: ""`를
준 경우로, "소리는 감지했으나 인식 실패"를 뜻한다. 마이크 입력 문제가 아니라
Web Speech가 원거리·다인 한국어를 못 알아듣고 버린 것이다.
**결론: Web Speech API는 회의 전사에 쓸 수 없다.** 재시작 갭을 메우고 interim을
flush해서 7%를 20~30%로는 올려도 90%로는 못 간다. 구현 결함이 아니라 엔진의 한계다.
---
## 🎯 P0 — 유실을 멈춘다
- [x] **오디오 원본 녹음** — `MediaRecorder`로 회의 원음을 파일로 보관
- [x] 15초 조각 단위로 서버에 append → 탭/서버가 죽어도 그때까지는 남음
- [x] 서버 실패해도 녹음 계속 + 브라우저 사본 내려받기
- [x] 0바이트일 때 "보관됨"이라고 하지 않음
- [x] 캡처 제약에서 노이즈 억제·에코 제거 해제 (원거리 화자 보존)
- [x] 회의록 저장 시 `audioFileName`/`audioMimeType`/`audioDuration` 연결
- [x] **서버 STT 파이프라인** — 녹음 파일 → Whisper / Gemini audio → transcript
- [x] `/api/upload`를 막다른 길에서 본선 경로로 승격 (업로드 → recordingId → 전사)
- [x] 프로바이더 레이어에 `/v1/audio/transcriptions` 추가 (#12 구조 확장)
- [x] Gemini 오디오 inline 입력 (webm 미지원은 명시적으로 안내)
- [x] `verbose_json`으로 실제 오디오 타임스탬프 확보
- [x] 참석자·용어 힌트를 전사 프롬프트로 전달
- [x] 녹음 비트레이트 32kbps로 하향 — 46분 회의가 11MB로 API 상한 안에 들어옴
- [ ] 같은 오디오로 Web Speech vs STT 포착률 실측 비교 ← **다음 회의에서**
- [ ] 상한 초과 회의 분할 전사 (Whisper 25MB / Gemini inline 14MB)
- [ ] Gemini Files API 경로 (큰 파일 + webm 우회)
- [ ] Web Speech를 "실시간 미리보기"로 명시적 강등 (현재는 둘 다 노출)
- [ ] **빈 청크 필터링** — 빈 발화 19개가 요약 프롬프트를 오염시키고 있음
- [ ] **타임스탬프 실측화** — `useSpeechRecognition.ts`의 `startTime: now - 2` 하드코딩 제거
- [ ] **10만 자 하드 실패 → 분할 요약** — 긴 회의가 마지막에 통째로 실패함
## 🎯 P1 — 입력단 개선
- [ ] 대면 회의용 USB 전방향 마이크 도입 (코드로 못 푸는 물리적 한계)
- [ ] 원격 회의용 `echoCancellation` 재활성 경로 분리
## 🎯 P2 — 화자 분리 재설계
- [ ] **PR #17은 현재 형태로 머지 보류** — 실사용에서 46분 회의를 화자 1명으로
판정했고, 5개 청크는 배정조차 실패했다. `assignSpeakers()`가 쓰는 시간축이
가짜(`now - 2`)라 diarization의 실제 타임라인과 맞지 않는다
- [ ] 서버 STT 도입 후 재설계 — Whisper의 단어 단위 실제 타임스탬프 위에서
diarization을 돌리면 그때 비로소 겹침 기반 배정이 의미를 갖는다
- [ ] #17의 sherpa-onnx 래퍼·모델 셋업 스크립트는 그때 재활용
- [ ] 참석자 수 힌트는 유지 (#17 실측에서 효과 확인됨)
- [ ] PR #16(dual-stream)은 원격 회의 전용으로 분리 검증
---
## 🎯 Phase 3 — 참석자 + 태그 (3~5일) ## 🎯 Phase 3 — 참석자 + 태그 (3~5일)
### Issues ### Issues
@@ -199,7 +263,6 @@
다음 기능은 개인 사용 목적에 부합하지 않아 **의도적으로 범위 밖**: 다음 기능은 개인 사용 목적에 부합하지 않아 **의도적으로 범위 밖**:
- **화자 구분 (Speaker Diarization)** — 유료 API 비용/복잡도 대비 개인용에 과함
- **실시간 공동 편집 (CRDT)** — Yjs/Liveblocks 도입 복잡도 대비 이득 없음 - **실시간 공동 편집 (CRDT)** — Yjs/Liveblocks 도입 복잡도 대비 이득 없음
- **권한 관리 / 워크스페이스** — 단일 사용자 가정 - **권한 관리 / 워크스페이스** — 단일 사용자 가정
- **모바일 네이티브 앱** — 웹 PWA로 충분 - **모바일 네이티브 앱** — 웹 PWA로 충분
+5
View File
@@ -71,6 +71,8 @@ describe('프로바이더 설정 저장', () => {
apiKey: 'sk-test', apiKey: 'sk-test',
baseUrl: 'https://api.orcarouter.ai/v1', baseUrl: 'https://api.orcarouter.ai/v1',
model: 'google/gemini-2.5-flash-lite', model: 'google/gemini-2.5-flash-lite',
// 예전에 저장된 설정에는 sttModel이 없다. 빈 값으로 채워 마이그레이션 없이 읽힌다.
sttModel: '',
}) })
}) })
@@ -105,6 +107,7 @@ describe('getProviderRequestPayload', () => {
apiKey: 'AIza-legacy', apiKey: 'AIza-legacy',
baseUrl: '', baseUrl: '',
model: '', model: '',
sttModel: '',
}) })
}) })
@@ -114,6 +117,7 @@ describe('getProviderRequestPayload', () => {
apiKey: '', apiKey: '',
baseUrl: '', baseUrl: '',
model: '', model: '',
sttModel: '',
}) })
}) })
@@ -130,6 +134,7 @@ describe('getProviderRequestPayload', () => {
apiKey: '', apiKey: '',
baseUrl: 'http://localhost:11434/v1', baseUrl: 'http://localhost:11434/v1',
model: 'llama3.1', model: 'llama3.1',
sttModel: '',
}) })
}) })
+164
View File
@@ -0,0 +1,164 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { mkdtemp, rm, readFile } from 'fs/promises'
import { tmpdir } from 'os'
import path from 'path'
type Store = typeof import('@/lib/recording-store')
let dir: string
let store: Store
beforeEach(async () => {
dir = await mkdtemp(path.join(tmpdir(), 'recordings-'))
process.env.RECORDINGS_DIR = dir
vi.resetModules()
store = await import('@/lib/recording-store')
})
afterEach(async () => {
delete process.env.RECORDINGS_DIR
await rm(dir, { recursive: true, force: true })
})
describe('createRecording', () => {
it('세션 메타를 만들고 확장자를 붙인다', async () => {
const meta = await store.createRecording('audio/webm;codecs=opus')
expect(meta.id).toMatch(/^[0-9a-f]{32}$/)
expect(meta.fileName).toBe(`${meta.id}.webm`)
expect(meta.finalizedAt).toBeNull()
expect(meta.durationMs).toBeNull()
})
it('매번 다른 id를 준다', async () => {
const a = await store.createRecording('audio/webm')
const b = await store.createRecording('audio/webm')
expect(a.id).not.toBe(b.id)
})
})
describe('appendChunk', () => {
it('조각을 받은 순서대로 이어 붙인다', async () => {
const { id } = await store.createRecording('audio/webm')
await store.appendChunk(id, Buffer.from('AAA'))
await store.appendChunk(id, Buffer.from('BBB'))
const last = await store.appendChunk(id, Buffer.from('CC'))
expect(last).toEqual({ ok: true, bytes: 8 })
const meta = await store.getRecording(id)
const written = await readFile(path.join(dir, meta!.fileName), 'utf-8')
expect(written).toBe('AAABBBCC')
})
it('동시에 들어와도 순서가 섞이지 않는다', async () => {
const { id } = await store.createRecording('audio/webm')
// 클라이언트가 직렬로 보내도 서버에서 겹칠 수 있다. 겹쳐도 파일이
// 깨지지 않아야 한다 — 순서가 어긋나면 컨테이너를 못 읽는다.
await Promise.all([
store.appendChunk(id, Buffer.from('1')),
store.appendChunk(id, Buffer.from('2')),
store.appendChunk(id, Buffer.from('3')),
store.appendChunk(id, Buffer.from('4')),
])
const meta = await store.getRecording(id)
const written = await readFile(path.join(dir, meta!.fileName), 'utf-8')
expect(written).toHaveLength(4)
expect(written.split('').sort().join('')).toBe('1234')
})
it('없는 세션은 404로 거절한다', async () => {
const result = await store.appendChunk('f'.repeat(32), Buffer.from('x'))
expect(result).toEqual({
ok: false,
error: '녹음 세션을 찾을 수 없습니다.',
status: 404,
})
})
it('누적 크기를 정확히 보고한다', async () => {
const { id } = await store.createRecording('audio/webm')
await store.appendChunk(id, Buffer.from('keep'))
const result = await store.appendChunk(id, Buffer.alloc(1024))
expect(result).toEqual({ ok: true, bytes: 4 + 1024 })
})
})
describe('finalizeRecording', () => {
it('길이를 확정하고 최종 크기를 돌려준다', async () => {
const { id } = await store.createRecording('audio/webm')
await store.appendChunk(id, Buffer.from('0123456789'))
const status = await store.finalizeRecording(id, 46_000)
expect(status?.bytes).toBe(10)
expect(status?.durationMs).toBe(46_000)
expect(status?.finalizedAt).not.toBeNull()
})
it('확정 정보가 디스크에도 남는다', async () => {
const { id } = await store.createRecording('audio/webm')
await store.finalizeRecording(id, 1_234)
const reloaded = await store.getRecording(id)
expect(reloaded?.durationMs).toBe(1_234)
})
it('길이가 숫자가 아니면 null로 둔다', async () => {
const { id } = await store.createRecording('audio/webm')
const status = await store.finalizeRecording(id, null)
expect(status?.durationMs).toBeNull()
})
it('없는 세션은 null', async () => {
expect(await store.finalizeRecording('e'.repeat(32), 1)).toBeNull()
})
})
describe('getRecording', () => {
it('잘못된 id는 파일을 찾아보지도 않는다', async () => {
expect(await store.getRecording('../../etc/passwd')).toBeNull()
expect(await store.getRecording('..')).toBeNull()
})
})
describe('openRecording', () => {
it('조각이 하나도 없으면 null', async () => {
const { id } = await store.createRecording('audio/webm')
expect(await store.openRecording(id)).toBeNull()
})
it('저장된 바이트를 그대로 읽어준다', async () => {
const { id } = await store.createRecording('audio/webm')
await store.appendChunk(id, Buffer.from('hello'))
const opened = await store.openRecording(id)
expect(opened?.bytes).toBe(5)
expect(opened?.meta.mimeType).toBe('audio/webm')
const chunks: Buffer[] = []
for await (const chunk of opened!.stream) {
chunks.push(Buffer.from(chunk as Buffer))
}
expect(Buffer.concat(chunks).toString()).toBe('hello')
})
})
describe('크래시 내성', () => {
it('종료 처리 없이 중단돼도 그때까지의 오디오는 남는다', async () => {
const { id } = await store.createRecording('audio/webm')
await store.appendChunk(id, Buffer.from('part1'))
await store.appendChunk(id, Buffer.from('part2'))
// finalize 없이 프로세스가 죽었다고 치고 모듈을 새로 읽는다.
vi.resetModules()
const reloaded: Store = await import('@/lib/recording-store')
const status = await reloaded.getRecordingStatus(id)
expect(status?.bytes).toBe(10)
expect(status?.finalizedAt).toBeNull()
})
})
+149
View File
@@ -0,0 +1,149 @@
import { describe, it, expect } from 'vitest'
import {
PREFERRED_MIME_TYPES,
RECORDING_AUDIO_CONSTRAINTS,
extensionForMimeType,
formatBytes,
formatDuration,
isValidRecordingId,
pickRecorderMimeType,
recordingDownloadName,
} from '@/lib/recording'
describe('pickRecorderMimeType', () => {
it('가장 앞선 후보를 고른다', () => {
const picked = pickRecorderMimeType(() => true)
expect(picked).toBe(PREFERRED_MIME_TYPES[0])
})
it('지원하지 않는 후보는 건너뛴다', () => {
const picked = pickRecorderMimeType((type) => type === 'audio/mp4')
expect(picked).toBe('audio/mp4')
})
it('아무것도 지원하지 않으면 null', () => {
expect(pickRecorderMimeType(() => false)).toBeNull()
})
})
describe('extensionForMimeType', () => {
it('코덱 파라미터를 떼고 판단한다', () => {
expect(extensionForMimeType('audio/webm;codecs=opus')).toBe('webm')
expect(extensionForMimeType('audio/ogg; codecs=opus')).toBe('ogg')
})
it('주요 컨테이너를 매핑한다', () => {
expect(extensionForMimeType('audio/webm')).toBe('webm')
expect(extensionForMimeType('audio/mp4')).toBe('m4a')
expect(extensionForMimeType('audio/mpeg')).toBe('mp3')
expect(extensionForMimeType('audio/wav')).toBe('wav')
})
it('대소문자를 가리지 않는다', () => {
expect(extensionForMimeType('AUDIO/WEBM')).toBe('webm')
})
it('모르는 형식은 bin으로 떨어진다', () => {
expect(extensionForMimeType('application/octet-stream')).toBe('bin')
})
})
describe('isValidRecordingId', () => {
const valid = 'a'.repeat(32)
it('32자 hex만 통과시킨다', () => {
expect(isValidRecordingId(valid)).toBe(true)
expect(isValidRecordingId('0123456789abcdef0123456789abcdef')).toBe(true)
})
it('경로 조작 시도를 막는다', () => {
expect(isValidRecordingId('../../etc/passwd')).toBe(false)
expect(isValidRecordingId(`${valid}/../x`)).toBe(false)
expect(isValidRecordingId('..')).toBe(false)
expect(isValidRecordingId(`../${valid}`)).toBe(false)
})
it('길이나 문자셋이 어긋나면 거부한다', () => {
expect(isValidRecordingId('a'.repeat(31))).toBe(false)
expect(isValidRecordingId('a'.repeat(33))).toBe(false)
expect(isValidRecordingId('A'.repeat(32))).toBe(false)
expect(isValidRecordingId('g'.repeat(32))).toBe(false)
expect(isValidRecordingId('')).toBe(false)
})
it('문자열이 아니면 거부한다', () => {
expect(isValidRecordingId(null)).toBe(false)
expect(isValidRecordingId(undefined)).toBe(false)
expect(isValidRecordingId(123)).toBe(false)
})
})
describe('recordingDownloadName', () => {
const at = new Date(2026, 8, 8, 14, 5)
it('날짜와 제목을 붙인다', () => {
expect(recordingDownloadName('주간 회의', at, 'audio/webm')).toBe(
'20260908-1405_주간_회의.webm',
)
})
it('제목이 없으면 날짜만 쓴다', () => {
expect(recordingDownloadName(' ', at, 'audio/webm')).toBe(
'20260908-1405.webm',
)
})
it('파일명에 못 쓰는 문자를 지운다', () => {
const name = recordingDownloadName('a/b\\c:d*e?f"g<h>i|j', at, 'audio/webm')
expect(name).toBe('20260908-1405_abcdefghij.webm')
expect(name).not.toMatch(/[\\/:*?"<>|]/)
})
it('아주 긴 제목을 자른다', () => {
const name = recordingDownloadName('가'.repeat(200), at, 'audio/webm')
expect(name.length).toBeLessThan(90)
})
})
describe('formatBytes', () => {
it('단위를 바꿔가며 표기한다', () => {
expect(formatBytes(512)).toBe('512B')
expect(formatBytes(2048)).toBe('2KB')
expect(formatBytes(5 * 1024 * 1024)).toBe('5.0MB')
})
it('비정상 값은 0으로 떨어진다', () => {
expect(formatBytes(-1)).toBe('0B')
expect(formatBytes(NaN)).toBe('0B')
})
})
describe('formatDuration', () => {
it('한 시간 미만은 분:초', () => {
expect(formatDuration(0)).toBe('00:00')
expect(formatDuration(65_000)).toBe('01:05')
expect(formatDuration(46 * 60_000 + 6_000)).toBe('46:06')
})
it('한 시간 이상은 시:분:초', () => {
expect(formatDuration(3_600_000)).toBe('1:00:00')
expect(formatDuration(3_725_000)).toBe('1:02:05')
})
it('음수는 0으로 본다', () => {
expect(formatDuration(-5_000)).toBe('00:00')
})
})
describe('RECORDING_AUDIO_CONSTRAINTS', () => {
it('원거리 화자를 지우는 전처리를 끈다', () => {
// 46분 대면 회의에서 포착률이 10% 안팎에 그친 원인 중 하나.
// 이 값이 다시 true로 돌아가면 회귀다.
expect(RECORDING_AUDIO_CONSTRAINTS.noiseSuppression).toBe(false)
expect(RECORDING_AUDIO_CONSTRAINTS.echoCancellation).toBe(false)
})
it('조용한 화자를 끌어올리는 AGC는 남긴다', () => {
expect(RECORDING_AUDIO_CONSTRAINTS.autoGainControl).toBe(true)
})
})
+335
View File
@@ -0,0 +1,335 @@
import { describe, it, expect, vi } from 'vitest'
import {
isGeminiSupportedAudioMimeType,
isWhisperSupportedMimeType,
parseTimestampedTranscript,
resolveSttModel,
transcribe,
GEMINI_INLINE_AUDIO_LIMIT,
DEFAULT_OPENAI_STT_MODEL,
DEFAULT_GEMINI_STT_MODEL,
} from '@/lib/providers'
import { resolveTranscriptionSettings } from '@/lib/api-keys'
import {
formatTranscriptionSegments,
segmentsToChunks,
} from '@/lib/transcript-formatter'
import type { TranscriptionInput } from '@/lib/providers/types'
function audio(overrides: Partial<TranscriptionInput> = {}): TranscriptionInput {
return {
bytes: new Uint8Array([1, 2, 3, 4]),
mimeType: 'audio/webm;codecs=opus',
fileName: 'meeting.webm',
language: 'ko',
...overrides,
}
}
function okResponse(body: unknown) {
return { ok: true, status: 200, json: async () => body } as unknown as Response
}
/** 목의 호출 인자를 좁혀서 읽는다. vi.fn의 추론 타입은 fetch 오버로드와 안 맞는다. */
function callArgs(
mock: { mock: { calls: unknown[][] } },
index = 0,
): { url: string; init: RequestInit } {
const [url, init] = mock.mock.calls[index] as [string, RequestInit]
return { url, init }
}
function errResponse(status: number) {
return {
ok: false,
status,
json: async () => ({ error: 'nope' }),
} as unknown as Response
}
describe('mime 지원 판정', () => {
it('Whisper는 브라우저 녹음(webm)을 받는다', () => {
expect(isWhisperSupportedMimeType('audio/webm;codecs=opus')).toBe(true)
expect(isWhisperSupportedMimeType('audio/mpeg')).toBe(true)
expect(isWhisperSupportedMimeType('audio/x-aiff')).toBe(false)
})
it('Gemini는 webm을 받지 않는다', () => {
// 이게 true로 바뀌면 UI의 안내 문구도 같이 고쳐야 한다.
expect(isGeminiSupportedAudioMimeType('audio/webm')).toBe(false)
expect(isGeminiSupportedAudioMimeType('audio/mpeg')).toBe(true)
expect(isGeminiSupportedAudioMimeType('audio/flac')).toBe(true)
})
})
describe('transcribe — OpenAI 호환', () => {
const settings = {
provider: 'openai-compatible' as const,
apiKey: 'sk-test',
baseUrl: 'https://api.example.com/v1',
}
it('multipart로 보내고 verbose_json 구간을 파싱한다', async () => {
const fetchFn = vi.fn(async () =>
okResponse({
text: '안녕하세요 회의 시작합니다',
segments: [
{ start: 0, end: 2.5, text: ' 안녕하세요' },
{ start: 2.5, end: 5, text: ' 회의 시작합니다' },
],
}),
)
const result = await transcribe(audio(), settings, { fetchFn })
expect(result.success).toBe(true)
if (!result.success) return
expect(result.text).toBe('안녕하세요 회의 시작합니다')
expect(result.segments).toEqual([
{ start: 0, end: 2.5, text: '안녕하세요' },
{ start: 2.5, end: 5, text: '회의 시작합니다' },
])
expect(result.model).toBe(DEFAULT_OPENAI_STT_MODEL)
const { url, init } = callArgs(fetchFn)
expect(url).toBe('https://api.example.com/v1/audio/transcriptions')
expect(init.body).toBeInstanceOf(FormData)
const form = init.body as FormData
expect(form.get('model')).toBe(DEFAULT_OPENAI_STT_MODEL)
expect(form.get('response_format')).toBe('verbose_json')
expect(form.get('language')).toBe('ko')
})
it('어휘 힌트를 prompt로 보낸다', async () => {
const fetchFn = vi.fn(async () =>
okResponse({ text: '내용' }),
)
await transcribe(audio({ vocabularyHint: '김효천, PACS' }), settings, {
fetchFn,
})
const form = callArgs(fetchFn).init.body as FormData
expect(form.get('prompt')).toBe('김효천, PACS')
})
it('verbose_json 미지원(400)이면 json으로 한 번 더 시도한다', async () => {
const fetchFn = vi
.fn()
.mockResolvedValueOnce(errResponse(400))
.mockResolvedValueOnce(okResponse({ text: '타임스탬프 없는 결과' }))
const result = await transcribe(audio(), settings, { fetchFn })
expect(fetchFn).toHaveBeenCalledTimes(2)
expect(result.success).toBe(true)
if (!result.success) return
expect(result.segments).toEqual([])
const second = callArgs(fetchFn, 1).init.body as FormData
expect(second.get('response_format')).toBe('json')
})
it('429는 rateLimited로 표시한다', async () => {
const fetchFn = vi.fn(async () => errResponse(429))
const result = await transcribe(audio(), settings, { fetchFn })
expect(result.success).toBe(false)
if (result.success) return
expect(result.rateLimited).toBe(true)
})
it('빈 전사 결과를 성공으로 넘기지 않는다', async () => {
const fetchFn = vi.fn(async () => okResponse({ text: ' ' }))
const result = await transcribe(audio(), settings, { fetchFn })
expect(result.success).toBe(false)
if (result.success) return
expect(result.error).toContain('비어 있습니다')
})
it('base URL이 잘못되면 호출조차 하지 않는다', async () => {
const fetchFn = vi.fn()
const result = await transcribe(
audio(),
{ ...settings, baseUrl: 'file:///etc/passwd' },
{ fetchFn },
)
expect(fetchFn).not.toHaveBeenCalled()
expect(result.success).toBe(false)
})
it('망가진 구간은 버리고 정상 구간만 남긴다', async () => {
const fetchFn = vi.fn(async () =>
okResponse({
text: 'ok',
segments: [
{ start: 0, end: 1, text: '정상' },
{ start: 'x', end: 2, text: '시작이 숫자가 아님' },
{ start: 3, end: 4, text: ' ' },
{ start: 5, end: 6, text: '또 정상' },
],
}),
)
const result = await transcribe(audio(), settings, { fetchFn })
expect(result.success).toBe(true)
if (!result.success) return
expect(result.segments.map((s) => s.text)).toEqual(['정상', '또 정상'])
})
})
describe('transcribe — Gemini', () => {
const settings = { provider: 'gemini' as const, apiKey: 'AIza-test' }
it('webm은 거부하고 대안을 안내한다', async () => {
const fetchFn = vi.fn()
const result = await transcribe(audio(), settings, { fetchFn })
expect(fetchFn).not.toHaveBeenCalled()
expect(result.success).toBe(false)
if (result.success) return
expect(result.error).toContain('OpenAI 호환')
})
it('지원 형식은 inline_data로 보낸다', async () => {
const fetchFn = vi.fn(async () =>
okResponse({
candidates: [{ content: { parts: [{ text: '[00:03] 안녕하세요' }] } }],
}),
)
const result = await transcribe(
audio({ mimeType: 'audio/mpeg', fileName: 'a.mp3' }),
settings,
{ fetchFn },
)
expect(result.success).toBe(true)
if (!result.success) return
expect(result.segments).toEqual([{ start: 3, end: 4, text: '안녕하세요' }])
const body = JSON.parse(callArgs(fetchFn).init.body as string)
expect(body.contents[0].parts[1].inline_data.mime_type).toBe('audio/mpeg')
expect(body.contents[0].parts[1].inline_data.data).toBe(
Buffer.from([1, 2, 3, 4]).toString('base64'),
)
})
it('inline 상한을 넘으면 호출하지 않고 대안을 안내한다', async () => {
const fetchFn = vi.fn()
const result = await transcribe(
audio({
mimeType: 'audio/mpeg',
bytes: new Uint8Array(GEMINI_INLINE_AUDIO_LIMIT + 1),
}),
settings,
{ fetchFn },
)
expect(fetchFn).not.toHaveBeenCalled()
expect(result.success).toBe(false)
if (result.success) return
expect(result.error).toContain('너무 큽니다')
})
it('키가 없으면 거부한다', async () => {
const fetchFn = vi.fn()
const result = await transcribe(
audio({ mimeType: 'audio/mpeg' }),
{ provider: 'gemini', apiKey: ' ' },
{ fetchFn },
)
expect(fetchFn).not.toHaveBeenCalled()
expect(result.success).toBe(false)
})
})
describe('parseTimestampedTranscript', () => {
it('MM:SS와 HH:MM:SS를 모두 읽는다', () => {
const segments = parseTimestampedTranscript(
['[00:03] 첫 발화', '[01:10] 두 번째', '[1:02:05] 한참 뒤'].join('\n'),
)
expect(segments.map((s) => s.start)).toEqual([3, 70, 3725])
})
it('다음 구간 시작을 이전 구간의 끝으로 잡는다', () => {
const segments = parseTimestampedTranscript('[00:00] 가\n[00:10] 나')
expect(segments[0]).toEqual({ start: 0, end: 10, text: '가' })
expect(segments[1].end).toBeGreaterThan(segments[1].start)
})
it('타임스탬프 없는 줄은 무시한다', () => {
expect(parseTimestampedTranscript('그냥 텍스트\n또 텍스트')).toEqual([])
})
})
describe('formatTranscriptionSegments', () => {
it('실제 오디오 타임라인으로 전사문을 만든다', () => {
const text = formatTranscriptionSegments([
{ start: 3, text: '어떤 거죠' },
{ start: 3725, text: '한참 뒤' },
])
expect(text).toBe('[00:03] 어떤 거죠\n[01:02:05] 한참 뒤')
})
it('빈 구간은 넣지 않는다', () => {
// Web Speech 경로에서 빈 청크 19개가 요약 프롬프트를 오염시켰다.
expect(
formatTranscriptionSegments([
{ start: 0, text: ' ' },
{ start: 1, text: '내용' },
]),
).toBe('[00:01] 내용')
})
})
describe('segmentsToChunks', () => {
it('청크 구조로 옮기면서 시간을 보존한다', () => {
expect(
segmentsToChunks([{ start: 1.5, end: 4.25, text: ' 발화 ' }]),
).toEqual([{ text: '발화', startTime: 1.5, endTime: 4.25, isFinal: true }])
})
})
describe('resolveTranscriptionSettings', () => {
it('대화 모델이 없어도 전사는 가능하다', () => {
// 요약용 resolveProviderSettings는 model이 비면 null을 준다.
const settings = resolveTranscriptionSettings({
provider: 'openai-compatible',
baseUrl: 'https://api.example.com/v1',
apiKey: 'sk-x',
})
expect(settings).not.toBeNull()
expect(resolveSttModel(settings!)).toBe(DEFAULT_OPENAI_STT_MODEL)
})
it('sttModel을 지정하면 그것을 쓴다', () => {
const settings = resolveTranscriptionSettings({
provider: 'openai-compatible',
baseUrl: 'https://api.example.com/v1',
sttModel: 'gpt-4o-transcribe',
})
expect(resolveSttModel(settings!)).toBe('gpt-4o-transcribe')
})
it('gemini 기본 STT 모델은 오디오를 받는 모델이다', () => {
const settings = resolveTranscriptionSettings({
provider: 'gemini',
apiKey: 'AIza-x',
})
expect(resolveSttModel(settings!)).toBe(DEFAULT_GEMINI_STT_MODEL)
})
it('base URL이 없으면 null', () => {
expect(
resolveTranscriptionSettings({ provider: 'openai-compatible' }),
).toBeNull()
})
})
+239
View File
@@ -0,0 +1,239 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { act, renderHook, waitFor } from '@testing-library/react'
import { useAudioRecorder } from '@/hooks/useAudioRecorder'
/**
* jsdom에는 MediaRecorder도 getUserMedia도 없다. 훅이 다루는 것은
* "조각이 언제 오고 어디로 가는가"이므로 그 둘만 흉내 내면 충분하다.
*/
class FakeMediaRecorder {
static isTypeSupported = () => true
state: 'inactive' | 'recording' = 'inactive'
ondataavailable: ((event: { data: Blob }) => void) | null = null
onerror: (() => void) | null = null
private listeners: Record<string, Array<() => void>> = {}
constructor(
public stream: MediaStream,
public options?: MediaRecorderOptions,
) {
instances.push(this)
}
start() {
this.state = 'recording'
}
stop() {
this.state = 'inactive'
// 실제 MediaRecorder는 stop() 시 남은 버퍼를 한 번 더 내보낸 뒤 stop을 쏜다.
for (const fn of this.listeners.stop ?? []) fn()
}
addEventListener(type: string, fn: () => void) {
;(this.listeners[type] ??= []).push(fn)
}
emit(bytes: number) {
this.ondataavailable?.({ data: new Blob([new Uint8Array(bytes)]) })
}
}
let instances: FakeMediaRecorder[] = []
let stopTracks: ReturnType<typeof vi.fn>
let fetchMock: ReturnType<typeof vi.fn>
function jsonResponse(body: unknown, ok = true, status = 200) {
return { ok, status, json: async () => body }
}
beforeEach(() => {
instances = []
stopTracks = vi.fn()
vi.stubGlobal('MediaRecorder', FakeMediaRecorder)
vi.stubGlobal('navigator', {
mediaDevices: {
getUserMedia: vi.fn(async () => ({
getTracks: () => [{ stop: stopTracks }],
})),
},
})
fetchMock = vi.fn(async (url: string) => {
if (url === '/api/recordings') {
return jsonResponse({ id: 'a'.repeat(32), mimeType: 'audio/webm' }, true, 201)
}
if (url.endsWith('/chunk')) return jsonResponse({ bytes: 1024 })
return jsonResponse({ bytes: 1024 })
})
vi.stubGlobal('fetch', fetchMock)
})
afterEach(() => {
vi.unstubAllGlobals()
})
async function startedHook() {
const view = renderHook(() => useAudioRecorder())
await waitFor(() => expect(view.result.current.isSupported).toBe(true))
await act(async () => {
await view.result.current.startRecording()
})
return view
}
describe('useAudioRecorder — 캡처 제약', () => {
it('원거리 화자를 지우는 전처리를 끄고 마이크를 연다', async () => {
await startedHook()
expect(navigator.mediaDevices.getUserMedia).toHaveBeenCalledWith({
audio: expect.objectContaining({
noiseSuppression: false,
echoCancellation: false,
autoGainControl: true,
}),
})
})
})
describe('useAudioRecorder — 조각 업로드', () => {
it('조각이 생길 때마다 서버로 올린다', async () => {
const view = await startedHook()
await act(async () => {
instances[0].emit(2048)
})
await waitFor(() => {
const chunkCalls = fetchMock.mock.calls.filter((c) =>
String(c[0]).endsWith('/chunk'),
)
expect(chunkCalls).toHaveLength(1)
})
expect(view.result.current.localBytes).toBe(2048)
})
it('빈 조각은 올리지 않는다', async () => {
await startedHook()
await act(async () => {
instances[0].emit(0)
})
const chunkCalls = fetchMock.mock.calls.filter((c) =>
String(c[0]).endsWith('/chunk'),
)
expect(chunkCalls).toHaveLength(0)
})
it('업로드가 끝내 실패하면 뒤 조각을 이어 붙이지 않고 경고한다', async () => {
// 중간이 빈 파일은 짧은 파일보다 나쁘다 — 재생도 전사도 안 된다.
fetchMock.mockImplementation(async (url: string) => {
if (url === '/api/recordings') {
return jsonResponse({ id: 'a'.repeat(32) }, true, 201)
}
if (url.endsWith('/chunk')) return jsonResponse({ error: 'nope' }, false, 500)
return jsonResponse({})
})
const view = await startedHook()
await act(async () => {
instances[0].emit(1024)
})
// 500은 일시 장애일 수 있으므로 백오프를 두고 3회까지 재시도한다.
await waitFor(
() => {
expect(view.result.current.uploadWarning).toContain('서버 저장이 중단')
},
{ timeout: 5_000 },
)
const callsAfterBreak = fetchMock.mock.calls.filter((c) =>
String(c[0]).endsWith('/chunk'),
).length
await act(async () => {
instances[0].emit(1024)
})
expect(
fetchMock.mock.calls.filter((c) => String(c[0]).endsWith('/chunk')).length,
).toBe(callsAfterBreak)
})
it('세션 생성이 실패해도 녹음은 계속된다', async () => {
fetchMock.mockImplementation(async (url: string) => {
if (url === '/api/recordings') {
return jsonResponse({ error: 'down' }, false, 500)
}
return jsonResponse({})
})
const view = await startedHook()
expect(view.result.current.isRecording).toBe(true)
expect(view.result.current.uploadWarning).toContain('내려받아')
await act(async () => {
instances[0].emit(4096)
})
expect(view.result.current.localBytes).toBe(4096)
})
})
describe('useAudioRecorder — 종료', () => {
it('오디오를 한 조각도 못 받았으면 보관됐다고 말하지 않는다', async () => {
const view = await startedHook()
await act(async () => {
await view.result.current.stopRecording()
})
expect(view.result.current.recording).toBeNull()
expect(view.result.current.error).toContain('한 조각도 캡처되지 않았습니다')
expect(view.result.current.isRecording).toBe(false)
})
it('받은 조각이 있으면 결과를 넘기고 마이크를 놓는다', async () => {
const view = await startedHook()
await act(async () => {
instances[0].emit(1024)
})
await act(async () => {
await view.result.current.stopRecording()
})
expect(view.result.current.recording?.blob.size).toBe(1024)
expect(view.result.current.recording?.recordingId).toBe('a'.repeat(32))
expect(stopTracks).toHaveBeenCalled()
expect(view.result.current.isRecording).toBe(false)
})
it('서버 사본이 로컬보다 짧으면 경고한다', async () => {
fetchMock.mockImplementation(async (url: string) => {
if (url === '/api/recordings') {
return jsonResponse({ id: 'a'.repeat(32) }, true, 201)
}
if (url.endsWith('/chunk')) return jsonResponse({ bytes: 10 })
return jsonResponse({ bytes: 10 })
})
const view = await startedHook()
await act(async () => {
instances[0].emit(4096)
})
await act(async () => {
await view.result.current.stopRecording()
})
expect(view.result.current.uploadWarning).toContain('서버 사본이 로컬보다 짧습니다')
})
})
+11
View File
@@ -79,6 +79,9 @@ export async function POST(request: NextRequest) {
customPrompt, customPrompt,
attendees, attendees,
tags, tags,
audioFileName,
audioMimeType,
audioDuration,
} = body } = body
if (!title || typeof title !== 'string' || title.trim().length === 0) { if (!title || typeof title !== 'string' || title.trim().length === 0) {
@@ -112,6 +115,14 @@ export async function POST(request: NextRequest) {
tags: Array.isArray(tags) tags: Array.isArray(tags)
? tags.filter((t) => typeof t === 'string') ? tags.filter((t) => typeof t === 'string')
: [], : [],
audioFileName:
typeof audioFileName === 'string' ? audioFileName : null,
audioMimeType:
typeof audioMimeType === 'string' ? audioMimeType : null,
audioDuration:
typeof audioDuration === 'number' && Number.isFinite(audioDuration)
? Math.max(0, Math.round(audioDuration))
: null,
status: 'COMPLETED', status: 'COMPLETED',
actionItems: { actionItems: {
create: parsed.map((item, index) => ({ create: parsed.map((item, index) => ({
@@ -0,0 +1,55 @@
import { NextRequest } from 'next/server'
import { appendChunk } from '@/lib/recording-store'
import { MAX_CHUNK_BYTES, isValidRecordingId } from '@/lib/recording'
export const dynamic = 'force-dynamic'
interface RouteContext {
params: Promise<{ id: string }>
}
/**
* 녹음 조각 하나를 이어 붙인다.
*
* 본문은 MediaRecorder가 준 바이트 그대로다. JSON이나 multipart로 감싸면
* base64 팽창이나 파싱 비용만 늘어난다.
*/
export async function POST(request: NextRequest, context: RouteContext) {
try {
const { id } = await context.params
if (!isValidRecordingId(id)) {
return Response.json(
{ error: '잘못된 녹음 세션 ID입니다.' },
{ status: 400 },
)
}
const buffer = Buffer.from(await request.arrayBuffer())
if (buffer.byteLength === 0) {
return Response.json({ error: '빈 조각입니다.' }, { status: 400 })
}
if (buffer.byteLength > MAX_CHUNK_BYTES) {
return Response.json(
{ error: '조각이 너무 큽니다.' },
{ status: 413 },
)
}
const result = await appendChunk(id, buffer)
if (!result.ok) {
return Response.json({ error: result.error }, { status: result.status })
}
return Response.json({ bytes: result.bytes })
} catch (err) {
const message = err instanceof Error ? err.message : '알 수 없는 오류'
return Response.json(
{ error: `녹음 조각 저장 실패: ${message}` },
{ status: 500 },
)
}
}
+86
View File
@@ -0,0 +1,86 @@
import { NextRequest } from 'next/server'
import { Readable } from 'stream'
import { finalizeRecording, getRecordingStatus, openRecording } from '@/lib/recording-store'
import { extensionForMimeType, isValidRecordingId } from '@/lib/recording'
export const dynamic = 'force-dynamic'
interface RouteContext {
params: Promise<{ id: string }>
}
/** 녹음 파일 내려받기. 헤더에는 사용자 입력을 넣지 않는다. */
export async function GET(_request: NextRequest, context: RouteContext) {
const { id } = await context.params
if (!isValidRecordingId(id)) {
return Response.json({ error: '잘못된 녹음 세션 ID입니다.' }, { status: 400 })
}
const opened = await openRecording(id)
if (!opened) {
return Response.json({ error: '녹음을 찾을 수 없습니다.' }, { status: 404 })
}
const { meta, bytes, stream } = opened
const stamp = meta.startedAt.slice(0, 16).replace(/[-:]/g, '').replace('T', '-')
const fileName = `meeting-${stamp}.${extensionForMimeType(meta.mimeType)}`
return new Response(Readable.toWeb(stream as Readable) as ReadableStream, {
headers: {
'Content-Type': meta.mimeType,
'Content-Length': String(bytes),
'Content-Disposition': `attachment; filename="${fileName}"`,
'Cache-Control': 'no-store',
},
})
}
/** 녹음 종료. 길이를 확정하고 최종 상태를 돌려준다. */
export async function POST(request: NextRequest, context: RouteContext) {
try {
const { id } = await context.params
if (!isValidRecordingId(id)) {
return Response.json(
{ error: '잘못된 녹음 세션 ID입니다.' },
{ status: 400 },
)
}
const body = await request.json().catch(() => ({}))
const durationMs =
typeof body.durationMs === 'number' ? body.durationMs : null
const status = await finalizeRecording(id, durationMs)
if (!status) {
return Response.json(
{ error: '녹음을 찾을 수 없습니다.' },
{ status: 404 },
)
}
return Response.json(status)
} catch (err) {
const message = err instanceof Error ? err.message : '알 수 없는 오류'
return Response.json(
{ error: `녹음 종료 처리 실패: ${message}` },
{ status: 500 },
)
}
}
/** 현재까지 저장된 크기 확인용. */
export async function HEAD(_request: NextRequest, context: RouteContext) {
const { id } = await context.params
if (!isValidRecordingId(id)) return new Response(null, { status: 400 })
const status = await getRecordingStatus(id)
if (!status) return new Response(null, { status: 404 })
return new Response(null, {
status: 200,
headers: { 'Content-Length': String(status.bytes) },
})
}
+31
View File
@@ -0,0 +1,31 @@
import { NextRequest } from 'next/server'
import { createRecording } from '@/lib/recording-store'
import { PREFERRED_MIME_TYPES } from '@/lib/recording'
export const dynamic = 'force-dynamic'
/** 브라우저가 고른 mimeType만 허용한다. 임의 문자열이 확장자로 새어들면 안 된다. */
const ALLOWED_MIME_TYPES: readonly string[] = PREFERRED_MIME_TYPES
export async function POST(request: NextRequest) {
try {
const body = await request.json().catch(() => ({}))
const { mimeType } = body
if (typeof mimeType !== 'string' || !ALLOWED_MIME_TYPES.includes(mimeType)) {
return Response.json(
{ error: '지원하지 않는 오디오 형식입니다.' },
{ status: 400 },
)
}
const meta = await createRecording(mimeType)
return Response.json(meta, { status: 201 })
} catch (err) {
const message = err instanceof Error ? err.message : '알 수 없는 오류'
return Response.json(
{ error: `녹음 세션 생성 실패: ${message}` },
{ status: 500 },
)
}
}
+117
View File
@@ -0,0 +1,117 @@
import { NextRequest } from 'next/server'
import { readFile } from 'fs/promises'
import path from 'path'
import { resolveTranscriptionSettings } from '@/lib/api-keys'
import { resolveSttModel, transcribe } from '@/lib/providers'
import { getRecording, RECORDINGS_DIR } from '@/lib/recording-store'
import { isValidRecordingId } from '@/lib/recording'
import { formatTranscriptionSegments } from '@/lib/transcript-formatter'
export const dynamic = 'force-dynamic'
/** 어휘 힌트는 Whisper가 약 224토큰까지만 본다. 넘겨도 버려지므로 잘라 보낸다. */
const MAX_VOCABULARY_HINT_CHARS = 800
export async function POST(request: NextRequest) {
try {
const body = await request.json().catch(() => ({}))
const { recordingId, language, vocabularyHint } = body
if (!isValidRecordingId(recordingId)) {
return Response.json(
{ error: '잘못된 녹음 세션 ID입니다.' },
{ status: 400 },
)
}
const meta = await getRecording(recordingId)
if (!meta) {
return Response.json(
{ error: '녹음을 찾을 수 없습니다.' },
{ status: 404 },
)
}
const settings = resolveTranscriptionSettings(body)
if (!settings) {
return Response.json(
{
error:
'AI 프로바이더가 설정되지 않았습니다. /settings에서 먼저 설정해주세요.',
},
{ status: 400 },
)
}
let bytes: Buffer
try {
bytes = await readFile(path.join(RECORDINGS_DIR, meta.fileName))
} catch {
return Response.json(
{ error: '녹음 파일을 읽을 수 없습니다. 오디오가 저장되지 않았을 수 있습니다.' },
{ status: 404 },
)
}
if (bytes.byteLength === 0) {
return Response.json(
{ error: '녹음 파일이 비어 있습니다.' },
{ status: 400 },
)
}
const result = await transcribe(
{
bytes,
mimeType: meta.mimeType,
fileName: meta.fileName,
language: typeof language === 'string' && language ? language : 'ko',
vocabularyHint:
typeof vocabularyHint === 'string' && vocabularyHint.trim().length > 0
? vocabularyHint.trim().slice(0, MAX_VOCABULARY_HINT_CHARS)
: undefined,
},
settings,
)
if (!result.success) {
return Response.json(
{ error: result.error },
{ status: result.rateLimited ? 429 : 502 },
)
}
// 구간 타임스탬프가 있으면 `[MM:SS]` 형식으로 맞춘다. 없으면 원문 그대로.
const transcript =
result.segments.length > 0
? formatTranscriptionSegments(result.segments)
: result.text
return Response.json({
transcript,
text: result.text,
segments: result.segments,
model: result.model,
hasTimestamps: result.segments.length > 0,
audioBytes: bytes.byteLength,
})
} catch (err) {
const message = err instanceof Error ? err.message : '알 수 없는 오류'
return Response.json({ error: `전사 실패: ${message}` }, { status: 500 })
}
}
/** 이 프로바이더 설정으로 전사가 가능한지 미리 확인. */
export async function GET(request: NextRequest) {
const url = new URL(request.url)
const settings = resolveTranscriptionSettings({
provider: url.searchParams.get('provider'),
baseUrl: url.searchParams.get('baseUrl'),
apiKey: url.searchParams.get('apiKey'),
})
return Response.json({
configured: settings !== null,
model: settings ? resolveSttModel(settings) : null,
})
}
+22 -10
View File
@@ -1,10 +1,20 @@
import { NextRequest } from 'next/server' import { NextRequest } from 'next/server'
import { handleUpload } from '@/lib/upload-handler' import { handleUpload } from '@/lib/upload-handler'
import { writeFile, mkdir } from 'fs/promises' import {
import path from 'path' appendChunk,
createRecording,
finalizeRecording,
} from '@/lib/recording-store'
const UPLOAD_DIR = path.join(process.cwd(), 'uploads') export const dynamic = 'force-dynamic'
/**
* 오디오 파일 업로드.
*
* 예전에는 `uploads/`에 파일만 떨궈 두고 아무것도 하지 않는 막다른 길이었다.
* 지금은 녹음 저장소에 그대로 넣어 `recordingId`를 돌려주므로, 브라우저 녹음과
* 똑같이 `/api/transcribe`로 전사할 수 있다. 두 경로가 한 파이프라인으로 만난다.
*/
export async function POST(request: NextRequest) { export async function POST(request: NextRequest) {
try { try {
const formData = await request.formData() const formData = await request.formData()
@@ -15,19 +25,21 @@ export async function POST(request: NextRequest) {
} }
const audioFile = formData.get('audio') as File const audioFile = formData.get('audio') as File
const buffer = Buffer.from(await audioFile.arrayBuffer()) const bytes = Buffer.from(await audioFile.arrayBuffer())
await mkdir(UPLOAD_DIR, { recursive: true }) const meta = await createRecording(result.data.mimeType)
const appended = await appendChunk(meta.id, bytes)
const timestamp = Date.now() if (!appended.ok) {
const safeFileName = `${timestamp}_${result.data.fileName.replace(/[^a-zA-Z0-9._-]/g, '_')}` return Response.json({ error: appended.error }, { status: appended.status })
const filePath = path.join(UPLOAD_DIR, safeFileName) }
await writeFile(filePath, buffer) await finalizeRecording(meta.id, null)
return Response.json({ return Response.json({
...result.data, ...result.data,
savedAs: safeFileName, recordingId: meta.id,
savedAs: meta.fileName,
}) })
} catch (err) { } catch (err) {
const message = err instanceof Error ? err.message : '알 수 없는 오류' const message = err instanceof Error ? err.message : '알 수 없는 오류'
+92 -5
View File
@@ -1,9 +1,12 @@
'use client' 'use client'
import { useMemo, useState } from 'react' import { useCallback, useMemo, useState } from 'react'
import Link from 'next/link' import Link from 'next/link'
import { AudioUploader } from '@/components/upload/AudioUploader' import { AudioUploader } from '@/components/upload/AudioUploader'
import { LiveRecorder } from '@/components/recorder/LiveRecorder' import { LiveRecorder } from '@/components/recorder/LiveRecorder'
import type { CompletedRecording } from '@/hooks/useAudioRecorder'
import { extensionForMimeType } from '@/lib/recording'
import { useTranscription } from '@/hooks/useTranscription'
import { MinutesViewer } from '@/components/minutes/MinutesViewer' import { MinutesViewer } from '@/components/minutes/MinutesViewer'
import { getProviderRequestPayload } from '@/lib/api-key-storage' import { getProviderRequestPayload } from '@/lib/api-key-storage'
import { import {
@@ -43,6 +46,9 @@ export default function HomePage() {
const [loading, setLoading] = useState(false) const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
const [uploadedFile, setUploadedFile] = useState<File | null>(null) const [uploadedFile, setUploadedFile] = useState<File | null>(null)
const [audio, setAudio] = useState<CompletedRecording | null>(null)
const [uploadedRecordingId, setUploadedRecordingId] = useState<string | null>(null)
const [attendees, setAttendees] = useState('')
const templateList = useMemo( const templateList = useMemo(
() => [ () => [
@@ -77,6 +83,7 @@ export default function HomePage() {
async function handleUpload(file: File) { async function handleUpload(file: File) {
setUploadedFile(file) setUploadedFile(file)
setUploadedRecordingId(null)
setError(null) setError(null)
const formData = new FormData() const formData = new FormData()
@@ -93,6 +100,7 @@ export default function HomePage() {
} }
if (!title) setTitle(data.title) if (!title) setTitle(data.title)
setUploadedRecordingId(data.recordingId ?? null)
} catch { } catch {
setError('파일 업로드에 실패했습니다.') setError('파일 업로드에 실패했습니다.')
} }
@@ -146,6 +154,37 @@ export default function HomePage() {
generateMinutes(text, summaryMode) generateMinutes(text, summaryMode)
} }
const handleRecordingReady = useCallback((recording: CompletedRecording) => {
setAudio(recording)
}, [])
const {
isTranscribing: isTranscribingUpload,
error: uploadTranscribeError,
result: uploadTranscription,
transcribeRecording: transcribeUpload,
} = useTranscription()
async function transcribeUploadedFile() {
if (!uploadedRecordingId) return
const outcome = await transcribeUpload(uploadedRecordingId, {
vocabularyHint: attendees,
})
if (outcome?.transcript) {
setTranscript(outcome.transcript)
generateMinutes(outcome.transcript, summaryMode)
}
}
// 회의록과 함께 저장할 오디오 정보. 서버 사본이 없으면 붙일 게 없다.
const audioMeta = audio?.recordingId
? {
audioFileName: `${audio.recordingId}.${extensionForMimeType(audio.mimeType)}`,
audioMimeType: audio.mimeType,
audioDuration: Math.round(audio.durationMs / 1000),
}
: undefined
const liveSummaryActive = const liveSummaryActive =
summaryMode === 'gemini' && activeTemplateMeta.live && tab === 'record' summaryMode === 'gemini' && activeTemplateMeta.live && tab === 'record'
@@ -188,6 +227,22 @@ export default function HomePage() {
/> />
</section> </section>
<section className="mb-8">
<label className="block text-sm font-medium text-neutral-600 mb-2">
참석자 · 용어 <span className="font-normal text-neutral-400">(선택)</span>
</label>
<input
type="text"
value={attendees}
onChange={(e) => setAttendees(e.target.value)}
placeholder="예: 김효천, 이지안, 계명대동산병원, PACS"
className="w-full rounded-xl border border-neutral-300 px-4 py-3 text-sm text-neutral-800 placeholder:text-neutral-400 focus:border-blue-400 focus:outline-none focus:ring-2 focus:ring-blue-100 transition-all"
/>
<p className="mt-1.5 text-xs text-neutral-500">
이름·제품명·사내 용어를 적어두면 전사가 고유명사를 훨씬 정확히 잡습니다.
</p>
</section>
<section className="mb-8 space-y-5"> <section className="mb-8 space-y-5">
<div className="flex items-center gap-4"> <div className="flex items-center gap-4">
<label className="text-sm font-medium text-neutral-600 min-w-20"> <label className="text-sm font-medium text-neutral-600 min-w-20">
@@ -328,6 +383,10 @@ export default function HomePage() {
{tab === 'record' ? ( {tab === 'record' ? (
<LiveRecorder <LiveRecorder
onTranscriptReady={handleTranscriptReady} onTranscriptReady={handleTranscriptReady}
onRecordingReady={handleRecordingReady}
onTranscriptReplaced={setTranscript}
title={title}
vocabularyHint={attendees}
liveSummaryEnabled={liveSummaryActive} liveSummaryEnabled={liveSummaryActive}
template={template} template={template}
depth={depth} depth={depth}
@@ -352,12 +411,39 @@ export default function HomePage() {
</section> </section>
)} )}
{uploadedFile && !transcript && ( {uploadedFile && (
<section className="mb-8"> <section className="mb-8 space-y-3">
<div className="rounded-xl border border-blue-200 bg-blue-50 p-4 text-sm text-blue-700"> <div className="rounded-xl border border-blue-200 bg-blue-50 p-4 text-sm text-blue-700">
<strong>{uploadedFile.name}</strong> 업로드 완료. <strong>{uploadedFile.name}</strong> 업로드 완료
실시간 녹음 탭에서 음성 인식을 시작하거나, 텍스트를 직접 입력해주세요. {uploadedRecordingId
? ' — 아래 버튼으로 전사를 시작하세요.'
: ' — 서버 저장에 실패해 전사할 수 없습니다.'}
</div> </div>
{uploadedRecordingId && (
<button
onClick={transcribeUploadedFile}
disabled={isTranscribingUpload}
className="w-full rounded-xl bg-neutral-900 px-6 py-3 text-sm font-medium text-white hover:bg-neutral-800 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
{isTranscribingUpload
? '전사 중… 회의 길이에 따라 몇 분 걸릴 수 있습니다'
: '🔤 전사 시작'}
</button>
)}
{uploadTranscribeError && (
<div className="rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700">
<strong>전사 오류:</strong> {uploadTranscribeError}
</div>
)}
{uploadTranscription && (
<div className="rounded-xl border border-blue-200 bg-blue-50 p-4 text-sm text-blue-800">
🔤 전사 완료 — {uploadTranscription.model} 모델,{' '}
{uploadTranscription.segments.length}개 구간
</div>
)}
</section> </section>
)} )}
@@ -391,6 +477,7 @@ export default function HomePage() {
depth={depth} depth={depth}
customPrompt={template === 'custom' ? customPrompt : undefined} customPrompt={template === 'custom' ? customPrompt : undefined}
summaryMode={summaryMode} summaryMode={summaryMode}
audio={audioMeta}
/> />
)} )}
</div> </div>
+31 -1
View File
@@ -27,6 +27,7 @@ export default function SettingsPage() {
const [apiKey, setApiKey] = useState('') const [apiKey, setApiKey] = useState('')
const [baseUrl, setBaseUrl] = useState('') const [baseUrl, setBaseUrl] = useState('')
const [model, setModel] = useState('') const [model, setModel] = useState('')
const [sttModel, setSttModel] = useState('')
const [showKey, setShowKey] = useState(false) const [showKey, setShowKey] = useState(false)
const [savedKey, setSavedKey] = useState<string | null>(null) const [savedKey, setSavedKey] = useState<string | null>(null)
const [envConfigured, setEnvConfigured] = useState<boolean | null>(null) const [envConfigured, setEnvConfigured] = useState<boolean | null>(null)
@@ -44,12 +45,15 @@ export default function SettingsPage() {
setApiKey(stored.apiKey) setApiKey(stored.apiKey)
setBaseUrl(stored.baseUrl) setBaseUrl(stored.baseUrl)
setModel(stored.model) setModel(stored.model)
setSttModel(stored.sttModel ?? '')
setSavedKey(stored.apiKey || null) setSavedKey(stored.apiKey || null)
} else { } else {
// 프로바이더 설정 이전에 저장해둔 Gemini 키를 그대로 이어받는다. // 프로바이더 설정 이전에 저장해둔 Gemini 키를 그대로 이어받는다.
const legacyKey = getStoredApiKey() const legacyKey = getStoredApiKey()
setApiKey(legacyKey ?? '') setApiKey(legacyKey ?? '')
setModel(findPreset(DEFAULT_PRESET_ID).defaultModel) const initial = findPreset(DEFAULT_PRESET_ID)
setModel(initial.defaultModel)
setSttModel(initial.defaultSttModel)
setSavedKey(legacyKey) setSavedKey(legacyKey)
} }
@@ -66,6 +70,7 @@ export default function SettingsPage() {
setPresetId(next.id) setPresetId(next.id)
setBaseUrl(next.baseUrl) setBaseUrl(next.baseUrl)
setModel(next.defaultModel) setModel(next.defaultModel)
setSttModel(next.defaultSttModel)
// 프로바이더가 바뀌면 이전 키는 무의미할 뿐 아니라, 그대로 두면 // 프로바이더가 바뀌면 이전 키는 무의미할 뿐 아니라, 그대로 두면
// 다른 회사 엔드포인트로 전송될 수 있으므로 비운다. // 다른 회사 엔드포인트로 전송될 수 있으므로 비운다.
setApiKey('') setApiKey('')
@@ -78,6 +83,7 @@ export default function SettingsPage() {
apiKey: apiKey.trim(), apiKey: apiKey.trim(),
baseUrl: baseUrl.trim(), baseUrl: baseUrl.trim(),
model: model.trim(), model: model.trim(),
sttModel: sttModel.trim(),
}) })
setSavedKey(apiKey.trim() || null) setSavedKey(apiKey.trim() || null)
setSavedToast(true) setSavedToast(true)
@@ -99,6 +105,7 @@ export default function SettingsPage() {
setApiKey('') setApiKey('')
setBaseUrl(fallback.baseUrl) setBaseUrl(fallback.baseUrl)
setModel(fallback.defaultModel) setModel(fallback.defaultModel)
setSttModel(fallback.defaultSttModel)
setSavedKey(null) setSavedKey(null)
setTestState({ status: 'idle' }) setTestState({ status: 'idle' })
} }
@@ -286,6 +293,29 @@ export default function SettingsPage() {
)} )}
</div> </div>
<div className="mt-5">
<label className="mb-2 block text-sm text-neutral-600">
음성 전사(STT) 모델
</label>
<input
type="text"
value={sttModel}
onChange={(e) => setSttModel(e.target.value)}
placeholder={preset.defaultSttModel || 'whisper-1'}
className="w-full rounded-xl border border-neutral-300 px-4 py-3 font-mono text-sm focus:border-purple-400 focus:outline-none focus:ring-2 focus:ring-purple-100 transition-all"
/>
<p className="mt-1 text-xs text-neutral-500">
녹음 오디오를 텍스트로 옮길 때 쓰는 모델입니다. 요약 모델과 별개입니다.
</p>
{!preset.canTranscribeWebm && (
<p className="mt-2 rounded-lg bg-amber-50 px-3 py-2 text-xs text-amber-800">
⚠️ 이 프로바이더는 브라우저 녹음 형식(webm)을 받지 않습니다. 실시간
녹음을 전사하려면 OpenAI 호환 프로바이더(OrcaRouter · OpenAI ·
로컬 whisper)를 선택하세요. 업로드한 mp3·wav·flac 파일은 전사됩니다.
</p>
)}
</div>
<div className="mt-5"> <div className="mt-5">
<label className="mb-2 block text-sm text-neutral-600"> <label className="mb-2 block text-sm text-neutral-600">
{preset.apiKeyLabel} {preset.apiKeyLabel}
+8
View File
@@ -22,6 +22,12 @@ interface MinutesViewerProps {
depth?: SummaryDepth depth?: SummaryDepth
customPrompt?: string customPrompt?: string
summaryMode?: 'simple' | 'gemini' summaryMode?: 'simple' | 'gemini'
/** 이 회의록의 원본 오디오. 서버에 보관된 녹음이 있을 때만 붙는다. */
audio?: {
audioFileName: string
audioMimeType: string
audioDuration: number
}
} }
type SaveState = type SaveState =
@@ -38,6 +44,7 @@ export function MinutesViewer({
template, template,
depth, depth,
customPrompt, customPrompt,
audio,
summaryMode, summaryMode,
}: MinutesViewerProps) { }: MinutesViewerProps) {
const [renderedView, setRenderedView] = useState<'rendered' | 'raw'>( const [renderedView, setRenderedView] = useState<'rendered' | 'raw'>(
@@ -110,6 +117,7 @@ export function MinutesViewer({
template, template,
depth, depth,
customPrompt, customPrompt,
...audio,
}), }),
}) })
const data = await res.json() const data = await res.json()
+147 -3
View File
@@ -3,11 +3,20 @@
import { useEffect, useRef } from 'react' import { useEffect, useRef } from 'react'
import { useSpeechRecognition } from '@/hooks/useSpeechRecognition' import { useSpeechRecognition } from '@/hooks/useSpeechRecognition'
import { useLiveSummary } from '@/hooks/useLiveSummary' import { useLiveSummary } from '@/hooks/useLiveSummary'
import { useAudioRecorder, type CompletedRecording } from '@/hooks/useAudioRecorder'
import { formatTranscriptChunks } from '@/lib/transcript-formatter' import { formatTranscriptChunks } from '@/lib/transcript-formatter'
import { useTranscription } from '@/hooks/useTranscription'
import { formatBytes, formatDuration } from '@/lib/recording'
import type { SummaryDepth, TemplateId } from '@/lib/templates' import type { SummaryDepth, TemplateId } from '@/lib/templates'
interface LiveRecorderProps { interface LiveRecorderProps {
onTranscriptReady: (transcript: string) => void onTranscriptReady: (transcript: string) => void
onRecordingReady?: (recording: CompletedRecording) => void
/** STT 재전사 결과로 전사문을 갈아끼운다. */
onTranscriptReplaced?: (transcript: string) => void
title: string
/** 참석자 등 고유명사 힌트. STT 정확도를 올린다. */
vocabularyHint?: string
liveSummaryEnabled: boolean liveSummaryEnabled: boolean
template: TemplateId template: TemplateId
depth: SummaryDepth depth: SummaryDepth
@@ -16,6 +25,10 @@ interface LiveRecorderProps {
export function LiveRecorder({ export function LiveRecorder({
onTranscriptReady, onTranscriptReady,
onRecordingReady,
onTranscriptReplaced,
title,
vocabularyHint,
liveSummaryEnabled, liveSummaryEnabled,
template, template,
depth, depth,
@@ -32,6 +45,29 @@ export function LiveRecorder({
resetChunks, resetChunks,
} = useSpeechRecognition() } = useSpeechRecognition()
const {
isRecording,
isSupported: isRecordingSupported,
error: recordingError,
uploadWarning,
elapsedMs,
localBytes,
uploadedBytes,
recording,
startRecording,
stopRecording,
downloadRecording,
reset: resetRecording,
} = useAudioRecorder()
const {
isTranscribing,
error: transcriptionError,
result: transcription,
transcribeRecording,
reset: resetTranscription,
} = useTranscription()
const { const {
summary, summary,
isSummarizing, isSummarizing,
@@ -59,6 +95,11 @@ export function LiveRecorder({
summaryEndRef.current?.scrollIntoView({ behavior: 'smooth', block: 'end' }) summaryEndRef.current?.scrollIntoView({ behavior: 'smooth', block: 'end' })
}, [summary]) }, [summary])
// 녹음이 끝나 파일이 확정되면 상위로 올려 회의록과 함께 저장되게 한다.
useEffect(() => {
if (recording) onRecordingReady?.(recording)
}, [recording, onRecordingReady])
if (isSupported === null) { if (isSupported === null) {
return ( return (
<div className="rounded-2xl border border-neutral-200 bg-neutral-50 p-6 text-center text-sm text-neutral-400"> <div className="rounded-2xl border border-neutral-200 bg-neutral-50 p-6 text-center text-sm text-neutral-400">
@@ -78,12 +119,23 @@ export function LiveRecorder({
) )
} }
function handleStop() { async function handleStart() {
resetRecording()
resetTranscription()
// 오디오 녹음을 먼저 건다. 전사가 실패하더라도 원본은 남아야 한다.
await startRecording()
startListening()
}
async function handleStop() {
stopListening() stopListening()
const transcript = formatTranscriptChunks(chunks) const transcript = formatTranscriptChunks(chunks)
if (transcript.length > 0) { if (transcript.length > 0) {
onTranscriptReady(transcript) onTranscriptReady(transcript)
} }
await stopRecording()
} }
const lastUpdatedLabel = lastUpdatedAt const lastUpdatedLabel = lastUpdatedAt
@@ -136,7 +188,7 @@ export function LiveRecorder({
</button> </button>
) : ( ) : (
<button <button
onClick={startListening} onClick={handleStart}
className="flex items-center gap-2 rounded-full bg-blue-600 px-6 py-3 text-white font-medium shadow-lg shadow-blue-600/25 hover:bg-blue-700 transition-colors" className="flex items-center gap-2 rounded-full bg-blue-600 px-6 py-3 text-white font-medium shadow-lg shadow-blue-600/25 hover:bg-blue-700 transition-colors"
> >
<span className="text-lg">🎤</span> <span className="text-lg">🎤</span>
@@ -144,9 +196,37 @@ export function LiveRecorder({
</button> </button>
)} )}
{recording?.recordingId && !isListening && (
<button
onClick={async () => {
const outcome = await transcribeRecording(recording.recordingId!, {
vocabularyHint,
})
if (outcome?.transcript) onTranscriptReplaced?.(outcome.transcript)
}}
disabled={isTranscribing}
className="flex items-center gap-2 rounded-full bg-neutral-900 px-5 py-2.5 text-sm font-medium text-white hover:bg-neutral-800 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
{isTranscribing ? '전사 중… (몇 분 걸릴 수 있습니다)' : '🔤 원본 오디오로 다시 전사'}
</button>
)}
{recording && !isListening && (
<button
onClick={() => downloadRecording(title)}
className="flex items-center gap-2 rounded-full border border-emerald-300 bg-emerald-50 px-4 py-2 text-sm font-medium text-emerald-700 hover:bg-emerald-100 transition-colors"
>
⬇️ 오디오 내려받기 ({formatBytes(recording.blob.size)})
</button>
)}
{chunks.length > 0 && !isListening && ( {chunks.length > 0 && !isListening && (
<button <button
onClick={resetChunks} onClick={() => {
resetChunks()
resetRecording()
resetTranscription()
}}
className="rounded-full border border-neutral-300 px-4 py-2 text-sm text-neutral-600 hover:bg-neutral-50 transition-colors" className="rounded-full border border-neutral-300 px-4 py-2 text-sm text-neutral-600 hover:bg-neutral-50 transition-colors"
> >
초기화 초기화
@@ -159,14 +239,78 @@ export function LiveRecorder({
녹음 중 · {wordCount}단어 · {chunks.length}개 구간 녹음 중 · {wordCount}단어 · {chunks.length}개 구간
</div> </div>
)} )}
{isRecording && (
<div className="flex items-center gap-2 rounded-full bg-neutral-100 px-4 py-1.5 text-xs text-neutral-600">
<span className="text-sm">🎧</span>
오디오 {formatDuration(elapsedMs)} · 저장 {formatBytes(uploadedBytes)}
{localBytes > 0 && uploadedBytes < localBytes && (
<span className="text-amber-600">
(전송 대기 {formatBytes(localBytes - uploadedBytes)})
</span>
)}
</div>
)}
</div> </div>
{isRecordingSupported === false && (
<div className="rounded-xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800">
이 브라우저는 오디오 녹음을 지원하지 않습니다. 전사만 진행되며,
<strong> 놓친 발화를 나중에 복구할 수 없습니다.</strong> Chrome을 사용해주세요.
</div>
)}
{recordingError && (
<div className="rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700">
<strong>오디오 녹음 오류:</strong> {recordingError}
</div>
)}
{uploadWarning && (
<div className="rounded-xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800">
<strong>⚠️ 서버 저장 문제:</strong> {uploadWarning}
</div>
)}
{recognitionError && ( {recognitionError && (
<div className="rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700"> <div className="rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700">
<strong>음성 인식 오류:</strong> {recognitionError} <strong>음성 인식 오류:</strong> {recognitionError}
</div> </div>
)} )}
{transcriptionError && (
<div className="rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700">
<strong>전사 오류:</strong> {transcriptionError}
</div>
)}
{transcription && (
<div className="rounded-xl border border-blue-200 bg-blue-50 p-4 text-sm text-blue-800">
<strong>🔤 재전사 완료</strong> — {transcription.model} 모델,{' '}
{transcription.segments.length > 0
? `${transcription.segments.length}개 구간 (실제 오디오 타임스탬프)`
: '타임스탬프 없음'}
. 아래 텍스트가 교체되었습니다.
</div>
)}
{recording && !isListening && (
<div className="rounded-xl border border-emerald-200 bg-emerald-50 p-4 text-sm text-emerald-800">
<strong>
🎧 오디오 {formatDuration(recording.durationMs)} ·{' '}
{formatBytes(recording.blob.size)} 확보
</strong>
{' — '}
{recording.recordingId
? `서버에 ${formatBytes(recording.uploadedBytes)} 저장됨.`
: '서버 저장 실패 — 브라우저 사본만 있습니다.'}{' '}
전사가 놓친 발화는 이 오디오로 다시 살릴 수 있습니다.
{!recording.recordingId && (
<strong> 지금 내려받아 보관해주세요.</strong>
)}
</div>
)}
{isListening && !hasTranscript && ( {isListening && !hasTranscript && (
<div className="rounded-2xl border border-dashed border-blue-300 bg-blue-50/50 p-6 text-center"> <div className="rounded-2xl border border-dashed border-blue-300 bg-blue-50/50 p-6 text-center">
<p className="text-sm text-blue-700"> <p className="text-sm text-blue-700">
+390
View File
@@ -0,0 +1,390 @@
'use client'
import { useCallback, useEffect, useRef, useState } from 'react'
import {
AUDIO_BITS_PER_SECOND,
CHUNK_INTERVAL_MS,
RECORDING_AUDIO_CONSTRAINTS,
pickRecorderMimeType,
recordingDownloadName,
} from '@/lib/recording'
export interface CompletedRecording {
/** 서버 세션 id. 세션 생성에 실패했으면 null이고 로컬 사본만 있다. */
recordingId: string | null
mimeType: string
blob: Blob
durationMs: number
startedAt: Date
/** 서버에 실제로 저장된 바이트. 0이거나 blob보다 작으면 일부가 못 올라갔다. */
uploadedBytes: number
}
export interface AudioRecorderHook {
isRecording: boolean
isSupported: boolean | null
/** 녹음을 시작조차 못하게 만든 오류. */
error: string | null
/** 녹음은 되고 있으나 서버 사본에 문제가 있을 때의 경고. */
uploadWarning: string | null
elapsedMs: number
localBytes: number
uploadedBytes: number
recording: CompletedRecording | null
startRecording: () => Promise<void>
stopRecording: () => Promise<void>
downloadRecording: (title: string) => void
reset: () => void
}
const MAX_CHUNK_RETRIES = 3
function describeCaptureError(err: unknown): string {
const name = err instanceof Error ? err.name : ''
switch (name) {
case 'NotAllowedError':
case 'SecurityError':
return '마이크 권한이 거부되어 녹음할 수 없습니다. 주소창 왼쪽 자물쇠 아이콘에서 마이크를 허용해주세요.'
case 'NotFoundError':
return '마이크를 찾을 수 없습니다. 장치가 연결되어 있는지 확인해주세요.'
case 'NotReadableError':
return '다른 프로그램이 마이크를 사용 중입니다. 해당 프로그램을 종료하고 다시 시도해주세요.'
default:
return err instanceof Error
? `마이크를 열 수 없습니다: ${err.message}`
: '마이크를 열 수 없습니다.'
}
}
/**
* 회의 오디오를 파일로 남긴다.
*
* 전사와 독립적으로 동작한다. Web Speech가 발화를 놓치든 네트워크가 끊기든
* 오디오만은 남아야 나중에 서버 STT로 다시 살릴 수 있다. 그래서 서버 업로드가
* 실패해도 녹음을 중단하지 않고, 브라우저 안의 사본을 끝까지 들고 간다.
*/
export function useAudioRecorder(): AudioRecorderHook {
const [isSupported, setIsSupported] = useState<boolean | null>(null)
const [isRecording, setIsRecording] = useState(false)
const [error, setError] = useState<string | null>(null)
const [uploadWarning, setUploadWarning] = useState<string | null>(null)
const [elapsedMs, setElapsedMs] = useState(0)
const [localBytes, setLocalBytes] = useState(0)
const [uploadedBytes, setUploadedBytes] = useState(0)
const [recording, setRecording] = useState<CompletedRecording | null>(null)
const recorderRef = useRef<MediaRecorder | null>(null)
const streamRef = useRef<MediaStream | null>(null)
const partsRef = useRef<Blob[]>([])
const sessionIdRef = useRef<string | null>(null)
const mimeTypeRef = useRef<string | null>(null)
const startedAtRef = useRef<Date | null>(null)
const uploadChainRef = useRef<Promise<void>>(Promise.resolve())
const uploadBrokenRef = useRef(false)
useEffect(() => {
setIsSupported(
typeof window !== 'undefined' &&
typeof window.MediaRecorder !== 'undefined' &&
typeof navigator !== 'undefined' &&
!!navigator.mediaDevices?.getUserMedia,
)
}, [])
// 녹음 중에는 1초마다 경과 시간을 갱신한다. 이 시각이 나중에 전사 청크를
// 오디오 타임라인에 맞추는 기준이 된다.
useEffect(() => {
if (!isRecording) return
const timer = setInterval(() => {
if (startedAtRef.current) {
setElapsedMs(Date.now() - startedAtRef.current.getTime())
}
}, 1000)
return () => clearInterval(timer)
}, [isRecording])
// 녹음 중 탭을 닫으면 아직 못 올린 조각이 사라진다. 확인을 한 번 받는다.
useEffect(() => {
if (!isRecording) return
function warn(event: BeforeUnloadEvent) {
event.preventDefault()
}
window.addEventListener('beforeunload', warn)
return () => window.removeEventListener('beforeunload', warn)
}, [isRecording])
/**
* 조각을 순서대로 올린다.
*
* 순서가 곧 파일의 순서이므로 병렬로 보내지 않는다. 한 조각이 끝내 실패하면
* 그 뒤를 이어 붙여봐야 중간이 비어 재생도 전사도 안 되는 파일이 되므로,
* 그 시점에 업로드를 멈추고 로컬 사본을 쓰라고 알린다.
*/
const queueUpload = useCallback((chunk: Blob) => {
const id = sessionIdRef.current
if (!id || uploadBrokenRef.current) return
uploadChainRef.current = uploadChainRef.current.then(async () => {
if (uploadBrokenRef.current) return
for (let attempt = 1; attempt <= MAX_CHUNK_RETRIES; attempt++) {
try {
const res = await fetch(`/api/recordings/${id}/chunk`, {
method: 'POST',
headers: { 'Content-Type': 'application/octet-stream' },
body: chunk,
})
if (res.ok) {
const data = await res.json()
setUploadedBytes(data.bytes)
return
}
// 4xx는 재시도해도 같은 답이 온다.
if (res.status >= 400 && res.status < 500) break
} catch {
// 네트워크 오류 — 아래에서 재시도한다.
}
if (attempt < MAX_CHUNK_RETRIES) {
await new Promise((resolve) => setTimeout(resolve, 500 * attempt))
}
}
uploadBrokenRef.current = true
setUploadWarning(
'서버 저장이 중단되었습니다. 녹음은 계속되고 있으니 종료 후 반드시 오디오를 내려받아 주세요.',
)
})
}, [])
const startRecording = useCallback(async () => {
if (recorderRef.current) return
setError(null)
setUploadWarning(null)
setRecording(null)
setElapsedMs(0)
setLocalBytes(0)
setUploadedBytes(0)
partsRef.current = []
sessionIdRef.current = null
uploadBrokenRef.current = false
uploadChainRef.current = Promise.resolve()
if (isSupported !== true) {
setError('이 브라우저는 오디오 녹음을 지원하지 않습니다. Chrome을 사용해주세요.')
return
}
const mimeType = pickRecorderMimeType((type) =>
MediaRecorder.isTypeSupported(type),
)
if (!mimeType) {
setError('브라우저가 지원하는 녹음 형식을 찾지 못했습니다.')
return
}
let stream: MediaStream
try {
stream = await navigator.mediaDevices.getUserMedia({
audio: RECORDING_AUDIO_CONSTRAINTS,
})
} catch (err) {
setError(describeCaptureError(err))
return
}
// 서버 세션은 있으면 좋고 없어도 녹음은 간다. 여기서 포기하면
// 오디오를 남기려던 목적 자체를 잃는다.
try {
const res = await fetch('/api/recordings', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ mimeType }),
})
if (res.ok) {
const meta = await res.json()
sessionIdRef.current = meta.id
} else {
uploadBrokenRef.current = true
setUploadWarning(
'서버에 녹음 세션을 만들지 못했습니다. 브라우저에만 저장되니 종료 후 반드시 내려받아 주세요.',
)
}
} catch {
uploadBrokenRef.current = true
setUploadWarning(
'서버에 연결하지 못했습니다. 브라우저에만 저장되니 종료 후 반드시 내려받아 주세요.',
)
}
const recorder = new MediaRecorder(stream, {
mimeType,
audioBitsPerSecond: AUDIO_BITS_PER_SECOND,
})
recorder.ondataavailable = (event) => {
if (event.data.size === 0) return
partsRef.current.push(event.data)
setLocalBytes((prev) => prev + event.data.size)
queueUpload(event.data)
}
recorder.onerror = () => {
setError('녹음 중 오류가 발생했습니다. 지금까지의 오디오는 보존되어 있습니다.')
}
streamRef.current = stream
recorderRef.current = recorder
mimeTypeRef.current = mimeType
startedAtRef.current = new Date()
recorder.start(CHUNK_INTERVAL_MS)
setIsRecording(true)
}, [isSupported, queueUpload])
const stopRecording = useCallback(async () => {
const recorder = recorderRef.current
if (!recorder) return
recorderRef.current = null
// stop()은 남은 버퍼를 dataavailable로 한 번 더 내보낸 뒤 stop을 쏜다.
// 그 마지막 조각까지 받아야 회의 끝부분이 잘리지 않는다.
if (recorder.state !== 'inactive') {
await new Promise<void>((resolve) => {
recorder.addEventListener('stop', () => resolve(), { once: true })
recorder.stop()
})
}
streamRef.current?.getTracks().forEach((track) => track.stop())
streamRef.current = null
await uploadChainRef.current
const startedAt = startedAtRef.current ?? new Date()
const durationMs = Date.now() - startedAt.getTime()
const mimeType = mimeTypeRef.current ?? 'audio/webm'
const id = sessionIdRef.current
const blob = new Blob(partsRef.current, { type: mimeType })
// 한 바이트도 못 받았으면 보관됐다고 말하면 안 된다. 이 기능의 요점은
// 오디오가 남는 것인데, 남지 않았는데 남았다고 알리면 사용자는 회의가
// 끝난 뒤에야 아무것도 없다는 걸 알게 된다.
if (blob.size === 0) {
setError(
'오디오가 한 조각도 캡처되지 않았습니다. 마이크 입력 장치를 확인하고 다시 녹음해주세요.',
)
setElapsedMs(durationMs)
setIsRecording(false)
return
}
let serverBytes = 0
if (id && !uploadBrokenRef.current) {
try {
const res = await fetch(`/api/recordings/${id}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ durationMs }),
})
if (res.ok) {
serverBytes = (await res.json()).bytes ?? 0
}
} catch {
setUploadWarning(
'녹음 종료 처리에 실패했습니다. 저장된 조각은 남아 있지만, 로컬 사본도 내려받아 두시길 권합니다.',
)
}
}
// 서버 사본이 로컬보다 짧으면 조각이 새어나간 것이다. 조용히 넘기지 않는다.
if (id && !uploadBrokenRef.current && serverBytes < blob.size) {
setUploadWarning(
`서버 사본이 로컬보다 짧습니다 (${serverBytes} / ${blob.size} bytes). 오디오를 내려받아 보관해주세요.`,
)
}
setElapsedMs(durationMs)
setUploadedBytes(serverBytes)
setRecording({
recordingId: uploadBrokenRef.current ? null : id,
mimeType,
blob,
durationMs,
startedAt,
uploadedBytes: serverBytes,
})
setIsRecording(false)
}, [])
const downloadRecording = useCallback((title: string) => {
const parts = partsRef.current
if (parts.length === 0) return
const mimeType = mimeTypeRef.current ?? 'audio/webm'
const blob = new Blob(parts, { type: mimeType })
const url = URL.createObjectURL(blob)
const anchor = document.createElement('a')
anchor.href = url
anchor.download = recordingDownloadName(
title,
startedAtRef.current ?? new Date(),
mimeType,
)
document.body.appendChild(anchor)
anchor.click()
anchor.remove()
setTimeout(() => URL.revokeObjectURL(url), 1_000)
}, [])
const reset = useCallback(() => {
partsRef.current = []
sessionIdRef.current = null
startedAtRef.current = null
uploadBrokenRef.current = false
setRecording(null)
setElapsedMs(0)
setLocalBytes(0)
setUploadedBytes(0)
setError(null)
setUploadWarning(null)
}, [])
// 언마운트 시 마이크를 놓아준다. 탭 표시등이 켜진 채 남지 않도록.
useEffect(() => {
return () => {
const recorder = recorderRef.current
if (recorder && recorder.state !== 'inactive') {
recorder.stop()
}
streamRef.current?.getTracks().forEach((track) => track.stop())
}
}, [])
return {
isRecording,
isSupported,
error,
uploadWarning,
elapsedMs,
localBytes,
uploadedBytes,
recording,
startRecording,
stopRecording,
downloadRecording,
reset,
}
}
+86
View File
@@ -0,0 +1,86 @@
'use client'
import { useCallback, useState } from 'react'
import { getProviderRequestPayload } from '@/lib/api-key-storage'
import type { TranscriptionSegment } from '@/lib/providers/types'
export interface TranscriptionOutcome {
transcript: string
segments: TranscriptionSegment[]
model: string
hasTimestamps: boolean
}
export interface TranscriptionHook {
isTranscribing: boolean
error: string | null
result: TranscriptionOutcome | null
transcribeRecording: (
recordingId: string,
options?: { vocabularyHint?: string },
) => Promise<TranscriptionOutcome | null>
reset: () => void
}
/**
* 보관된 녹음을 서버 STT로 전사한다.
*
* Web Speech 결과를 덮어쓰는 것이 목적이다. 실시간 텍스트는 회의 중 흐름을
* 보기 위한 초안이고, 확정본은 원본 오디오에서 다시 뽑는다.
*/
export function useTranscription(): TranscriptionHook {
const [isTranscribing, setIsTranscribing] = useState(false)
const [error, setError] = useState<string | null>(null)
const [result, setResult] = useState<TranscriptionOutcome | null>(null)
const transcribeRecording = useCallback(
async (recordingId: string, options: { vocabularyHint?: string } = {}) => {
setIsTranscribing(true)
setError(null)
try {
const res = await fetch('/api/transcribe', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
recordingId,
language: 'ko',
vocabularyHint: options.vocabularyHint,
...getProviderRequestPayload(),
}),
})
const data = await res.json().catch(() => ({}))
if (!res.ok) {
setError(data.error ?? '전사에 실패했습니다.')
return null
}
const outcome: TranscriptionOutcome = {
transcript: data.transcript ?? '',
segments: Array.isArray(data.segments) ? data.segments : [],
model: data.model ?? '',
hasTimestamps: Boolean(data.hasTimestamps),
}
setResult(outcome)
return outcome
} catch (err) {
setError(
err instanceof Error ? `전사 요청 실패: ${err.message}` : '전사 요청 실패',
)
return null
} finally {
setIsTranscribing(false)
}
},
[],
)
const reset = useCallback(() => {
setResult(null)
setError(null)
}, [])
return { isTranscribing, error, result, transcribeRecording, reset }
}
+6
View File
@@ -48,6 +48,8 @@ export interface StoredProviderConfig {
apiKey: string apiKey: string
baseUrl: string baseUrl: string
model: string model: string
/** 음성 전사 모델. 비우면 프리셋 기본값을 쓴다. */
sttModel?: string
} }
export interface ProviderRequestPayload { export interface ProviderRequestPayload {
@@ -55,6 +57,7 @@ export interface ProviderRequestPayload {
apiKey: string apiKey: string
baseUrl: string baseUrl: string
model: string model: string
sttModel: string
} }
export function getStoredProviderConfig(): StoredProviderConfig | null { export function getStoredProviderConfig(): StoredProviderConfig | null {
@@ -69,6 +72,7 @@ export function getStoredProviderConfig(): StoredProviderConfig | null {
apiKey: typeof parsed.apiKey === 'string' ? parsed.apiKey : '', apiKey: typeof parsed.apiKey === 'string' ? parsed.apiKey : '',
baseUrl: typeof parsed.baseUrl === 'string' ? parsed.baseUrl : '', baseUrl: typeof parsed.baseUrl === 'string' ? parsed.baseUrl : '',
model: typeof parsed.model === 'string' ? parsed.model : '', model: typeof parsed.model === 'string' ? parsed.model : '',
sttModel: typeof parsed.sttModel === 'string' ? parsed.sttModel : '',
} }
} catch { } catch {
return null return null
@@ -108,6 +112,7 @@ export function getProviderRequestPayload(): ProviderRequestPayload {
apiKey: getStoredApiKey() ?? '', apiKey: getStoredApiKey() ?? '',
baseUrl: '', baseUrl: '',
model: '', model: '',
sttModel: '',
} }
} }
@@ -117,5 +122,6 @@ export function getProviderRequestPayload(): ProviderRequestPayload {
apiKey: stored.apiKey || (preset.provider === 'gemini' ? getStoredApiKey() ?? '' : ''), apiKey: stored.apiKey || (preset.provider === 'gemini' ? getStoredApiKey() ?? '' : ''),
baseUrl: stored.baseUrl, baseUrl: stored.baseUrl,
model: stored.model, model: stored.model,
sttModel: stored.sttModel ?? '',
} }
} }
+41 -1
View File
@@ -1,4 +1,9 @@
import { isProviderId, type ProviderId, type ProviderSettings } from './providers' import {
isProviderId,
type ProviderId,
type ProviderSettings,
type TranscriptionSettings,
} from './providers'
/** /**
* Gemini API 키 해석 우선순위: * Gemini API 키 해석 우선순위:
@@ -88,3 +93,38 @@ function str(value: unknown): string {
function env(name: string): string { function env(name: string): string {
return (process.env[name] ?? '').trim() return (process.env[name] ?? '').trim()
} }
export interface TranscriptionRequestBody extends ProviderRequestBody {
sttModel?: unknown
}
/**
* 전사용 프로바이더 설정.
*
* 요약과 달리 대화 모델 이름이 없어도 된다. 전사는 `sttModel`(비우면 프로바이더
* 기본값)로 별도 엔드포인트를 호출하므로, 대화 모델을 지정하지 않은 사용자도
* 전사는 쓸 수 있어야 한다.
*/
export function resolveTranscriptionSettings(
body: TranscriptionRequestBody | null | undefined,
): TranscriptionSettings | null {
const provider = resolveProvider(body?.provider)
const sttModel = str(body?.sttModel) || env('LLM_STT_MODEL')
if (provider === 'gemini') {
const apiKey = resolveGeminiApiKey(str(body?.apiKey) || env('LLM_API_KEY'))
if (!apiKey) return null
return { provider, apiKey, sttModel: sttModel || undefined }
}
const baseUrl = str(body?.baseUrl) || env('LLM_BASE_URL')
if (baseUrl.length === 0) return null
return {
provider,
apiKey: str(body?.apiKey) || env('LLM_API_KEY'),
baseUrl,
model: str(body?.model) || env('LLM_MODEL'),
sttModel: sttModel || undefined,
}
}
+189
View File
@@ -2,6 +2,11 @@ import type {
CompletionOptions, CompletionOptions,
CompletionResult, CompletionResult,
ProviderSettings, ProviderSettings,
TranscriptionInput,
TranscriptionOptions,
TranscriptionResult,
TranscriptionSegment,
TranscriptionSettings,
} from './types' } from './types'
export const DEFAULT_GEMINI_MODEL = 'gemini-3.5-flash-lite' export const DEFAULT_GEMINI_MODEL = 'gemini-3.5-flash-lite'
@@ -74,3 +79,187 @@ function describeHttpError(status: number): string {
} }
return `Gemini API 호출 실패: ${status}` return `Gemini API 호출 실패: ${status}`
} }
/**
* Gemini 오디오 입력 기본 모델.
* flash-lite는 오디오를 받지 않으므로 요약용 기본값과 다르다.
*/
export const DEFAULT_GEMINI_STT_MODEL = 'gemini-3.6-flash'
/**
* Gemini가 문서로 밝힌 오디오 형식.
*
* **webm은 여기에 없다.** 우리 브라우저 녹음이 webm/opus이므로 Gemini로는
* 실시간 녹음을 전사할 수 없고, 업로드한 mp3/wav/flac/ogg/m4a만 된다.
* 녹음 전사는 Whisper 호환 엔드포인트(OrcaRouter·OpenAI·로컬)를 써야 한다.
*/
const GEMINI_AUDIO_MIME_TYPES = [
'audio/wav',
'audio/x-wav',
'audio/mp3',
'audio/mpeg',
'audio/aiff',
'audio/aac',
'audio/ogg',
'audio/flac',
'audio/mp4',
'audio/x-m4a',
]
export function isGeminiSupportedAudioMimeType(mimeType: string): boolean {
const base = mimeType.split(';')[0].trim().toLowerCase()
return GEMINI_AUDIO_MIME_TYPES.includes(base)
}
/**
* inline_data로 보낼 수 있는 최대 오디오 크기.
*
* generateContent 요청 전체가 20MB를 넘으면 안 되는데 base64가 약 4/3배로
* 부풀리므로, 원본 기준 14MB에서 끊는다. 더 큰 파일은 Files API가 필요하다.
*/
export const GEMINI_INLINE_AUDIO_LIMIT = 14 * 1024 * 1024
function buildTranscriptionPrompt(input: TranscriptionInput): string {
const lines = [
'이 오디오는 회의 녹음입니다. 들리는 발화를 그대로 받아쓰세요.',
'',
'규칙:',
'- 요약하거나 문장을 다듬지 말고 말한 그대로 옮깁니다.',
'- 들리지 않는 구간은 지어내지 말고 건너뜁니다.',
'- 각 발화 앞에 `[MM:SS]` 형식으로 시작 시각을 붙입니다.',
'- 설명이나 머리말 없이 전사문만 출력합니다.',
]
if (input.vocabularyHint) {
lines.push(
'',
`이 회의에 나올 수 있는 고유명사·용어: ${input.vocabularyHint}`,
)
}
return lines.join('\n')
}
/** `[MM:SS] 텍스트` 또는 `[HH:MM:SS] 텍스트` 줄을 구간으로 바꾼다. */
export function parseTimestampedTranscript(text: string): TranscriptionSegment[] {
const segments: TranscriptionSegment[] = []
const pattern = /^\[(?:(\d{1,2}):)?(\d{1,2}):(\d{2})\]\s*(.+)$/
for (const line of text.split('\n')) {
const match = pattern.exec(line.trim())
if (!match) continue
const [, h, m, s, body] = match
const start = (h ? Number(h) * 3600 : 0) + Number(m) * 60 + Number(s)
const content = body.trim()
if (content.length === 0) continue
// 다음 구간이 시작될 때까지가 이 구간이다. 마지막은 뒤에서 채운다.
if (segments.length > 0) {
segments[segments.length - 1].end = start
}
segments.push({ start, end: start, text: content })
}
if (segments.length > 0) {
const last = segments[segments.length - 1]
if (last.end <= last.start) last.end = last.start + 1
}
return segments
}
/** Gemini에 오디오를 inline으로 실어 전사한다. */
export async function transcribeWithGemini(
input: TranscriptionInput,
settings: TranscriptionSettings,
options: TranscriptionOptions = {},
): Promise<TranscriptionResult> {
const { fetchFn = fetch } = options
const apiKey = settings.apiKey.trim()
if (apiKey.length === 0) {
return { success: false, error: 'Gemini API 키가 필요합니다.' }
}
const baseMime = input.mimeType.split(';')[0].trim().toLowerCase()
if (!isGeminiSupportedAudioMimeType(input.mimeType)) {
return {
success: false,
error:
`Gemini는 ${baseMime} 형식을 받지 않습니다. ` +
'브라우저 녹음(webm)을 전사하려면 설정에서 OpenAI 호환 프로바이더' +
'(OrcaRouter · OpenAI · 로컬 whisper)를 선택해주세요.',
}
}
if (input.bytes.byteLength > GEMINI_INLINE_AUDIO_LIMIT) {
return {
success: false,
error:
`오디오가 너무 큽니다 (${Math.round(input.bytes.byteLength / 1024 / 1024)}MB). ` +
`Gemini 직접 호출은 ${Math.round(GEMINI_INLINE_AUDIO_LIMIT / 1024 / 1024)}MB까지만 가능합니다. ` +
'OpenAI 호환 프로바이더를 쓰거나 오디오를 나눠주세요.',
}
}
const model = settings.sttModel?.trim() || DEFAULT_GEMINI_STT_MODEL
const url = `${API_ROOT}/${encodeURIComponent(model)}:generateContent`
try {
const response = await fetchFn(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-goog-api-key': apiKey,
},
body: JSON.stringify({
contents: [
{
parts: [
{ text: buildTranscriptionPrompt(input) },
{
inline_data: {
mime_type: baseMime,
data: Buffer.from(input.bytes).toString('base64'),
},
},
],
},
],
}),
})
if (!response.ok) {
if (response.status === 429) {
return {
success: false,
error: 'Gemini API 요청 한도 초과. 잠시 후 다시 시도해주세요.',
rateLimited: true,
}
}
return { success: false, error: describeHttpError(response.status) }
}
const data = await response.json()
const text: string = data?.candidates?.[0]?.content?.parts?.[0]?.text ?? ''
if (text.trim().length === 0) {
return {
success: false,
error: '전사 결과가 비어 있습니다. 오디오에 음성이 들어 있는지 확인해주세요.',
}
}
return {
success: true,
text: text.trim(),
segments: parseTimestampedTranscript(text),
model,
}
} catch (err) {
const message = err instanceof Error ? err.message : '알 수 없는 오류'
return { success: false, error: `전사 호출 중 오류: ${message}` }
}
}
+56 -4
View File
@@ -1,15 +1,39 @@
import { completeWithGemini, resolveGeminiModel } from './gemini' import {
import { completeWithOpenAICompatible } from './openai-compatible' DEFAULT_GEMINI_STT_MODEL,
completeWithGemini,
resolveGeminiModel,
transcribeWithGemini,
} from './gemini'
import {
DEFAULT_OPENAI_STT_MODEL,
completeWithOpenAICompatible,
transcribeWithOpenAICompatible,
} from './openai-compatible'
import type { import type {
CompletionOptions, CompletionOptions,
CompletionResult, CompletionResult,
ProviderSettings, ProviderSettings,
TranscriptionInput,
TranscriptionOptions,
TranscriptionResult,
TranscriptionSettings,
} from './types' } from './types'
export * from './types' export * from './types'
export * from './presets' export * from './presets'
export { DEFAULT_GEMINI_MODEL, resolveGeminiModel } from './gemini' export {
export { normalizeBaseUrl } from './openai-compatible' DEFAULT_GEMINI_MODEL,
DEFAULT_GEMINI_STT_MODEL,
GEMINI_INLINE_AUDIO_LIMIT,
isGeminiSupportedAudioMimeType,
parseTimestampedTranscript,
resolveGeminiModel,
} from './gemini'
export {
DEFAULT_OPENAI_STT_MODEL,
isWhisperSupportedMimeType,
normalizeBaseUrl,
} from './openai-compatible'
/** /**
* 설정된 프로바이더로 프롬프트 1회 호출. * 설정된 프로바이더로 프롬프트 1회 호출.
@@ -41,3 +65,31 @@ export function toProviderSettings(
): ProviderSettings { ): ProviderSettings {
return settings ?? { provider: 'gemini', apiKey: apiKey ?? '' } return settings ?? { provider: 'gemini', apiKey: apiKey ?? '' }
} }
/**
* 설정된 프로바이더로 오디오 1건 전사.
*
* 요약과 마찬가지로 실패를 예외로 던지지 않는다. 전사는 회의가 끝난 뒤
* 한 번뿐인 기회이므로, 호출부가 오류 문구를 그대로 사용자에게 보여주고
* 원본 오디오를 내려받도록 안내할 수 있어야 한다.
*/
export async function transcribe(
input: TranscriptionInput,
settings: TranscriptionSettings,
options: TranscriptionOptions = {},
): Promise<TranscriptionResult> {
if (settings.provider === 'openai-compatible') {
return transcribeWithOpenAICompatible(input, settings, options)
}
return transcribeWithGemini(input, settings, options)
}
/** 전사에 실제로 쓰일 모델 이름. */
export function resolveSttModel(settings: TranscriptionSettings): string {
const explicit = settings.sttModel?.trim()
if (explicit) return explicit
return settings.provider === 'openai-compatible'
? DEFAULT_OPENAI_STT_MODEL
: DEFAULT_GEMINI_STT_MODEL
}
+144
View File
@@ -2,6 +2,11 @@ import type {
CompletionOptions, CompletionOptions,
CompletionResult, CompletionResult,
ProviderSettings, ProviderSettings,
TranscriptionInput,
TranscriptionOptions,
TranscriptionResult,
TranscriptionSegment,
TranscriptionSettings,
} from './types' } from './types'
/** /**
@@ -110,3 +115,142 @@ function describeHttpError(status: number): string {
} }
return `API 호출 실패: ${status}` return `API 호출 실패: ${status}`
} }
/** Whisper 계열 기본 모델. OrcaRouter·OpenAI·로컬 whisper.cpp 모두 이 이름을 쓴다. */
export const DEFAULT_OPENAI_STT_MODEL = 'whisper-1'
/**
* Whisper가 받아주는 컨테이너.
* 우리 녹음(webm/opus)이 여기 포함되므로 별도 변환 없이 그대로 보낸다.
*/
const WHISPER_MIME_TYPES = [
'audio/webm',
'audio/mp4',
'audio/mpeg',
'audio/mpga',
'audio/m4a',
'audio/x-m4a',
'audio/wav',
'audio/x-wav',
'audio/ogg',
'audio/flac',
]
export function isWhisperSupportedMimeType(mimeType: string): boolean {
const base = mimeType.split(';')[0].trim().toLowerCase()
return WHISPER_MIME_TYPES.includes(base)
}
/**
* OpenAI `/audio/transcriptions` 호환 엔드포인트로 전사.
*
* `verbose_json`을 먼저 요청한다. 구간별 실제 타임스탬프가 같이 오기 때문이다 —
* Web Speech가 주지 못하던 진짜 오디오 타임라인이며, 화자 분리를 얹으려면
* 반드시 필요하다. 이 형식을 지원하지 않는 최신 모델(gpt-4o-transcribe 등)은
* 400을 돌려주므로 그때는 `json`으로 한 번 더 시도한다.
*/
export async function transcribeWithOpenAICompatible(
input: TranscriptionInput,
settings: TranscriptionSettings,
options: TranscriptionOptions = {},
): Promise<TranscriptionResult> {
const { fetchFn = fetch } = options
const baseUrl = normalizeBaseUrl(settings.baseUrl ?? '')
if (!baseUrl) {
return {
success: false,
error: 'API 주소(base URL)가 올바르지 않습니다. http:// 또는 https:// 로 시작해야 합니다.',
}
}
if (!isWhisperSupportedMimeType(input.mimeType)) {
return {
success: false,
error: `이 엔드포인트가 지원하지 않는 오디오 형식입니다 (${input.mimeType}).`,
}
}
const model = settings.sttModel?.trim() || DEFAULT_OPENAI_STT_MODEL
const headers: Record<string, string> = {}
const apiKey = settings.apiKey.trim()
if (apiKey.length > 0) {
headers.Authorization = `Bearer ${apiKey}`
}
// Content-Type은 지정하지 않는다. FormData가 boundary까지 붙여 설정한다.
async function send(responseFormat: 'verbose_json' | 'json') {
const form = new FormData()
form.append(
'file',
new Blob([input.bytes as BlobPart], { type: input.mimeType }),
input.fileName,
)
form.append('model', model)
form.append('response_format', responseFormat)
if (input.language) form.append('language', input.language)
if (input.vocabularyHint) form.append('prompt', input.vocabularyHint)
return fetchFn(`${baseUrl}/audio/transcriptions`, {
method: 'POST',
headers,
body: form,
})
}
try {
let response = await send('verbose_json')
// verbose_json 미지원 모델 → 타임스탬프를 포기하고 텍스트만 받는다.
if (response.status === 400) {
response = await send('json')
}
if (!response.ok) {
if (response.status === 429) {
return {
success: false,
error: '전사 API 요청 한도를 초과했습니다. 잠시 후 다시 시도해주세요.',
rateLimited: true,
}
}
return { success: false, error: describeHttpError(response.status) }
}
const data = await response.json()
const text: string = typeof data?.text === 'string' ? data.text : ''
if (text.trim().length === 0) {
return {
success: false,
error: '전사 결과가 비어 있습니다. 오디오에 음성이 들어 있는지 확인해주세요.',
}
}
return { success: true, text, segments: parseWhisperSegments(data), model }
} catch (err) {
const message = err instanceof Error ? err.message : '알 수 없는 오류'
return { success: false, error: `전사 호출 중 오류: ${message}` }
}
}
function parseWhisperSegments(data: unknown): TranscriptionSegment[] {
const raw = (data as { segments?: unknown })?.segments
if (!Array.isArray(raw)) return []
const segments: TranscriptionSegment[] = []
for (const item of raw) {
const start = Number((item as { start?: unknown })?.start)
const end = Number((item as { end?: unknown })?.end)
const text = String((item as { text?: unknown })?.text ?? '').trim()
if (!Number.isFinite(start) || !Number.isFinite(end)) continue
if (text.length === 0) continue
segments.push({ start: Math.max(0, start), end: Math.max(start, end), text })
}
return segments
}
+18 -2
View File
@@ -1,4 +1,5 @@
import { DEFAULT_GEMINI_MODEL } from './gemini' import { DEFAULT_GEMINI_MODEL, DEFAULT_GEMINI_STT_MODEL } from './gemini'
import { DEFAULT_OPENAI_STT_MODEL } from './openai-compatible'
import type { ProviderId } from './types' import type { ProviderId } from './types'
export interface ProviderPreset { export interface ProviderPreset {
@@ -8,6 +9,10 @@ export interface ProviderPreset {
/** openai-compatible 프리셋의 기본 base URL. 사용자가 수정할 수 있다. */ /** openai-compatible 프리셋의 기본 base URL. 사용자가 수정할 수 있다. */
baseUrl: string baseUrl: string
defaultModel: string defaultModel: string
/** 음성 전사(STT)에 쓸 기본 모델. 요약용 모델과 다르다. */
defaultSttModel: string
/** 이 프로바이더로 브라우저 녹음(webm)을 전사할 수 있는지. */
canTranscribeWebm: boolean
description: string description: string
apiKeyLabel: string apiKeyLabel: string
apiKeyPlaceholder: string apiKeyPlaceholder: string
@@ -25,6 +30,9 @@ export const PROVIDER_PRESETS: ProviderPreset[] = [
provider: 'gemini', provider: 'gemini',
baseUrl: '', baseUrl: '',
defaultModel: DEFAULT_GEMINI_MODEL, defaultModel: DEFAULT_GEMINI_MODEL,
defaultSttModel: DEFAULT_GEMINI_STT_MODEL,
// Gemini는 webm 오디오를 받지 않는다 — 업로드한 mp3/wav/flac만 전사 가능.
canTranscribeWebm: false,
description: 'Google에 직접 호출합니다. 무료 티어가 있어 가장 간단합니다.', description: 'Google에 직접 호출합니다. 무료 티어가 있어 가장 간단합니다.',
apiKeyLabel: 'Gemini API 키', apiKeyLabel: 'Gemini API 키',
apiKeyPlaceholder: 'AIzaSy...', apiKeyPlaceholder: 'AIzaSy...',
@@ -39,7 +47,9 @@ export const PROVIDER_PRESETS: ProviderPreset[] = [
provider: 'openai-compatible', provider: 'openai-compatible',
baseUrl: 'https://api.openai.com/v1', baseUrl: 'https://api.openai.com/v1',
defaultModel: 'gpt-4o-mini', defaultModel: 'gpt-4o-mini',
description: 'OpenAI Chat Completions API를 사용합니다.', defaultSttModel: DEFAULT_OPENAI_STT_MODEL,
canTranscribeWebm: true,
description: 'OpenAI Chat Completions + Whisper 전사를 사용합니다.',
apiKeyLabel: 'OpenAI API 키', apiKeyLabel: 'OpenAI API 키',
apiKeyPlaceholder: 'sk-...', apiKeyPlaceholder: 'sk-...',
docsUrl: 'https://platform.openai.com/api-keys', docsUrl: 'https://platform.openai.com/api-keys',
@@ -52,6 +62,8 @@ export const PROVIDER_PRESETS: ProviderPreset[] = [
provider: 'openai-compatible', provider: 'openai-compatible',
baseUrl: 'https://api.orcarouter.ai/v1', baseUrl: 'https://api.orcarouter.ai/v1',
defaultModel: 'google/gemini-3.5-flash-lite', defaultModel: 'google/gemini-3.5-flash-lite',
defaultSttModel: 'openai/whisper-1',
canTranscribeWebm: true,
description: description:
'하나의 키로 여러 제공사 모델을 사용합니다. 별도 가입과 크레딧 충전(또는 BYOK 등록)이 필요합니다.', '하나의 키로 여러 제공사 모델을 사용합니다. 별도 가입과 크레딧 충전(또는 BYOK 등록)이 필요합니다.',
apiKeyLabel: 'OrcaRouter API 키', apiKeyLabel: 'OrcaRouter API 키',
@@ -67,6 +79,8 @@ export const PROVIDER_PRESETS: ProviderPreset[] = [
provider: 'openai-compatible', provider: 'openai-compatible',
baseUrl: 'http://localhost:11434/v1', baseUrl: 'http://localhost:11434/v1',
defaultModel: 'llama3.1', defaultModel: 'llama3.1',
defaultSttModel: 'whisper-1',
canTranscribeWebm: true,
description: description:
'Ollama · LM Studio · vLLM 등 내 PC에서 도는 모델. 회의 내용이 외부로 나가지 않습니다.', 'Ollama · LM Studio · vLLM 등 내 PC에서 도는 모델. 회의 내용이 외부로 나가지 않습니다.',
apiKeyLabel: 'API 키 (보통 불필요)', apiKeyLabel: 'API 키 (보통 불필요)',
@@ -80,6 +94,8 @@ export const PROVIDER_PRESETS: ProviderPreset[] = [
provider: 'openai-compatible', provider: 'openai-compatible',
baseUrl: '', baseUrl: '',
defaultModel: '', defaultModel: '',
defaultSttModel: DEFAULT_OPENAI_STT_MODEL,
canTranscribeWebm: true,
description: 'OpenAI 호환 엔드포인트라면 무엇이든 연결할 수 있습니다.', description: 'OpenAI 호환 엔드포인트라면 무엇이든 연결할 수 있습니다.',
apiKeyLabel: 'API 키', apiKeyLabel: 'API 키',
apiKeyPlaceholder: 'sk-...', apiKeyPlaceholder: 'sk-...',
+50
View File
@@ -30,3 +30,53 @@ export type CompletionResult =
export interface CompletionOptions { export interface CompletionOptions {
fetchFn?: typeof fetch fetchFn?: typeof fetch
} }
/* ------------------------------------------------------------------------- *
* 음성 전사 (STT)
* ------------------------------------------------------------------------- */
/**
* 전사할 오디오.
*
* 파일 전체를 메모리에 올린다. 회의 하나가 상한(수십 MB) 안에 들어오도록
* 녹음 비트레이트를 낮춰 두었으므로 스트리밍까지 갈 필요는 없다.
*/
export interface TranscriptionInput {
bytes: Uint8Array
mimeType: string
fileName: string
/** BCP-47 앞부분. 예: 'ko'. 지정하면 인식 정확도가 눈에 띄게 오른다. */
language?: string
/**
* 어휘 힌트. 참석자 이름·제품명·사내 용어를 넣으면 고유명사 오인식이 준다.
* Whisper는 이 문자열을 직전 문맥처럼 취급한다(약 224토큰까지).
*/
vocabularyHint?: string
}
/** 전사 구간. Whisper `verbose_json`이 주는 실제 오디오 타임라인 기준. */
export interface TranscriptionSegment {
/** 초 단위, 오디오 시작 기준. */
start: number
end: number
text: string
}
export type TranscriptionResult =
| {
success: true
text: string
/** 프로바이더가 타임스탬프를 주지 않으면 비어 있다. */
segments: TranscriptionSegment[]
model: string
}
| { success: false; error: string; rateLimited?: boolean }
export interface TranscriptionOptions {
fetchFn?: typeof fetch
}
/** 전사에 쓸 모델은 대화용 모델과 다르므로 따로 받는다. */
export interface TranscriptionSettings extends ProviderSettings {
sttModel?: string
}
+195
View File
@@ -0,0 +1,195 @@
/**
* 녹음 조각을 디스크에 이어 붙이는 서버 저장소.
*
* 메모리에 모아 뒀다가 종료 시 한 번에 쓰지 않는다. 그러면 탭이나 서버가
* 죽는 순간 회의 전체가 사라진다. 조각이 도착할 때마다 곧바로 append 하므로
* 어느 시점에 중단되든 그때까지의 오디오는 파일로 남아 있다.
*
* MediaRecorder가 timeslice 모드에서 내보내는 조각은 첫 조각에 컨테이너
* 헤더가 들어 있고 이후에는 클러스터만 이어진다. 받은 순서대로 이어 붙이면
* 그대로 재생·전사 가능한 파일이 된다. 단 헤더의 duration 필드는 비어 있어
* 플레이어에 따라 탐색(seek)이 부정확할 수 있다 — 재전사에는 영향이 없다.
*/
import { randomBytes } from 'crypto'
import { createReadStream } from 'fs'
import type { Readable } from 'stream'
import { appendFile, mkdir, readFile, stat, writeFile } from 'fs/promises'
import path from 'path'
import {
MAX_RECORDING_BYTES,
extensionForMimeType,
isValidRecordingId,
} from './recording'
/** 별도 볼륨에 두고 싶으면 `RECORDINGS_DIR`로 덮어쓴다. */
export const RECORDINGS_DIR =
process.env.RECORDINGS_DIR ?? path.join(process.cwd(), 'uploads', 'recordings')
export interface RecordingMeta {
id: string
mimeType: string
/** `uploads/recordings/` 기준 상대 파일명. */
fileName: string
startedAt: string
finalizedAt: string | null
durationMs: number | null
}
export interface RecordingStatus extends RecordingMeta {
bytes: number
}
/**
* id별 직렬화 큐.
*
* 조각의 순서가 곧 파일의 순서다. 두 요청이 겹쳐 들어오면 컨테이너가
* 깨지므로 같은 녹음에 대한 쓰기는 한 줄로 세운다.
*/
const queues = new Map<string, Promise<unknown>>()
function enqueue<T>(id: string, task: () => Promise<T>): Promise<T> {
const previous = queues.get(id) ?? Promise.resolve()
const next = previous.then(task, task)
// 앞 작업이 실패해도 뒤 작업은 돌아야 하므로, 큐에는 절대 거부되지 않는
// 프로미스를 넣는다. 실패는 호출자가 받는 `next`로만 전달된다.
const settled = next.then(
() => undefined,
() => undefined,
)
// 큐가 무한정 자라지 않도록, 마지막 작업이 끝나면 항목을 지운다.
queues.set(id, settled)
settled.then(() => {
if (queues.get(id) === settled) queues.delete(id)
})
return next
}
function metaPath(id: string): string {
return path.join(RECORDINGS_DIR, `${id}.json`)
}
function audioPath(meta: RecordingMeta): string {
return path.join(RECORDINGS_DIR, meta.fileName)
}
async function fileSize(filePath: string): Promise<number> {
try {
return (await stat(filePath)).size
} catch {
return 0
}
}
/** 새 녹음 세션을 만든다. 오디오 파일은 첫 조각이 도착할 때 생긴다. */
export async function createRecording(
mimeType: string,
): Promise<RecordingMeta> {
const id = randomBytes(16).toString('hex')
const meta: RecordingMeta = {
id,
mimeType,
fileName: `${id}.${extensionForMimeType(mimeType)}`,
startedAt: new Date().toISOString(),
finalizedAt: null,
durationMs: null,
}
await mkdir(RECORDINGS_DIR, { recursive: true })
await writeFile(metaPath(id), JSON.stringify(meta, null, 2), 'utf-8')
return meta
}
export async function getRecording(id: string): Promise<RecordingMeta | null> {
if (!isValidRecordingId(id)) return null
try {
const raw = await readFile(metaPath(id), 'utf-8')
return JSON.parse(raw) as RecordingMeta
} catch {
return null
}
}
export async function getRecordingStatus(
id: string,
): Promise<RecordingStatus | null> {
const meta = await getRecording(id)
if (!meta) return null
return { ...meta, bytes: await fileSize(audioPath(meta)) }
}
export type AppendResult =
| { ok: true; bytes: number }
| { ok: false; error: string; status: number }
/** 조각 하나를 파일 끝에 이어 붙이고 누적 크기를 돌려준다. */
export async function appendChunk(
id: string,
chunk: Buffer,
): Promise<AppendResult> {
const meta = await getRecording(id)
if (!meta) {
return { ok: false, error: '녹음 세션을 찾을 수 없습니다.', status: 404 }
}
return enqueue(id, async () => {
const filePath = audioPath(meta)
const current = await fileSize(filePath)
if (current + chunk.byteLength > MAX_RECORDING_BYTES) {
return {
ok: false as const,
error: `녹음이 상한(${Math.round(
MAX_RECORDING_BYTES / 1024 / 1024,
)}MB)을 넘었습니다.`,
status: 413,
}
}
await appendFile(filePath, chunk)
return { ok: true as const, bytes: current + chunk.byteLength }
})
}
/** 녹음을 닫는다. 이후 조각은 더 오지 않는다고 보고 길이를 확정한다. */
export async function finalizeRecording(
id: string,
durationMs: number | null,
): Promise<RecordingStatus | null> {
const meta = await getRecording(id)
if (!meta) return null
return enqueue(id, async () => {
const updated: RecordingMeta = {
...meta,
finalizedAt: new Date().toISOString(),
durationMs:
typeof durationMs === 'number' && Number.isFinite(durationMs)
? Math.max(0, Math.round(durationMs))
: null,
}
await writeFile(metaPath(id), JSON.stringify(updated, null, 2), 'utf-8')
return { ...updated, bytes: await fileSize(audioPath(updated)) }
})
}
/** 다운로드용 읽기 스트림. 파일이 없으면 null. */
export async function openRecording(
id: string,
): Promise<{ meta: RecordingMeta; bytes: number; stream: Readable } | null> {
const meta = await getRecording(id)
if (!meta) return null
const filePath = audioPath(meta)
const bytes = await fileSize(filePath)
if (bytes === 0) return null
return { meta, bytes, stream: createReadStream(filePath) }
}
+148
View File
@@ -0,0 +1,148 @@
/**
* 회의 오디오 녹음 — 브라우저·서버가 공유하는 상수와 순수 함수.
*
* 녹음의 목적은 재생이 아니라 **재전사**다. Web Speech가 놓친 발화를 나중에
* 서버 STT로 되살리려면 원본 오디오가 남아 있어야 한다. 그래서 전사와
* 무관하게, 전사가 실패하더라도 오디오만은 반드시 파일로 남긴다.
*/
/** MediaRecorder에 우선순위대로 시도할 컨테이너/코덱. */
export const PREFERRED_MIME_TYPES = [
'audio/webm;codecs=opus',
'audio/webm',
'audio/ogg;codecs=opus',
'audio/mp4',
] as const
/**
* 대면 회의 기준 캡처 제약.
*
* 브라우저 기본값은 세 가지가 모두 켜져 있고 전화 통화용으로 튜닝돼 있다.
* 노이즈 억제는 멀리 앉은 화자의 목소리를 노이즈로 오판해 지워버릴 수 있고,
* 에코 제거는 스피커 출력이 없는 대면 회의에서는 얻을 게 없다. 둘 다 끈다.
* 반면 AGC는 조용한 화자의 레벨을 끌어올려 주므로 남긴다.
*
* 원격 회의(스피커 출력이 마이크로 되먹임되는 경우)에는 echoCancellation을
* 다시 켜야 한다. 그 경로는 dual-stream 캡처와 함께 다룬다.
*/
export const RECORDING_AUDIO_CONSTRAINTS: MediaTrackConstraints = {
channelCount: 1,
echoCancellation: false,
noiseSuppression: false,
autoGainControl: true,
}
/**
* 서버로 조각을 올리는 간격.
*
* 짧을수록 탭이 죽었을 때 잃는 양이 적고, 길수록 요청 수가 준다. 15초면
* 최악의 경우에도 15초치만 잃는다.
*/
export const CHUNK_INTERVAL_MS = 15_000
/**
* 녹음 비트레이트.
*
* 이 오디오는 감상용이 아니라 STT 입력이다. Opus는 음성 대역에서 32kbps만
* 되어도 인식 정확도에 영향이 없고, 대신 파일이 작아야 전사 API에 통째로
* 넣을 수 있다. 128kbps로 두면 46분 회의가 44MB가 되어 Whisper 상한(25MB)도,
* Gemini inline 상한도 넘긴다.
*
* 32kbps 기준 대략: 46분 → 11MB, 1시간 → 14MB, 1시간 40분 → 24MB
*/
export const AUDIO_BITS_PER_SECOND = 32_000
/** 회의 하나의 상한. 128kbps 기준 약 8.6시간. */
export const MAX_RECORDING_BYTES = 500 * 1024 * 1024
/** 조각 하나의 상한. 15초 × 128kbps면 240KB 남짓이라 넉넉하다. */
export const MAX_CHUNK_BYTES = 8 * 1024 * 1024
/** 브라우저가 지원하는 첫 번째 후보를 고른다. 없으면 null. */
export function pickRecorderMimeType(
isTypeSupported: (type: string) => boolean,
): string | null {
for (const type of PREFERRED_MIME_TYPES) {
if (isTypeSupported(type)) return type
}
return null
}
/** `audio/webm;codecs=opus` → `webm` */
export function extensionForMimeType(mimeType: string): string {
const base = mimeType.split(';')[0].trim().toLowerCase()
switch (base) {
case 'audio/webm':
return 'webm'
case 'audio/ogg':
return 'ogg'
case 'audio/mp4':
case 'audio/x-m4a':
return 'm4a'
case 'audio/mpeg':
return 'mp3'
case 'audio/wav':
case 'audio/x-wav':
return 'wav'
case 'audio/flac':
return 'flac'
default:
return 'bin'
}
}
/**
* 녹음 세션 식별자 검증.
*
* 이 값이 그대로 파일 경로가 되므로 `..`이나 구분자가 섞이면 안 된다.
* 경로 조립 전에 반드시 통과시킨다.
*/
const RECORDING_ID_PATTERN = /^[0-9a-f]{32}$/
export function isValidRecordingId(id: unknown): id is string {
return typeof id === 'string' && RECORDING_ID_PATTERN.test(id)
}
/** 사용자가 내려받을 때 보게 될 파일 이름. */
export function recordingDownloadName(
title: string,
startedAt: Date,
mimeType: string,
): string {
const stamp = [
startedAt.getFullYear(),
String(startedAt.getMonth() + 1).padStart(2, '0'),
String(startedAt.getDate()).padStart(2, '0'),
'-',
String(startedAt.getHours()).padStart(2, '0'),
String(startedAt.getMinutes()).padStart(2, '0'),
].join('')
const safeTitle = title
.trim()
.replace(/[\\/:*?"<>|]/g, '')
.replace(/\s+/g, '_')
.slice(0, 60)
const stem = safeTitle.length > 0 ? `${stamp}_${safeTitle}` : stamp
return `${stem}.${extensionForMimeType(mimeType)}`
}
export function formatBytes(bytes: number): string {
if (!Number.isFinite(bytes) || bytes < 0) return '0B'
if (bytes < 1024) return `${bytes}B`
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)}KB`
return `${(bytes / 1024 / 1024).toFixed(1)}MB`
}
export function formatDuration(ms: number): string {
const total = Math.max(0, Math.floor(ms / 1000))
const h = Math.floor(total / 3600)
const m = Math.floor((total % 3600) / 60)
const s = total % 60
const mm = String(m).padStart(2, '0')
const ss = String(s).padStart(2, '0')
return h > 0 ? `${h}:${mm}:${ss}` : `${mm}:${ss}`
}
+29
View File
@@ -50,3 +50,32 @@ export function mergeAdjacentChunks(
return result return result
} }
/**
* 서버 STT가 준 구간을 전사문으로 옮긴다.
*
* 여기 붙는 타임스탬프는 실제 오디오 타임라인이다. Web Speech 경로가 쓰던
* `결과 이벤트 시각 − 2초` 추정값과 달리 화자 분리·구간 재생에 그대로 쓸 수 있다.
*/
export function formatTranscriptionSegments(
segments: readonly { start: number; text: string }[],
): string {
return segments
.filter((segment) => segment.text.trim().length > 0)
.map((segment) => `${formatTimestamp(segment.start)} ${segment.text.trim()}`)
.join('\n')
}
/** STT 구간을 기존 청크 구조로 변환한다 (화자 배정·병합 로직 재사용용). */
export function segmentsToChunks(
segments: readonly { start: number; end: number; text: string }[],
): TranscriptChunk[] {
return segments
.filter((segment) => segment.text.trim().length > 0)
.map((segment) => ({
text: segment.text.trim(),
startTime: Math.max(0, segment.start),
endTime: Math.max(segment.start, segment.end),
isFinal: true,
}))
}