Files
stt/README.md
dosangyoon 2e503d1a56 Web STT: speaker diarization via pyannote; whisper_stt snapshot validation
- Add app/diarize.py: merge faster-whisper segments with pyannote (A/B/C)
- Wire /api/jobs and /api/transcribe; job API returns speaker_diarization, diarize_skip_reason
- UI: meta line shows diarization applied/skipped; hint for models path
- requirements.txt: pyannote.audio; README APP_DIARIZE / APP_PYANNOTE_MODEL_DIR
- whisper_stt.py: validate config.yaml before loading pipeline
- requirements-whisper-stt.txt: minor doc updates if any

Made-with: Cursor
2026-03-23 13:09:31 +09:00

176 lines
7.4 KiB
Markdown

# Web STT (mp3/m4a 업로드 → 텍스트 변환)
## 구성
- **백엔드**: FastAPI (업로드/검증/STT 수행)
- **STT 엔진**: `faster-whisper` (Whisper 모델)
- **프론트**: 단일 HTML (파일 선택 → 전사 → 결과 표시/다운로드)
- **선택 CLI**: `whisper_stt.py` — OpenAI Whisper 기반 로컬 전사(**기본: 화자 구분**, 로컬 `./models/pyannote-diarization-3.1`)
## 동작 개요 (pseudocode)
```text
UI:
onSelect(file):
validate client-side (extension)
enable "전사" 버튼
onClickTranscribe():
POST /api/transcribe (multipart/form-data, file, options)
show progress (업로드 중 / 처리 중)
render returned text + segments
allow download as .txt
API:
POST /api/transcribe:
if no file -> 400
validate mime/ext in allowed audio types -> 415 if not
save to temp file
run STT(model, language, vad_filter, beam_size, ...)
return { text, segments[], detected_language, duration_sec }
cleanup temp file
```
---
## 사전 요구 사항
### Ubuntu (22.04 / 24.04 등)
오디오 디코딩과 일부 Python 패키지 빌드에 쓰입니다.
```bash
sudo apt update
sudo apt install -y ffmpeg build-essential
```
- **`ffmpeg`**: `faster-whisper`·Whisper가 mp3/m4a 등을 읽을 때 필요합니다. (`apt`로 설치하는 편이 가장 단순합니다.)
- **`build-essential`**: 소스/휠 빌드가 필요한 의존성이 있을 때 도움이 됩니다.
선택(GPU로 faster-whisper 등을 쓸 때):
- NVIDIA 드라이버 및 CUDA는 [NVIDIA 문서](https://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html)에 맞게 설치합니다.
- 이 저장소 기본값은 **CPU**입니다. GPU 사용 시 `APP_WHISPER_DEVICE`·`APP_WHISPER_COMPUTE_TYPE` 등을 환경에 맞게 조정하세요.
### macOS
```bash
brew install ffmpeg
```
`pip``imageio-ffmpeg`만으로도 CLI 쪽 보조는 가능하지만, 서버·도구 공통으로 **시스템 `ffmpeg` 설치를 권장**합니다.
---
## Python 환경 (Conda 권장)
이 프로젝트는 **conda 환경 `stt`** (Python 3.11) 사용을 권장합니다. (Cursor/VS Code는 `.vscode/settings.json`에 인터프리터 경로가 있습니다.)
### 1) `stt` 생성 및 웹 서버 의존성
```bash
conda create -n stt python=3.11 -y
conda activate stt
pip install -r requirements.txt
```
### 2) (선택) 로컬 전사 CLI — `whisper_stt.py`
```bash
conda activate stt
pip install -r requirements-whisper-stt.txt
```
**Ubuntu에서 `pip install -r requirements-whisper-stt.txt` 가 torch 관련 `OSError` / `ATen.h` 없음 등으로 실패할 때**
기존 `torch` 설치가 깨졌거나 pip가 교체 도중 멈춘 경우가 많습니다.
```bash
conda activate stt # 또는 사용 중인 env (예: ncue)
pip uninstall -y torch torchvision torchaudio functorch
pip uninstall -y torch torchvision torchaudio functorch # Skipping만 나올 때까지 반복
pip cache purge
pip install torch torchaudio --index-url https://download.pytorch.org/whl/cpu
pip install -r requirements-whisper-stt.txt
```
**같은 오류(`ATen.h` 없음 등)가 `torch` 재설치 시에도 반복되면**
`pip uninstall`만으로는 깨진 `site-packages/torch` 폴더가 남는 경우가 있습니다. 아래로 **잔여 디렉터리를 직접 삭제**한 뒤 다시 설치하세요. (`python3.11``python -c "import sys; print(sys.version_info[:2])"`로 맞춤.)
```bash
conda activate ncue # 문제 나는 env
pip uninstall -y torch torchvision torchaudio functorch 2>/dev/null || true
rm -rf "$CONDA_PREFIX/lib/python3.11/site-packages/torch" \
"$CONDA_PREFIX/lib/python3.11/site-packages/torch-"*.dist-info \
"$CONDA_PREFIX/lib/python3.11/site-packages/torchaudio" \
"$CONDA_PREFIX/lib/python3.11/site-packages/torchaudio-"*.dist-info \
"$CONDA_PREFIX/lib/python3.11/site-packages/torchgen" \
"$CONDA_PREFIX/lib/python3.11/site-packages/functorch"
pip cache purge
pip install torch torchaudio --index-url https://download.pytorch.org/whl/cpu
pip install -r requirements-whisper-stt.txt
```
그래도 실패하면 **새 conda 환경**(`conda create -n stt-whisper python=3.11 -y`)을 만들고, 위 README의 **conda로 PyTorch 먼저** 절차만 그 env에서 진행하는 것이 가장 확실합니다.
애초에 꼬이지 않게 하려면 **PyTorch를 conda로 먼저** 깐 뒤 위 requirements만 pip로 설치하는 것을 권장합니다.
```bash
conda activate stt
conda install pytorch torchaudio cpuonly -c pytorch -y
pip install -r requirements-whisper-stt.txt
```
- **Hugging Face `hf` CLI**: `pip install huggingface_hub``hf auth login`, `hf download …` (화자 구분용 pyannote 모델 등).
- $ hf auth login
- $ hf download pyannote/speaker-diarization-3.1 --local-dir ./models/pyannote-diarization-3.1
- **화자 구분(기본 켜짐)**: `./models/pyannote-diarization-3.1` 에 pyannote 스냅샷이 있어야 합니다. 없으면 스크립트가 `hf download` 안내 후 종료합니다. 모델 받기: [pyannote/speaker-diarization-3.1](https://huggingface.co/pyannote/speaker-diarization-3.1) 약관 동의 후 `hf auth login`, `hf download … --local-dir ./models/pyannote-diarization-3.1`. 다른 경로는 `--diarize-model-dir` 또는 `WHISPER_DIARIZE_MODEL_DIR` 로 지정.
- **화자 구분 끄기**: `python whisper_stt.py 입력.m4a 출력.txt --no-diarize` (Whisper 통문만 저장)
```bash
python whisper_stt.py 입력.m4a 출력.txt
python whisper_stt.py 입력.m4a 출력.txt --no-diarize
python whisper_stt.py 입력.m4a 출력.txt --diarize-model-dir /다른/경로/pyannote-diarization-3.1
```
### 대안: `environment.yml` (환경 이름 `ncue`, conda에 `ffmpeg` 포함)
```bash
conda env create -f environment.yml
conda activate ncue
```
`pip` 의존성은 `requirements.txt`를 통해 설치됩니다. 팀에서 이미 `ncue`를 쓰는 경우에만 사용해도 됩니다.
---
## 서버 실행
```bash
conda activate stt # 또는 ncue
uvicorn app.main:app --reload --host 127.0.0.1 --port 8025
```
브라우저에서 `http://127.0.0.1:8025` 접속.
업로드 전사가 끝나면 **`app/diarize.py`** 가 `whisper_stt.py`와 같은 방식으로 pyannote 화자 구분을 시도합니다. 저장소 루트의 **`models/pyannote-diarization-3.1`** (`config.yaml` 포함)이 있어야 하며, `requirements.txt``pyannote.audio`가 포함되어 있습니다. 스냅샷이 없거나 오류면 전사만 반환하고, 응답에 `speaker_diarization: false``diarize_skip_reason` 이 붙을 수 있습니다.
---
## 옵션·환경 변수
- **모델**: 기본 `small` (정확도/속도 균형). `APP_WHISPER_MODEL=base|small|medium|large-v3` 등으로 변경 가능.
- **디바이스**: 기본 CPU. Apple Silicon에서 Metal은 `faster-whisper` 단독으로는 제한이 있어 CPU 기본값을 권장.
- **웹 화자 구분**: `APP_DIARIZE=1`(기본) — `0`/`false`/`off` 이면 pyannote 단계 생략. `APP_PYANNOTE_MODEL_DIR` 로 스냅샷 경로 지정(없으면 프로젝트 `models/pyannote-diarization-3.1`).
- **기타**: `APP_WHISPER_DEVICE`, `APP_WHISPER_COMPUTE_TYPE`, 업로드 크기 등은 `app/main.py``.env` 예시를 참고.
---
## 플랫폼 요약
| 항목 | Ubuntu | macOS |
|------|--------|--------|
| `ffmpeg` | `sudo apt install ffmpeg` | `brew install ffmpeg` |
| Python | Conda `stt` 권장 | 동일 |
| 웹 STT | `pip install -r requirements.txt` | 동일 |
| `whisper_stt.py` | `pip install -r requirements-whisper-stt.txt` | 동일 |