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
+35
View File
@@ -0,0 +1,35 @@
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
venv/
env/
ENV/
# IDE
.vscode/
.idea/
*.swp
*.swo
# Logs
logs/
*.log
# Environment
.env
.env.local
# Git
.git/
.gitignore
# Documentation
README.md
API-DOCUMENTATION.md
# Test
tests/
test_*.py
+26
View File
@@ -0,0 +1,26 @@
# 서버 설정
PORT=8086
HOST=0.0.0.0
# Claude API
CLAUDE_API_KEY=your-api-key-here
CLAUDE_MODEL=claude-3-5-sonnet-20241022
CLAUDE_MAX_TOKENS=2000
CLAUDE_TEMPERATURE=0.3
# Redis
REDIS_HOST=20.249.177.114
REDIS_PORT=6379
REDIS_PASSWORD=Hi5Jessica!
REDIS_DB=4
# Azure Event Hub
EVENTHUB_CONNECTION_STRING=Endpoint=sb://hgzero-eventhub-ns.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=VUqZ9vFgu35E3c6RiUzoOGVUP8IZpFvlV+AEhC6sUpo=
EVENTHUB_NAME=hgzero-eventhub-name
EVENTHUB_CONSUMER_GROUP=ai-transcript-group
# CORS
CORS_ORIGINS=["http://localhost:*","http://127.0.0.1:*"]
# 로깅
LOG_LEVEL=INFO
+37
View File
@@ -0,0 +1,37 @@
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
venv/
ENV/
env/
.venv
# Environment
.env
# IDE
.vscode/
.idea/
*.swp
*.swo
# OS
.DS_Store
Thumbs.db
# Logs
*.log
logs/
# Testing
.pytest_cache/
.coverage
htmlcov/
# Distribution
build/
dist/
*.egg-info/
+250
View File
@@ -0,0 +1,250 @@
# AI Service API Documentation
## 서비스 정보
- **Base URL**: `http://localhost:8087`
- **프로덕션 URL**: `http://{AKS-IP}:8087` (배포 후)
- **포트**: 8087
- **프로토콜**: HTTP
- **CORS**: 모든 origin 허용 (개발 환경)
## API 엔드포인트
### 1. 실시간 AI 제안사항 스트리밍 (SSE)
**엔드포인트**: `GET /api/ai/suggestions/meetings/{meeting_id}/stream`
**설명**: 회의 중 실시간으로 AI 제안사항을 Server-Sent Events로 스트리밍합니다.
**파라미터**:
| 이름 | 위치 | 타입 | 필수 | 설명 |
|------|------|------|------|------|
| meeting_id | path | string | O | 회의 ID |
**응답 형식**: `text/event-stream`
**SSE 이벤트 구조**:
```
event: ai-suggestion
id: 15
data: {"suggestions":[{"id":"uuid","content":"제안 내용","timestamp":"14:23:45","confidence":0.92}]}
```
**응답 데이터 스키마**:
```typescript
interface SimpleSuggestion {
id: string; // 제안 ID (UUID)
content: string; // 제안 내용 (1-2문장)
timestamp: string; // 타임스탬프 (HH:MM:SS)
confidence: number; // 신뢰도 (0.0 ~ 1.0)
}
interface RealtimeSuggestionsResponse {
suggestions: SimpleSuggestion[];
}
```
**프론트엔드 연동 예시 (JavaScript/TypeScript)**:
```javascript
// EventSource 연결
const meetingId = 'meeting-123';
const eventSource = new EventSource(
`http://localhost:8087/api/ai/suggestions/meetings/${meetingId}/stream`
);
// AI 제안사항 수신
eventSource.addEventListener('ai-suggestion', (event) => {
const data = JSON.parse(event.data);
data.suggestions.forEach(suggestion => {
console.log('새 제안:', suggestion.content);
console.log('신뢰도:', suggestion.confidence);
console.log('시간:', suggestion.timestamp);
// UI 업데이트
addSuggestionToUI(suggestion);
});
});
// 에러 핸들링
eventSource.onerror = (error) => {
console.error('SSE 연결 오류:', error);
eventSource.close();
};
// 연결 종료 (회의 종료 시)
function closeSuggestions() {
eventSource.close();
}
```
**React 예시**:
```tsx
import { useEffect, useState } from 'react';
interface Suggestion {
id: string;
content: string;
timestamp: string;
confidence: number;
}
function MeetingRoom({ meetingId }: { meetingId: string }) {
const [suggestions, setSuggestions] = useState<Suggestion[]>([]);
useEffect(() => {
const eventSource = new EventSource(
`http://localhost:8087/api/ai/suggestions/meetings/${meetingId}/stream`
);
eventSource.addEventListener('ai-suggestion', (event) => {
const data = JSON.parse(event.data);
setSuggestions(prev => [...prev, ...data.suggestions]);
});
eventSource.onerror = () => {
console.error('SSE 연결 오류');
eventSource.close();
};
return () => {
eventSource.close();
};
}, [meetingId]);
return (
<div>
<h2>AI </h2>
{suggestions.map(s => (
<div key={s.id}>
<span>{s.timestamp}</span>
<p>{s.content}</p>
<small>: {(s.confidence * 100).toFixed(0)}%</small>
</div>
))}
</div>
);
}
```
### 2. 헬스 체크
**엔드포인트**: `GET /health`
**설명**: 서비스 상태 확인 (Kubernetes probe용)
**응답 예시**:
```json
{
"status": "healthy",
"service": "AI Service",
"port": 8087
}
```
### 3. 서비스 정보
**엔드포인트**: `GET /`
**설명**: 서비스 기본 정보 조회
**응답 예시**:
```json
{
"service": "AI Service",
"version": "1.0.0",
"status": "running",
"endpoints": {
"test": "/api/ai/suggestions/test",
"stream": "/api/ai/suggestions/meetings/{meeting_id}/stream"
}
}
```
## 동작 흐름
```
1. 회의 시작
└─> 프론트엔드가 SSE 연결 시작
2. 음성 녹음
└─> STT 서비스가 텍스트 변환
└─> Event Hub 발행
└─> AI 서비스가 Redis에 축적
3. 실시간 분석 (5초마다)
└─> Redis에서 텍스트 조회
└─> 임계값(10개 세그먼트) 도달 시
└─> Claude API 분석
└─> SSE로 제안사항 전송
└─> 프론트엔드 UI 업데이트
4. 회의 종료
└─> SSE 연결 종료
```
## 주의사항
1. **연결 유지**:
- SSE 연결은 장시간 유지되므로 네트워크 타임아웃 설정 필요
- 브라우저는 연결 끊김 시 자동 재연결 시도
2. **CORS**:
- 개발 환경: 모든 origin 허용
- 프로덕션: 특정 도메인만 허용하도록 설정 필요
3. **에러 처리**:
- SSE 연결 실패 시 재시도 로직 구현 권장
- 네트워크 오류 시 사용자에게 알림
4. **성능**:
- 한 회의당 하나의 SSE 연결만 유지
- 불필요한 재연결 방지
## 테스트
### curl 테스트:
```bash
# 헬스 체크
curl http://localhost:8087/health
# SSE 스트리밍 테스트
curl -N http://localhost:8087/api/ai/suggestions/meetings/test-meeting/stream
```
### 브라우저 테스트:
1. 서비스 실행: `python3 main.py`
2. Swagger UI 접속: http://localhost:8087/docs
3. `/api/ai/suggestions/meetings/{meeting_id}/stream` 엔드포인트 테스트
## 환경 변수
프론트엔드에서 API URL을 환경 변수로 관리:
```env
# .env.local
NEXT_PUBLIC_AI_SERVICE_URL=http://localhost:8087
```
```typescript
const AI_SERVICE_URL = process.env.NEXT_PUBLIC_AI_SERVICE_URL || 'http://localhost:8087';
const eventSource = new EventSource(
`${AI_SERVICE_URL}/api/ai/suggestions/meetings/${meetingId}/stream`
);
```
## FAQ
**Q: SSE vs WebSocket?**
A: SSE는 서버→클라이언트 단방향 통신에 최적화되어 있습니다. 이 서비스는 AI 제안사항을 프론트엔드로 전송만 하므로 SSE가 적합합니다.
**Q: 재연결은 어떻게?**
A: 브라우저의 EventSource는 자동으로 재연결을 시도합니다. 추가 로직 불필요.
**Q: 여러 클라이언트가 동시 연결 가능?**
A: 네, 각 클라이언트는 독립적으로 SSE 연결을 유지합니다.
**Q: 제안사항이 오지 않으면?**
A: Redis에 충분한 텍스트(10개 세그먼트)가 축적되어야 분석이 시작됩니다. 5초마다 체크합니다.
+318
View File
@@ -0,0 +1,318 @@
# AI Service (Python) - AKS 배포 가이드
## 📋 사전 준비
### 1. Azure Container Registry (ACR) 접근 권한
```bash
# ACR 로그인
az acr login --name acrdigitalgarage02
```
### 2. Kubernetes 클러스터 접근
```bash
# AKS 자격 증명 가져오기
az aks get-credentials --resource-group <리소스그룹> --name <클러스터명>
# 네임스페이스 확인
kubectl get namespace hgzero
```
## 🐳 1단계: Docker 이미지 빌드 및 푸시
### 이미지 빌드
```bash
cd ai-python
# 이미지 빌드
docker build -t acrdigitalgarage02.azurecr.io/hgzero/ai-service:latest .
# 특정 버전 태그도 함께 생성 (권장)
docker tag acrdigitalgarage02.azurecr.io/hgzero/ai-service:latest \
acrdigitalgarage02.azurecr.io/hgzero/ai-service:v1.0.0
```
### ACR에 푸시
```bash
# latest 태그 푸시
docker push acrdigitalgarage02.azurecr.io/hgzero/ai-service:latest
# 버전 태그 푸시
docker push acrdigitalgarage02.azurecr.io/hgzero/ai-service:v1.0.0
```
### 로컬 테스트 (선택)
```bash
# 이미지 실행 테스트
docker run -p 8087:8087 \
-e CLAUDE_API_KEY="your-api-key" \
-e REDIS_HOST="20.249.177.114" \
-e REDIS_PASSWORD="Hi5Jessica!" \
acrdigitalgarage02.azurecr.io/hgzero/ai-service:latest
# 헬스 체크
curl http://localhost:8087/health
```
## 🔐 2단계: Kubernetes Secret 생성
### Claude API Key Secret 생성
```bash
# Claude API Key를 base64로 인코딩
echo -n "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" | base64
# Secret 생성
kubectl create secret generic ai-secret \
--from-literal=claude-api-key="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" \
-n hgzero
```
### Event Hub Secret 생성 (기존에 없는 경우)
```bash
# Event Hub Connection String (AI Listen Policy)
kubectl create secret generic azure-secret \
--from-literal=eventhub-ai-connection-string="Endpoint=sb://hgzero-eventhub-ns.servicebus.windows.net/;SharedAccessKeyName=ai-listen-policy;SharedAccessKey=wqcbVIXlOMyn/C562lx6DD75AyjHQ87xo+AEhJ7js9Q=" \
-n hgzero --dry-run=client -o yaml | kubectl apply -f -
```
### Redis Secret 확인/생성
```bash
# 기존 Redis Secret 확인
kubectl get secret redis-secret -n hgzero
# 없으면 생성
kubectl create secret generic redis-secret \
--from-literal=password="Hi5Jessica!" \
-n hgzero
```
### ConfigMap 확인
```bash
# Redis ConfigMap 확인
kubectl get configmap redis-config -n hgzero
# 없으면 생성
kubectl create configmap redis-config \
--from-literal=host="20.249.177.114" \
--from-literal=port="6379" \
-n hgzero
```
## 🚀 3단계: AI 서비스 배포
### 배포 실행
```bash
# 배포 매니페스트 적용
kubectl apply -f deploy/k8s/backend/ai-service.yaml
# 배포 상태 확인
kubectl get deployment ai-service -n hgzero
kubectl get pods -n hgzero -l app=ai-service
```
### 로그 확인
```bash
# Pod 이름 가져오기
POD_NAME=$(kubectl get pods -n hgzero -l app=ai-service -o jsonpath='{.items[0].metadata.name}')
# 실시간 로그 확인
kubectl logs -f $POD_NAME -n hgzero
# Event Hub 연결 로그 확인
kubectl logs $POD_NAME -n hgzero | grep "Event Hub"
```
## 🌐 4단계: Ingress 업데이트
### Ingress 적용
```bash
# Ingress 설정 적용
kubectl apply -f .github/kustomize/base/common/ingress.yaml
# Ingress 확인
kubectl get ingress -n hgzero
kubectl describe ingress hgzero -n hgzero
```
### 접속 테스트
```bash
# 서비스 URL
AI_SERVICE_URL="http://hgzero-api.20.214.196.128.nip.io"
# 헬스 체크
curl $AI_SERVICE_URL/api/ai/suggestions/test
# Swagger UI
echo "Swagger UI: $AI_SERVICE_URL/swagger-ui.html"
```
## ✅ 5단계: 배포 검증
### Pod 상태 확인
```bash
# Pod 상태
kubectl get pods -n hgzero -l app=ai-service
# Pod 상세 정보
kubectl describe pod -n hgzero -l app=ai-service
# Pod 리소스 사용량
kubectl top pod -n hgzero -l app=ai-service
```
### 서비스 확인
```bash
# Service 확인
kubectl get svc ai-service -n hgzero
# Service 상세 정보
kubectl describe svc ai-service -n hgzero
```
### 엔드포인트 테스트
```bash
# 내부 테스트 (Pod에서)
kubectl exec -it $POD_NAME -n hgzero -- curl http://localhost:8087/health
# 외부 테스트 (Ingress 통해)
curl http://hgzero-api.20.214.196.128.nip.io/api/ai/suggestions/test
# SSE 스트리밍 테스트
curl -N http://hgzero-api.20.214.196.128.nip.io/api/ai/suggestions/meetings/test-meeting/stream
```
## 🔄 업데이트 배포
### 새 버전 배포
```bash
# 1. 새 이미지 빌드 및 푸시
docker build -t acrdigitalgarage02.azurecr.io/hgzero/ai-service:v1.0.1 .
docker push acrdigitalgarage02.azurecr.io/hgzero/ai-service:v1.0.1
# 2. Deployment 이미지 업데이트
kubectl set image deployment/ai-service \
ai-service=acrdigitalgarage02.azurecr.io/hgzero/ai-service:v1.0.1 \
-n hgzero
# 3. 롤아웃 상태 확인
kubectl rollout status deployment/ai-service -n hgzero
# 4. 롤아웃 히스토리
kubectl rollout history deployment/ai-service -n hgzero
```
### 롤백 (문제 발생 시)
```bash
# 이전 버전으로 롤백
kubectl rollout undo deployment/ai-service -n hgzero
# 특정 리비전으로 롤백
kubectl rollout undo deployment/ai-service -n hgzero --to-revision=2
```
## 🐛 트러블슈팅
### Pod가 Running 상태가 아닌 경우
```bash
# Pod 상태 확인
kubectl get pods -n hgzero -l app=ai-service
# Pod 이벤트 확인
kubectl describe pod -n hgzero -l app=ai-service
# 로그 확인
kubectl logs -n hgzero -l app=ai-service
```
### ImagePullBackOff 에러
```bash
# ACR 접근 권한 확인
kubectl get secret -n hgzero
# ACR Pull Secret 생성 (필요시)
kubectl create secret docker-registry acr-secret \
--docker-server=acrdigitalgarage02.azurecr.io \
--docker-username=<ACR_USERNAME> \
--docker-password=<ACR_PASSWORD> \
-n hgzero
```
### CrashLoopBackOff 에러
```bash
# 로그 확인
kubectl logs -n hgzero -l app=ai-service --previous
# 환경 변수 확인
kubectl exec -it $POD_NAME -n hgzero -- env | grep -E "CLAUDE|REDIS|EVENTHUB"
```
### Redis 연결 실패
```bash
# Redis 접속 테스트 (Pod에서)
kubectl exec -it $POD_NAME -n hgzero -- \
python -c "import redis; r=redis.Redis(host='20.249.177.114', port=6379, password='Hi5Jessica!', db=4); print(r.ping())"
```
### Event Hub 연결 실패
```bash
# Event Hub 연결 문자열 확인
kubectl get secret azure-secret -n hgzero -o jsonpath='{.data.eventhub-ai-connection-string}' | base64 -d
# 로그에서 Event Hub 오류 확인
kubectl logs $POD_NAME -n hgzero | grep -i "eventhub\|error"
```
## 📊 모니터링
### 실시간 로그 모니터링
```bash
# 실시간 로그
kubectl logs -f -n hgzero -l app=ai-service
# 특정 키워드 필터링
kubectl logs -f -n hgzero -l app=ai-service | grep -E "SSE|Claude|AI"
```
### 리소스 사용량
```bash
# CPU/메모리 사용량
kubectl top pod -n hgzero -l app=ai-service
# 상세 리소스 정보
kubectl describe pod -n hgzero -l app=ai-service | grep -A 5 "Resources"
```
## 🗑️ 삭제
### AI 서비스 삭제
```bash
# Deployment와 Service 삭제
kubectl delete -f deploy/k8s/backend/ai-service.yaml
# Secret 삭제
kubectl delete secret ai-secret -n hgzero
# ConfigMap 유지 (다른 서비스에서 사용 중)
# kubectl delete configmap redis-config -n hgzero
```
## 📝 주의사항
1. **Secret 관리**
- Claude API Key는 민감 정보이므로 Git에 커밋하지 마세요
- 프로덕션 환경에서는 Azure Key Vault 사용 권장
2. **리소스 제한**
- 초기 설정: CPU 250m-1000m, Memory 512Mi-1024Mi
- 트래픽에 따라 조정 필요
3. **Event Hub**
- AI Listen Policy 사용 (Listen 권한만)
- EntityPath는 연결 문자열에서 제거
4. **Redis**
- DB 4번 사용 (다른 서비스와 분리)
- TTL 5분 설정 (슬라이딩 윈도우)
5. **Ingress 경로**
- `/api/ai/suggestions``/api/ai`보다 먼저 정의되어야 함
- 더 구체적인 경로를 위에 배치
+27
View File
@@ -0,0 +1,27 @@
# Python 3.11 slim 이미지 사용
FROM python:3.11-slim
# 작업 디렉토리 설정
WORKDIR /app
# 시스템 패키지 업데이트 및 필요한 도구 설치
RUN apt-get update && apt-get install -y \
gcc \
&& rm -rf /var/lib/apt/lists/*
# Python 의존성 파일 복사 및 설치
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# 애플리케이션 코드 복사
COPY . .
# 포트 노출
EXPOSE 8087
# 헬스 체크
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8087/health')" || exit 1
# 애플리케이션 실행
CMD ["python", "main.py"]
+167
View File
@@ -0,0 +1,167 @@
# AI Service (Python)
실시간 AI 제안사항 서비스 - FastAPI 기반
## 📋 개요
STT 서비스에서 실시간으로 변환된 텍스트를 받아 Claude API로 분석하여 회의 제안사항을 생성하고, SSE(Server-Sent Events)로 프론트엔드에 스트리밍합니다.
## 🏗️ 아키텍처
```
Frontend (회의록 작성 화면)
↓ (SSE 연결)
AI Service (Python)
↓ (Redis 조회)
Redis (실시간 텍스트 축적)
↑ (Event Hub)
STT Service (음성 → 텍스트)
```
## 🚀 실행 방법
### 1. 환경 설정
```bash
# .env 파일 생성
cp .env.example .env
# .env에서 아래 값 설정
CLAUDE_API_KEY=sk-ant-... # 실제 Claude API 키
```
### 2. 의존성 설치
```bash
# 가상환경 생성 (권장)
python3 -m venv venv
source venv/bin/activate # Mac/Linux
# venv\Scripts\activate # Windows
# 패키지 설치
pip install -r requirements.txt
```
### 3. 서비스 시작
```bash
# 방법 1: 스크립트 실행
./start.sh
# 방법 2: 직접 실행
python3 main.py
```
### 4. 서비스 확인
```bash
# 헬스 체크
curl http://localhost:8086/health
# SSE 스트림 테스트
curl -N http://localhost:8086/api/v1/ai/suggestions/meetings/test-meeting/stream
```
## 📡 API 엔드포인트
### SSE 스트리밍
```
GET /api/v1/ai/suggestions/meetings/{meeting_id}/stream
```
**응답 형식 (SSE)**:
```json
event: ai-suggestion
data: {
"suggestions": [
{
"id": "uuid",
"content": "신제품의 타겟 고객층을 20-30대로 설정...",
"timestamp": "00:05:23",
"confidence": 0.92
}
]
}
```
## 🔧 개발 환경
- **Python**: 3.9+
- **Framework**: FastAPI
- **AI**: Anthropic Claude API
- **Cache**: Redis
- **Event**: Azure Event Hub
## 📂 프로젝트 구조
```
ai-python/
├── main.py # FastAPI 진입점
├── requirements.txt # 의존성
├── .env.example # 환경 변수 예시
├── start.sh # 시작 스크립트
└── app/
├── config.py # 환경 설정
├── models/
│ └── response.py # 응답 모델
├── services/
│ ├── claude_service.py # Claude API 서비스
│ ├── redis_service.py # Redis 서비스
│ └── eventhub_service.py # Event Hub 리스너
└── api/
└── v1/
└── suggestions.py # SSE 엔드포인트
```
## ⚙️ 환경 변수
| 변수 | 설명 | 기본값 |
|------|------|--------|
| `CLAUDE_API_KEY` | Claude API 키 | (필수) |
| `CLAUDE_MODEL` | Claude 모델 | claude-3-5-sonnet-20241022 |
| `REDIS_HOST` | Redis 호스트 | 20.249.177.114 |
| `REDIS_PORT` | Redis 포트 | 6379 |
| `EVENTHUB_CONNECTION_STRING` | Event Hub 연결 문자열 | (선택) |
| `PORT` | 서비스 포트 | 8086 |
## 🔍 동작 원리
1. **STT → Event Hub**: STT 서비스가 음성을 텍스트로 변환하여 Event Hub에 발행
2. **Event Hub → Redis**: AI 서비스가 Event Hub에서 텍스트를 받아 Redis에 축적 (슬라이딩 윈도우: 최근 5분)
3. **Redis → Claude API**: 임계값(10개 세그먼트) 이상이면 Claude API로 분석
4. **Claude API → Frontend**: 분석 결과를 SSE로 프론트엔드에 스트리밍
## 🧪 테스트
```bash
# Event Hub 없이 SSE만 테스트 (Mock 데이터)
curl -N http://localhost:8086/api/v1/ai/suggestions/meetings/test-meeting/stream
# 5초마다 샘플 제안사항이 발행됩니다
```
## 📝 개발 가이드
### Claude API 키 발급
1. https://console.anthropic.com/ 접속
2. API Keys 메뉴에서 새 키 생성
3. `.env` 파일에 설정
### Redis 연결 확인
```bash
redis-cli -h 20.249.177.114 -p 6379 -a Hi5Jessica! ping
# 응답: PONG
```
### Event Hub 설정 (선택)
- Event Hub가 없어도 SSE 스트리밍은 동작합니다
- STT 연동 시 필요
## 🚧 TODO
- [ ] Event Hub 연동 테스트
- [ ] 프론트엔드 연동 테스트
- [ ] 에러 핸들링 강화
- [ ] 로깅 개선
- [ ] 성능 모니터링
+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}")
+115
View File
@@ -0,0 +1,115 @@
#!/bin/bash
# AI Python 서비스 재시작 스크립트
# 8086 포트로 깔끔하게 재시작
echo "=================================="
echo "AI Python 서비스 재시작"
echo "=================================="
# 1. 기존 프로세스 종료
echo "1️⃣ 기존 프로세스 정리 중..."
pkill -9 -f "python.*main.py" 2>/dev/null
pkill -9 -f "uvicorn.*8086" 2>/dev/null
pkill -9 -f "uvicorn.*8087" 2>/dev/null
# 잠시 대기 (포트 해제 대기)
sleep 2
# 2. 포트 확인
echo "2️⃣ 포트 상태 확인..."
if lsof -i:8086 > /dev/null 2>&1; then
echo " ⚠️ 8086 포트가 아직 사용 중입니다."
echo " 강제 종료 시도..."
PID=$(lsof -ti:8086)
if [ ! -z "$PID" ]; then
kill -9 $PID
sleep 2
fi
fi
if lsof -i:8086 > /dev/null 2>&1; then
echo " ❌ 8086 포트를 해제할 수 없습니다."
echo " 시스템 재부팅 후 다시 시도하거나,"
echo " 다른 포트를 사용하세요."
exit 1
else
echo " ✅ 8086 포트 사용 가능"
fi
# 3. 가상환경 활성화
echo "3️⃣ 가상환경 활성화..."
if [ ! -d "venv" ]; then
echo " ❌ 가상환경이 없습니다. venv 디렉토리를 생성하세요."
exit 1
fi
source venv/bin/activate
echo " ✅ 가상환경 활성화 완료"
# 4. 로그 디렉토리 확인
mkdir -p ../logs
# 5. 서비스 시작
echo "4️⃣ AI Python 서비스 시작 (포트: 8086)..."
nohup python3 main.py > ../logs/ai-python.log 2>&1 &
PID=$!
echo " PID: $PID"
echo " 로그: ../logs/ai-python.log"
# 6. 시작 대기
echo "5️⃣ 서비스 시작 대기 (7초)..."
sleep 7
# 7. 상태 확인
echo "6️⃣ 서비스 상태 확인..."
# 프로세스 확인
if ps -p $PID > /dev/null; then
echo " ✅ 프로세스 실행 중 (PID: $PID)"
else
echo " ❌ 프로세스 종료됨"
echo " 로그 확인:"
tail -20 ../logs/ai-python.log
exit 1
fi
# 포트 확인
if lsof -i:8086 > /dev/null 2>&1; then
echo " ✅ 8086 포트 리스닝 중"
else
echo " ⚠️ 8086 포트 아직 준비 중..."
fi
# Health 체크
echo "7️⃣ Health Check..."
sleep 2
HEALTH=$(curl -s http://localhost:8086/health 2>/dev/null)
if [ $? -eq 0 ]; then
echo " ✅ Health Check 성공"
echo " $HEALTH"
else
echo " ⚠️ Health Check 실패 (서버가 아직 시작 중일 수 있습니다)"
echo ""
echo " 최근 로그:"
tail -10 ../logs/ai-python.log
fi
echo ""
echo "=================================="
echo "✅ AI Python 서비스 시작 완료"
echo "=================================="
echo "📊 서비스 정보:"
echo " - PID: $PID"
echo " - 포트: 8086"
echo " - 로그: tail -f ../logs/ai-python.log"
echo ""
echo "📡 엔드포인트:"
echo " - Health: http://localhost:8086/health"
echo " - Root: http://localhost:8086/"
echo " - Swagger: http://localhost:8086/swagger-ui.html"
echo ""
echo "🛑 서비스 중지: pkill -f 'python.*main.py'"
echo "=================================="