Files
luke_scribe/notebooks/luke-scribe-colab.ipynb
T
lukehemmin 457c67df2c fix: colab bench manifest — entities must be dicts with char spans
Bench clip failed in Colab because entity_retention calls ent.get() but
the manifest used plain strings -> AttributeError -> clip counted as
failure (failure_rate 1.0). Notebook now builds entities as
{canonical, surface, start_char, end_char} from the reference text and
writes a reference file for meaningful metrics.
2026-08-12 17:40:08 +09:00

19 KiB

luke_scribe — Colab 실전 테스트 노트북

내부용 로컬 STT 전사 API (faster-whisper, hardware-adaptive, privacy-first)

이 노트북은 CPU-only 개발 환경에서 mock으로만 검증했던 것을, Colab Pro(GPU + 터미널)에서 실전 검증하기 위한 것입니다.

검증 대상

  • luke-scribe detect → T4 GPU 실제 감지 (능력 등급 T1~T3, 정밀도, 워커수)
  • faster-whisper 모델 다운로드 + 실제 한국어 전사 (CPU-only 환경에선 불가)
  • glossary/hotword 후처리 (KO+EN 기술용어 보존)
  • REST API 흐름 (업로드 → poll → 결과)
  • turbo vs large-v3 벤치마크

준비

  1. 런타임 → 런타임 유형 변경 → T4 GPU 선택
  2. (Colab Pro) 터미널을 사용해도 동일한 명령을 실행할 수 있습니다
  3. 저장소가 private이면 아래 셀에 Gitea 토큰 입력 (Settings → Applications → Generate New Token)

In [ ]:
# 0) 런타임 확인 — T4 GPU가 활성 상태여야 합니다
!nvidia-smi
import sys
print('Python', sys.version.split()[0])

1) 저장소 클론

feat/full-platform 브랜치를 클론합니다. 저장소가 private이면 아래 셀의 GITEA_TOKEN에 토큰을 입력하세요.

In [ ]:
# 1) 클론 또는 업데이트 (private 저장소면 GITEA_TOKEN 입력)
GITEA_TOKEN = ''  # ← 필요 시 입력: https://git.lukehemmin.com/user/settings/applications

if GITEA_TOKEN:
    REPO = f'https://{GITEA_TOKEN}@git.lukehemmin.com/lukehemmin/luke_scribe.git'
else:
    REPO = 'https://git.lukehemmin.com/lukehemmin/luke_scribe.git'

import os, subprocess

if os.path.isdir('/content/luke_scribe/.git'):
    # 이미 클론된 레포 → 최신 브랜치로 갱신 (pull)
    print('기존 레포 감지 → pull로 갱신')
    subprocess.run(['git', 'fetch', 'origin'], cwd='/content/luke_scribe', check=True)
    subprocess.run(['git', 'checkout', 'feat/full-platform'], cwd='/content/luke_scribe', check=True)
    subprocess.run(['git', 'pull', '--ff-only', 'origin', 'feat/full-platform'], cwd='/content/luke_scribe', check=True)
else:
    # 최초 실행 → 클론
    subprocess.run(['git', 'clone', '-b', 'feat/full-platform', REPO], cwd='/content', check=True)

os.chdir('/content/luke_scribe')
print('작업 디렉터리 →', os.getcwd())
!git log --oneline -1

2) 시스템 의존성 + 설치

ffmpeg(오디오 정규화) 설치 후 venv에 luke-scribe를 설치합니다.

In [ ]:
# 2) 시스템 패키지 (ffmpeg — ffprobe/정규화에 필수)
!apt-get update -qq && apt-get install -y -qq ffmpeg >/dev/null
!ffmpeg -version 2>&1 | head -1
!ffprobe -version 2>&1 | head -1
In [ ]:
# 3) 설치 — Colab은 시스템 pip가 표준 (venv는 Colab에서 ensurepip 오류로 실패할 수 있음)
!pip install -q --upgrade pip
!pip install -q -e '.[engine,api]'
!pip install -q edge-tts  # 샘플 음성 생성용

# CUDA 13(Colab)에서는 CTranslate2 wheel(CUDA 12용)이 런타임 라이브러리를 못 찾음.
# CUDA 12 런타임(cuBLAS/cuDNN)을 pip로 설치하고, 실제 .so 위치를 find로 찾아
# LD_LIBRARY_PATH에 추가한다 (nvidia-*-cu12는 namespace package라 __file__이 없음).
!pip install -q nvidia-cublas-cu12 nvidia-cudnn-cu12
import os, site, subprocess
lib_dirs = set()
for lib in ('libcublas.so', 'libcudnn.so'):
    out = subprocess.run(
        ['bash', '-c', f'find {site.getsitepackages()[0]} -name "{lib}*" 2>/dev/null | head -3'],
        capture_output=True, text=True,
    ).stdout
    for line in out.splitlines():
        d = os.path.dirname(line)
        if d:
            lib_dirs.add(d)
os.environ['LD_LIBRARY_PATH'] = ':'.join(lib_dirs) + ':' + os.environ.get('LD_LIBRARY_PATH', '')
print('LD_LIBRARY_PATH:', os.environ['LD_LIBRARY_PATH'])
print('설치 완료')
!which luke-scribe && luke-scribe --help 2>&1 | head -8
In [ ]:
# 4) CTranslate2 GPU 검증 — unsupported device cuda:0 해결 여부 확인
import ctranslate2
print('ctranslate2', ctranslate2.__version__)
print('CUDA device count:', ctranslate2.get_cuda_device_count())
if ctranslate2.get_cuda_device_count() > 0:
    print('GPU 사용 가능 ✅ — 이후 전사는 GPU로 실행됩니다')
else:
    print('GPU 사용 불가 — CPU 폴백 필요 (--device cpu --compute-type int8)')

3) 하드웨어 감지 — GPU 실제 확인

CPU-only 환경에서는 T0 / cpu / int8이 나왔지만, Colab GPU(A100 80GB / T4 16GB)에서는 GPU가 감지되어야 합니다.

In [ ]:
# 4) detect — GPU 감지 / 능력 등급 / 정밀도 / 워커수
!luke-scribe detect

4) 단위/통합 테스트 (127개)

mock 기반 테스트가 GPU 환경에서도 전부 통과하는지 확인합니다.

In [ ]:
# 5) 테스트 스위트
!python -m pytest tests/ -q 2>&1 | tail -5

5) 실전 전사 (GPU)

5-1) 샘플 오디오 생성

edge-tts(MS TTS)로 한국어 + 영문 기술용어가 섞인 샘플을 생성합니다. 이 텍스트에는 vLLM, Kubernetes, GPU 같은 용어가 포함되어 glossary/hotword 검증에 적합합니다.

In [ ]:
# 6) 샘플 오디오 생성 (한국어 + 기술용어, 무료 TTS)
!mkdir -p samples
!edge-tts --voice ko-KR-SunHiNeural --text '오늘은 vLLM 서버를 Kubernetes 클러스터에 배포하는 방법을 설명합니다. GPU 가속 추론으로 대기 시간을 줄일 수 있습니다.' --write-media samples/colab-ko-en.mp3
!ffprobe -v error -show_entries format=duration -of json samples/colab-ko-en.mp3
In [ ]:
# 7) 실전 전사 — GPU 자동 감지 + 모델 다운로드 (large-v3-turbo)
# 첫 실행 시 Hugging Face에서 모델을 다운로드합니다 (turbo ≈ 1.6GB, 1~2분)
# v0.1: 'cuda:N' device를 분리해 CTranslate2 계약에 맞게 전달하도록 수정됨
# (기존: unsupported device cuda:0). 그래도 실패하면 CPU 폴백 안내가 출력됩니다.
import subprocess, json
r = subprocess.run(
    ['luke-scribe', 'transcribe', 'samples/colab-ko-en.mp3', '--language', 'ko', '--device', 'auto'],
    capture_output=True, text=True,
)
print(r.stdout[-2500:] if r.stdout else '')
print(r.stderr[-800:] if r.stderr else '')

5-2) 후처리 검증

glossary(오인식 용어 복원) + hotword(용어 사전 주입) 동작을 확인합니다. --hotword vLLM Kubernetes를 주면 initial_prompt에 용어가 주입되어 보존률이 올라갑니다.

In [ ]:
# 8) hotword 포함 전사 (용어 보존 강화)
!luke-scribe transcribe samples/colab-ko-en.mp3 --language ko --device auto --hotword vLLM --hotword Kubernetes

6) REST API 스모크

서버를 백그라운드로 띄우고 업로드 → poll → 결과(SRT) 흐름을 검증합니다.

In [ ]:
# 9) API 키 생성 — raw 키는 1회만 출력되므로 여기서 캡처한다
import subprocess, json, os
r = subprocess.run(
    ['luke-scribe', 'key', '--create', '--scopes', 'transcribe,admin', '--file', '/content/api_keys.json'],
    capture_output=True, text=True,
)
created = json.loads(r.stdout)
RAW_KEY = created['key']  # 이후 셀에서 사용
print('key_id:', created['key_id'], '| scopes:', created['scopes'])
print('raw 키 캡처 완료 (표시 안 함)')
In [ ]:
# 10) 서버 기동 (in-proc 큐, 백그라운드 — nohup)
# 이전 실행에서 남은 서버가 포트 8000을 점유하면 새 키를 모른 채 401이 난다.
# → 먼저 기존 서버를 모두 종료하고, 키 파일 경로를 명시해 재시작한다.
import subprocess, os, time, urllib.request, urllib.error

assert 'RAW_KEY' in globals(), '셀 9(키 생성)를 먼저 실행하세요'

subprocess.run(['pkill', '-f', 'luke-scribe serve'], capture_output=True)
time.sleep(2)

# 서버가 읽을 키 파일/큐를 명시 (cwd 의존 제거)
os.environ['LUKESCRIBE_API_KEY_FILE'] = '/content/api_keys.json'
os.environ['LUKESCRIBE_QUEUE_BACKEND'] = 'inproc'
# in-proc 서버가 자체 워커 스레드로 큐를 소비 (업로드 → 완료까지 API 단독 처리)
os.environ['LUKESCRIBE_AUTO_WORKER'] = 'true'

!mkdir -p /content/logs
!nohup luke-scribe serve --port 8000 > /content/logs/server.log 2>&1 &

ok = False
for _ in range(40):
    try:
        urllib.request.urlopen('http://localhost:8000/health', timeout=1)
        ok = True
        break
    except Exception:
        time.sleep(1)
if not ok:
    print('서버 기동 실패 — 로그:')
    print(open('/content/logs/server.log').read()[-1500:])
    raise SystemExit('서버 기동 실패')

# 키 인증 검증 — RAW_KEY로 /v1/jobs 호출 → 200이어야 함 (401이면 종료)
req = urllib.request.Request('http://localhost:8000/v1/jobs', headers={'X-API-Key': RAW_KEY})
try:
    resp = urllib.request.urlopen(req, timeout=5)
    print('서버 기동 OK + 키 인증 OK (HTTP', resp.status, ')')
except urllib.error.HTTPError as e:
    print('키 인증 실패 (HTTP', e.code, ') — 서버 로그:')
    print(open('/content/logs/server.log').read()[-1500:])
    raise SystemExit('키 인증 실패 — RAW_KEY 캡처/키 파일 확인')
In [ ]:
# 11) 업로드 → poll → 결과 (RAW_KEY는 셀 9에서 캡처된 값)
import json, time, urllib.request, urllib.error, subprocess

assert 'RAW_KEY' in globals(), '셀 9(키 생성)를 먼저 실행하세요'

# multipart 업로드 (curl 사용 — 간단)
r = subprocess.run(
    ['curl', '-s', '-X', 'POST', 'http://localhost:8000/v1/jobs',
     '-H', f'X-API-Key: {RAW_KEY}',
     '-F', 'file=@samples/colab-ko-en.mp3',
     '-F', 'options={"language":"ko","formats":["json","srt"]}'],
    capture_output=True, text=True,
)
job = json.loads(r.stdout)
print('생성:', job)
job_id = job.get('job_id')

# 완료까지 poll (auto-worker가 서버 프로세스에서 큐를 소비 — 첫 실행은
# 모델 다운로드 ~1.6GB 포함이라 최대 4분까지 대기)
if job_id:
    print('job_id =', job_id)
    for _ in range(120):
        st = json.loads(urllib.request.urlopen(
            urllib.request.Request(f'http://localhost:8000/v1/jobs/{job_id}',
                                   headers={'X-API-Key': RAW_KEY})
        ).read())
        if st['status'] in ('completed', 'failed', 'cancelled'):
            print('최종 상태:', st['status'])
            break
        time.sleep(2)
    else:
        print('폴링 60초 초과 — 서버 로그 확인: /content/logs/server.log')
else:
    print('업로드 실패 — 서버 로그 확인: /content/logs/server.log')

참고 — 서버에서 실제 전사까지 실행하려면

in-proc 브로커는 큐만 받고 워커가 별도로 소비해야 합니다. 워커 스레드를 띄우거나 간단하게는 배치 파이프라인을 직접 호출하는 CLI가 더 간단합니다. API 전체 흐름(워커 포함)은 다음 셀에서 python으로 브로커 + 워커를 함께 돌려 확인합니다.

In [ ]:
# 12) 브로커 + 워커 포함 전체 흐름 (in-proc)
# 서버의 in-proc 브로커에 enqueue된 job을 같은 프로세스의 워커가 소비하는 구조는
# 프로세스 분리 필요 → 여기서는 클라이언트에서 직접 Worker.drain() 호출로 검증
from luke_scribe.config import Settings
from luke_scribe.jobqueue.broker import InProcBroker
from luke_scribe.jobqueue.worker import Worker
from luke_scribe.jobqueue.jobs import Job
from luke_scribe.results.store import ResultStore

settings = Settings(_env_file=None, queue_backend='inproc',
                    results_dir='/content/results', model_cache_dir=None)
broker = InProcBroker(settings)
store = ResultStore(settings.results_dir)

job = Job(type='file', lane='batch', source_path='samples/colab-ko-en.mp3',
         options={'model': 'large-v3-turbo', 'language': 'ko', 'device': 'auto'})
broker.enqueue(job)
worker = Worker(settings=settings, broker=broker, store=store)
worker.drain()

result = store.read_result(job.id)
if result is None:
    # 전사 실패(예: GPU 초기화 실패) 시 결과가 저장되지 않음 — 상태/오류 출력
    state = broker.get(job.id)
    print('결과 없음 — job 상태:', getattr(state, 'status', 'unknown'))
    if state is not None:
        err = getattr(state, 'error_message', None) or getattr(state, 'error_code', None)
        print('job 오류:', err or '없음')
else:
    print('status:', result.status)
    print('text:', result.text[:120])
    print('device:', result.execution.device, '| ct:', result.execution.compute_type, '| rtf:', result.timings.rtf)

7) 벤치마크 (turbo vs large-v3)

manifest에 모델 비교 항목이 있으면 실행합니다. 두 모델을 모두 다운로드하므로 시간이 걸립니다 (turbo ~1.6GB + large-v3 ~3GB).

In [ ]:
# 13) 벤치마크 — 샘플 manifest 사용 (선택, 시간 소요)
# entities는 {canonical, surface, start_char, end_char} dict여야 한다
# (문자열이면 entity_retention이 .get() 호출에 실패해 clip이 실패 처리됨)
import yaml

REF_TEXT = '오늘은 vLLM 서버를 Kubernetes 클러스터에 배포하는 방법을 설명합니다. GPU 가속 추론으로 대기 시간을 줄일 수 있습니다.'
with open('/content/reference.txt', 'w', encoding='utf-8') as f:
    f.write(REF_TEXT)

entities = []
for name in ('vLLM', 'Kubernetes', 'GPU'):
    idx = REF_TEXT.index(name)
    entities.append({
        'canonical': name, 'surface': name,
        'start_char': idx, 'end_char': idx + len(name),
    })

manifest = {
    'name': 'colab-quick',
    'dataset_version': '1.0',
    'language': 'ko',
    'targets': {'entity_preservation': 0.95, 'cer': 0.15},
    'clips': [
        {'id': 'ko-en-tech', 'audio_path': 'samples/colab-ko-en.mp3',
         'reference_path': '/content/reference.txt',
         'duration_sec': 10.5, 'entities': entities},
    ],
}
yaml.safe_dump(manifest, open('/content/manifest.yaml', 'w'))

# 실행 (기본: turbo만 → 빠름)
!luke-scribe bench /content/manifest.yaml --models large-v3-turbo --device auto --repeats 2 --output /content/bench-report.json 2>&1 | tail -20

8) 문제 해결

전사 실패: unsupported device cuda:0

근본 원인: v0.1 엔진이 device="cuda:0"(인덱스 포함)를 그대로 CTranslate2에 전달했는데, CTranslate2는 device="cuda"만 허용하고 인덱스는 별도 device_index 인자로 받습니다. → 엔진에서 device/device_index를 분리하도록 수정 완료 (이 브랜치 최신 커밋 포함).

참고: Colab의 CUDA 13(드라이버 580)에서는 CUDA 12용 CTranslate2 wheel이 런타임 라이브러리(cuBLAS/cuDNN)를 못 찾을 수 있어, 설치 셀 3에서 nvidia-cublas-cu12/nvidia-cudnn-cu12 + LD_LIBRARY_PATH를 설정합니다. 그래도 실패하면 CPU 폴백: --device cpu --compute-type int8 (느리지만 확실).

API 키 인증 실패 (401)

  1. api_keys.json에는 다이제스트만 저장되고 raw 키는 생성 시 1회만 출력됩니다 (보안 설계). 셀 9에서 RAW_KEY를 캡처했는지 확인하세요 — 파일에서 키를 읽으면 401.
  2. 이전 실행에서 남은 서버가 포트 8000을 점유하면 새 키를 모른 채 401이 납니다. 셀 10이 시작 시 pkill로 기존 서버를 종료하고 키 인증(HTTP 200)까지 검증합니다.

업로드 후 job이 queued에 머무는 경우

in-proc 백엔드는 별도 워커 프로세스가 없으면 큐를 소비하지 못합니다. 셀 10이 LUKESCRIBE_AUTO_WORKER=true로 서버를 띄우면 서버 내부 워커 스레드가 업로드 → 완료까지 처리합니다 (v0.1에서 추가된 옵트인 기능).

모델 다운로드 실패

  • Hugging Face 연결 필요. 재시도: LUKESCRIBE_MODEL_DOWNLOAD_RETRIES=3
  • 특정 모델만: --model large-v3-turbo (기본) / --model large-v3

API 키 인증 실패 (401)

api_keys.json에는 다이제스트만 저장되고 raw 키는 생성 시 1회만 출력됩니다 (보안 설계). 셀 9에서 RAW_KEY를 캡처했는지 확인하세요 — 파일에서 키를 읽으면 401이 납니다.

OOM (16GB VRAM)

  • EngineOwner가 자동으로 정밀도를 강등합니다 (float16 → int8_float16 → int8 → CPU)
  • 수동 지정: --compute-type int8_float16

저장소가 private인데 클론 안 됨

1번 셀의 GITEA_TOKEN에 토큰을 입력하고 런타임 → Restart session 후 다시 실행하세요.