Merge feature/stt-ai into main

주요 변경사항:
- EventHub 공유 액세스 정책 재설정 (send-policy, listen-policy)
- Redis DB 2번 읽기 전용 문제 해결
- AI-Python 서비스 추가 (FastAPI 기반)
- STT WebSocket 실시간 스트리밍 구현
- AI 제안사항 실시간 추출 기능 구현
- 테스트 페이지 추가 (stt-test-wav.html)
- 개발 가이드 문서 추가

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Minseo-Jo
2025-10-29 16:01:47 +09:00
81 changed files with 10269 additions and 276 deletions
+2
View File
@@ -0,0 +1,2 @@
"""AI Service - Python FastAPI"""
__version__ = "1.0.0"
+1
View File
@@ -0,0 +1 @@
"""API 레이어"""
+147
View File
@@ -0,0 +1,147 @@
"""AI 제안사항 SSE 엔드포인트"""
from fastapi import APIRouter
from sse_starlette.sse import EventSourceResponse
import logging
import asyncio
from typing import AsyncGenerator
from app.models import RealtimeSuggestionsResponse
from app.services.claude_service import ClaudeService
from app.services.redis_service import RedisService
from app.config import get_settings
logger = logging.getLogger(__name__)
router = APIRouter()
settings = get_settings()
# 서비스 인스턴스
claude_service = ClaudeService()
@router.get(
"/meetings/{meeting_id}/stream",
summary="실시간 AI 제안사항 스트리밍",
description="""
회의 중 실시간으로 AI 제안사항을 Server-Sent Events(SSE)로 스트리밍합니다.
### 동작 방식
1. Redis에서 누적된 회의 텍스트 조회 (5초마다)
2. 임계값(10개 세그먼트) 이상이면 Claude API로 분석
3. 분석 결과를 SSE 이벤트로 전송
### SSE 이벤트 형식
```
event: ai-suggestion
id: {segment_count}
data: {"suggestions": [...]}
```
### 클라이언트 연결 예시 (JavaScript)
```javascript
const eventSource = new EventSource(
'http://localhost:8087/api/v1/ai/suggestions/meetings/{meeting_id}/stream'
);
eventSource.addEventListener('ai-suggestion', (event) => {
const data = JSON.parse(event.data);
console.log('새로운 제안사항:', data.suggestions);
});
eventSource.onerror = (error) => {
console.error('SSE 오류:', error);
eventSource.close();
};
```
### 주의사항
- 연결은 클라이언트가 종료할 때까지 유지됩니다
- 네트워크 타임아웃 설정이 충분히 길어야 합니다
- 브라우저는 자동으로 재연결을 시도합니다
""",
responses={
200: {
"description": "SSE 스트림 연결 성공",
"content": {
"text/event-stream": {
"example": """event: ai-suggestion
id: 15
data: {"suggestions":[{"id":"550e8400-e29b-41d4-a716-446655440000","content":"신제품의 타겟 고객층을 20-30대로 설정하고, 모바일 우선 전략을 취하기로 논의 중입니다.","timestamp":"14:23:45","confidence":0.92}]}
"""
}
}
}
}
)
async def stream_ai_suggestions(meeting_id: str):
"""
실시간 AI 제안사항 SSE 스트리밍
Args:
meeting_id: 회의 ID
Returns:
Server-Sent Events 스트림
"""
logger.info(f"SSE 스트림 시작 - meetingId: {meeting_id}")
async def event_generator() -> AsyncGenerator:
"""SSE 이벤트 생성기"""
redis_service = RedisService()
try:
# Redis 연결
await redis_service.connect()
previous_count = 0
while True:
# 현재 세그먼트 개수 확인
current_count = await redis_service.get_segment_count(meeting_id)
# 임계값 이상이고, 이전보다 증가했으면 분석
if (current_count >= settings.min_segments_for_analysis
and current_count > previous_count):
# 누적된 텍스트 조회
accumulated_text = await redis_service.get_accumulated_text(meeting_id)
if accumulated_text:
# Claude API로 분석
suggestions = await claude_service.analyze_suggestions(accumulated_text)
if suggestions.suggestions:
# SSE 이벤트 전송
yield {
"event": "ai-suggestion",
"id": str(current_count),
"data": suggestions.json()
}
logger.info(
f"AI 제안사항 발행 - meetingId: {meeting_id}, "
f"개수: {len(suggestions.suggestions)}"
)
previous_count = current_count
# 5초마다 체크
await asyncio.sleep(5)
except asyncio.CancelledError:
logger.info(f"SSE 스트림 종료 - meetingId: {meeting_id}")
# 회의 종료 시 데이터 정리는 선택사항 (나중에 조회 필요할 수도)
# await redis_service.cleanup_meeting_data(meeting_id)
except Exception as e:
logger.error(f"SSE 스트림 오류 - meetingId: {meeting_id}", exc_info=e)
finally:
await redis_service.disconnect()
return EventSourceResponse(event_generator())
@router.get("/test")
async def test_endpoint():
"""테스트 엔드포인트"""
return {"message": "AI Suggestions API is working", "port": settings.port}
+45
View File
@@ -0,0 +1,45 @@
"""응답 모델"""
from pydantic import BaseModel, Field
from typing import List
class SimpleSuggestion(BaseModel):
"""간소화된 AI 제안사항"""
id: str = Field(..., description="제안 ID")
content: str = Field(..., description="제안 내용 (1-2문장)")
timestamp: str = Field(..., description="타임스탬프 (HH:MM:SS)")
confidence: float = Field(..., ge=0.0, le=1.0, description="신뢰도 (0-1)")
class Config:
json_schema_extra = {
"example": {
"id": "sugg-001",
"content": "신제품의 타겟 고객층을 20-30대로 설정하고, 모바일 우선 전략을 취하기로 논의 중입니다.",
"timestamp": "00:05:23",
"confidence": 0.92
}
}
class RealtimeSuggestionsResponse(BaseModel):
"""실시간 AI 제안사항 응답"""
suggestions: List[SimpleSuggestion] = Field(
default_factory=list,
description="AI 제안사항 목록"
)
class Config:
json_schema_extra = {
"example": {
"suggestions": [
{
"id": "sugg-001",
"content": "신제품의 타겟 고객층을 20-30대로 설정하고...",
"timestamp": "00:05:23",
"confidence": 0.92
}
]
}
}
+1
View File
@@ -0,0 +1 @@
"""서비스 레이어"""
+113
View File
@@ -0,0 +1,113 @@
"""Azure Event Hub 서비스 - STT 텍스트 수신"""
import asyncio
import logging
import json
from azure.eventhub.aio import EventHubConsumerClient
from app.config import get_settings
from app.services.redis_service import RedisService
logger = logging.getLogger(__name__)
settings = get_settings()
class EventHubService:
"""Event Hub 리스너 - STT 텍스트 실시간 수신"""
def __init__(self):
self.client = None
self.redis_service = RedisService()
async def start(self):
"""Event Hub 리스닝 시작"""
if not settings.eventhub_connection_string:
logger.warning("Event Hub 연결 문자열이 설정되지 않음 - Event Hub 리스너 비활성화")
return
logger.info("Event Hub 리스너 시작")
try:
# Redis 연결
await self.redis_service.connect()
# Event Hub 클라이언트 생성
self.client = EventHubConsumerClient.from_connection_string(
conn_str=settings.eventhub_connection_string,
consumer_group=settings.eventhub_consumer_group,
eventhub_name=settings.eventhub_name,
)
# 이벤트 수신 시작
async with self.client:
await self.client.receive(
on_event=self.on_event,
on_error=self.on_error,
starting_position="-1", # 최신 이벤트부터
)
except Exception as e:
logger.error(f"Event Hub 리스너 오류: {e}")
finally:
await self.redis_service.disconnect()
async def on_event(self, partition_context, event):
"""
이벤트 수신 핸들러
이벤트 형식 (STT Service에서 발행):
{
"eventType": "TranscriptSegmentReady",
"meetingId": "meeting-123",
"text": "변환된 텍스트",
"timestamp": 1234567890000
}
"""
try:
# 이벤트 데이터 파싱
event_data = json.loads(event.body_as_str())
event_type = event_data.get("eventType")
meeting_id = event_data.get("meetingId")
text = event_data.get("text")
timestamp = event_data.get("timestamp")
if event_type == "TranscriptSegmentReady" and meeting_id and text:
logger.info(
f"STT 텍스트 수신 - meetingId: {meeting_id}, "
f"텍스트 길이: {len(text)}"
)
# Redis에 텍스트 축적 (슬라이딩 윈도우)
await self.redis_service.add_transcript_segment(
meeting_id=meeting_id,
text=text,
timestamp=timestamp
)
logger.debug(f"Redis 저장 완료 - meetingId: {meeting_id}")
# MVP 개발: checkpoint 업데이트 제거 (InMemory 모드)
# await partition_context.update_checkpoint(event)
except Exception as e:
logger.error(f"이벤트 처리 오류: {e}", exc_info=True)
async def on_error(self, partition_context, error):
"""에러 핸들러"""
logger.error(
f"Event Hub 에러 - Partition: {partition_context.partition_id}, "
f"Error: {error}"
)
async def stop(self):
"""Event Hub 리스너 종료"""
if self.client:
await self.client.close()
logger.info("Event Hub 리스너 종료")
# 백그라운드 태스크로 실행할 함수
async def start_eventhub_listener():
"""Event Hub 리스너 백그라운드 실행"""
service = EventHubService()
await service.start()
+117
View File
@@ -0,0 +1,117 @@
"""Redis 서비스 - 실시간 텍스트 축적"""
import redis.asyncio as redis
import logging
from typing import List
from app.config import get_settings
logger = logging.getLogger(__name__)
settings = get_settings()
class RedisService:
"""Redis 서비스 (슬라이딩 윈도우 방식)"""
def __init__(self):
self.redis_client = None
async def connect(self):
"""Redis 연결"""
try:
self.redis_client = await redis.Redis(
host=settings.redis_host,
port=settings.redis_port,
password=settings.redis_password,
db=settings.redis_db,
decode_responses=True
)
await self.redis_client.ping()
logger.info("Redis 연결 성공")
except Exception as e:
logger.error(f"Redis 연결 실패: {e}")
raise
async def disconnect(self):
"""Redis 연결 종료"""
if self.redis_client:
await self.redis_client.close()
logger.info("Redis 연결 종료")
async def add_transcript_segment(
self,
meeting_id: str,
text: str,
timestamp: int
):
"""
실시간 텍스트 세그먼트 추가 (슬라이딩 윈도우)
Args:
meeting_id: 회의 ID
text: 텍스트 세그먼트
timestamp: 타임스탬프 (밀리초)
"""
key = f"meeting:{meeting_id}:transcript"
value = f"{timestamp}:{text}"
# Sorted Set에 추가 (타임스탬프를 스코어로)
await self.redis_client.zadd(key, {value: timestamp})
# 설정된 시간 이전 데이터 제거 (기본 5분)
retention_ms = settings.text_retention_seconds * 1000
cutoff_time = timestamp - retention_ms
await self.redis_client.zremrangebyscore(key, 0, cutoff_time)
logger.debug(f"텍스트 세그먼트 추가 - meetingId: {meeting_id}")
async def get_accumulated_text(self, meeting_id: str) -> str:
"""
누적된 텍스트 조회 (최근 5분)
Args:
meeting_id: 회의 ID
Returns:
누적된 텍스트 (시간순)
"""
key = f"meeting:{meeting_id}:transcript"
# 최신순으로 모든 세그먼트 조회
segments = await self.redis_client.zrevrange(key, 0, -1)
if not segments:
return ""
# 타임스탬프 제거하고 텍스트만 추출
texts = []
for seg in segments:
parts = seg.split(":", 1)
if len(parts) == 2:
texts.append(parts[1])
# 시간순으로 정렬 (역순으로 조회했으므로 다시 뒤집기)
return "\n".join(reversed(texts))
async def get_segment_count(self, meeting_id: str) -> int:
"""
누적된 세그먼트 개수
Args:
meeting_id: 회의 ID
Returns:
세그먼트 개수
"""
key = f"meeting:{meeting_id}:transcript"
count = await self.redis_client.zcard(key)
return count if count else 0
async def cleanup_meeting_data(self, meeting_id: str):
"""
회의 종료 시 데이터 정리
Args:
meeting_id: 회의 ID
"""
key = f"meeting:{meeting_id}:transcript"
await self.redis_client.delete(key)
logger.info(f"회의 데이터 정리 완료 - meetingId: {meeting_id}")