This commit is contained in:
yabo0812 2025-10-29 17:23:13 +09:00
commit 8dd830c25f
10 changed files with 621 additions and 1608 deletions

View File

@ -1,5 +1,6 @@
"""AI 제안사항 SSE 엔드포인트""" """AI 제안사항 SSE 엔드포인트"""
from fastapi import APIRouter from fastapi import APIRouter, Response
from fastapi.responses import StreamingResponse
from sse_starlette.sse import EventSourceResponse from sse_starlette.sse import EventSourceResponse
import logging import logging
import asyncio import asyncio
@ -94,9 +95,16 @@ async def stream_ai_suggestions(meeting_id: str):
previous_count = 0 previous_count = 0
# Keep-alive를 위한 주석 전송
yield {
"event": "ping",
"data": "connected"
}
while True: while True:
# 현재 세그먼트 개수 확인 # 현재 세그먼트 개수 확인
current_count = await redis_service.get_segment_count(meeting_id) current_count = await redis_service.get_segment_count(meeting_id)
logger.debug(f"세그먼트 카운트 - meetingId: {meeting_id}, count: {current_count}, prev: {previous_count}")
# 임계값 이상이고, 이전보다 증가했으면 분석 # 임계값 이상이고, 이전보다 증가했으면 분석
if (current_count >= settings.min_segments_for_analysis if (current_count >= settings.min_segments_for_analysis
@ -106,6 +114,8 @@ async def stream_ai_suggestions(meeting_id: str):
accumulated_text = await redis_service.get_accumulated_text(meeting_id) accumulated_text = await redis_service.get_accumulated_text(meeting_id)
if accumulated_text: if accumulated_text:
logger.info(f"텍스트 누적 완료 - meetingId: {meeting_id}, 길이: {len(accumulated_text)}")
# Claude API로 분석 # Claude API로 분석
suggestions = await claude_service.analyze_suggestions(accumulated_text) suggestions = await claude_service.analyze_suggestions(accumulated_text)
@ -124,6 +134,12 @@ async def stream_ai_suggestions(meeting_id: str):
previous_count = current_count previous_count = current_count
# Keep-alive 주석 전송 (SSE 연결 유지)
yield {
"event": "ping",
"data": f"alive-{current_count}"
}
# 5초마다 체크 # 5초마다 체크
await asyncio.sleep(5) await asyncio.sleep(5)
@ -138,7 +154,16 @@ async def stream_ai_suggestions(meeting_id: str):
finally: finally:
await redis_service.disconnect() await redis_service.disconnect()
return EventSourceResponse(event_generator()) # CORS 헤더를 포함한 EventSourceResponse 반환
return EventSourceResponse(
event_generator(),
headers={
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no",
"Access-Control-Allow-Origin": "http://localhost:8888",
"Access-Control-Allow-Credentials": "true",
}
)
@router.get("/test") @router.get("/test")

View File

@ -42,8 +42,8 @@ class Settings(BaseSettings):
# 로깅 # 로깅
log_level: str = "INFO" log_level: str = "INFO"
# 분석 임계값 # 분석 임계값 (MVP 수준)
min_segments_for_analysis: int = 10 min_segments_for_analysis: int = 3 # 3개 세그먼트 = 약 15-30초 분량의 대화
text_retention_seconds: int = 300 # 5분 text_retention_seconds: int = 300 # 5분
class Config: class Config:

View File

@ -63,28 +63,48 @@ class EventHubService:
} }
""" """
try: try:
# 이벤트 원본 데이터 로깅
raw_body = event.body_as_str()
logger.info(f"수신한 이벤트 원본 (처음 300자): {raw_body[:300]}")
# 이벤트 데이터 파싱 # 이벤트 데이터 파싱
event_data = json.loads(event.body_as_str()) event_data = json.loads(raw_body)
event_type = event_data.get("eventType") event_type = event_data.get("eventType")
meeting_id = event_data.get("meetingId") meeting_id = event_data.get("meetingId")
text = event_data.get("text") text = event_data.get("text")
timestamp = event_data.get("timestamp") timestamp_raw = event_data.get("timestamp")
if event_type == "TranscriptSegmentReady" and meeting_id and text: # timestamp 변환: LocalDateTime 배열 → Unix timestamp (ms)
# Java LocalDateTime은 [year, month, day, hour, minute, second, nano] 형식
if isinstance(timestamp_raw, list) and len(timestamp_raw) >= 3:
from datetime import datetime
year, month, day = timestamp_raw[0:3]
hour = timestamp_raw[3] if len(timestamp_raw) > 3 else 0
minute = timestamp_raw[4] if len(timestamp_raw) > 4 else 0
second = timestamp_raw[5] if len(timestamp_raw) > 5 else 0
dt = datetime(year, month, day, hour, minute, second)
timestamp = int(dt.timestamp() * 1000) # milliseconds
else:
timestamp = int(timestamp_raw) if timestamp_raw else int(datetime.now().timestamp() * 1000)
# SegmentCreated 이벤트 처리
if event_type == "SegmentCreated" and meeting_id and text:
logger.info( logger.info(
f"STT 텍스트 수신 - meetingId: {meeting_id}, " f"STT 텍스트 수신 - meetingId: {meeting_id}, "
f"텍스트 길이: {len(text)}" f"텍스트 길이: {len(text)}, timestamp: {timestamp}"
) )
# Redis에 텍스트 축적 (슬라이딩 윈도우) try:
await self.redis_service.add_transcript_segment( # Redis에 텍스트 축적 (슬라이딩 윈도우)
meeting_id=meeting_id, await self.redis_service.add_transcript_segment(
text=text, meeting_id=meeting_id,
timestamp=timestamp text=text,
) timestamp=timestamp
)
logger.debug(f"Redis 저장 완료 - meetingId: {meeting_id}") logger.info(f"✅ Redis 저장 완료 - meetingId: {meeting_id}, timestamp: {timestamp}")
except Exception as redis_error:
logger.error(f"❌ Redis 저장 실패 - meetingId: {meeting_id}, 오류: {redis_error}", exc_info=True)
# MVP 개발: checkpoint 업데이트 제거 (InMemory 모드) # MVP 개발: checkpoint 업데이트 제거 (InMemory 모드)
# await partition_context.update_checkpoint(event) # await partition_context.update_checkpoint(event)

View File

@ -0,0 +1,27 @@
"""Redis 데이터 정리 스크립트"""
import asyncio
import sys
sys.path.append('/Users/jominseo/HGZero/ai-python')
from app.services.redis_service import RedisService
async def cleanup():
redis_service = RedisService()
try:
await redis_service.connect()
print("✅ Redis 연결 성공")
# test-meeting-001 데이터 정리
meeting_id = "test-meeting-001"
await redis_service.cleanup_meeting_data(meeting_id)
print(f"{meeting_id} 데이터 정리 완료")
except Exception as e:
print(f"❌ 오류 발생: {e}")
finally:
await redis_service.disconnect()
print("✅ Redis 연결 종료")
if __name__ == "__main__":
asyncio.run(cleanup())

File diff suppressed because it is too large Load Diff

View File

@ -4,7 +4,9 @@ from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from app.config import get_settings from app.config import get_settings
from app.api.v1 import router as api_v1_router from app.api.v1 import router as api_v1_router
from app.services.eventhub_service import start_eventhub_listener
import logging import logging
import asyncio
# 로깅 설정 # 로깅 설정
logging.basicConfig( logging.basicConfig(
@ -39,6 +41,14 @@ app.add_middleware(
app.include_router(api_v1_router, prefix="/api") app.include_router(api_v1_router, prefix="/api")
# Event Hub 리스너 백그라운드 태스크
@app.on_event("startup")
async def startup_event():
"""애플리케이션 시작 시 Event Hub 리스너 시작"""
logger.info("애플리케이션 시작 - Event Hub 리스너 백그라운드 실행")
asyncio.create_task(start_eventhub_listener())
@app.get("/health") @app.get("/health")
async def health_check(): async def health_check():
"""헬스 체크""" """헬스 체크"""

View File

@ -36,8 +36,8 @@ public class SuggestionService implements SuggestionUseCase {
// 회의별 실시간 스트림 관리 (회의 ID -> Sink) // 회의별 실시간 스트림 관리 (회의 ID -> Sink)
private final Map<String, Sinks.Many<RealtimeSuggestionsDto>> meetingSinks = new ConcurrentHashMap<>(); private final Map<String, Sinks.Many<RealtimeSuggestionsDto>> meetingSinks = new ConcurrentHashMap<>();
// 분석 임계값 설정 // 분석 임계값 설정 (MVP용 완화)
private static final int MIN_SEGMENTS_FOR_ANALYSIS = 10; // 10개 세그먼트 = 100-200자 private static final int MIN_SEGMENTS_FOR_ANALYSIS = 5; // 5개 세그먼트 = 50-100자 (MVP용 완화)
private static final long TEXT_RETENTION_MS = 5 * 60 * 1000; // 5분 private static final long TEXT_RETENTION_MS = 5 * 60 * 1000; // 5분
@Override @Override

View File

@ -43,33 +43,35 @@ public class ClaudeApiClient {
String systemPrompt = """ String systemPrompt = """
당신은 회의록 작성 전문 AI 어시스턴트입니다. 당신은 회의록 작성 전문 AI 어시스턴트입니다.
실시간 회의 텍스트를 분석하여 **중요한 제안사항만** 추출하세요. 실시간 회의 텍스트를 분석하여 **제안사항을 적극적으로** 추출하세요.
**추출 기준**: **추출 대상 (MVP용 - 넓은 기준)**:
- 회의 안건과 직접 관련된 내용 - 회의 안건 관련 내용
- 논의가 필요한 주제 - 논의 중인 주제 (확정되지 않아도 OK)
- 의견이나 제안
- 결정된 사항 - 결정된 사항
- 액션 아이템 - 액션 아이템
- 계획이나 일정 관련 언급
- 검토가 필요한 내용
**제외할 내용**: **제외할 내용** (최소화):
- 잡담, 농담, 인사말 - 명백한 잡담이나 농담
- 회의와 무관한 대화 - 회의 시작/종료 인사말
- 단순 확인이나 질의응답
**응답 형식**: JSON만 반환 (다른 설명 없이) **응답 형식**: JSON만 반환 (다른 설명 없이)
{ {
"suggestions": [ "suggestions": [
{ {
"content": "구체적인 제안 내용 (1-2문장으로 명확하게)", "content": "구체적인 제안 내용 (자연스러운 문장으로)",
"confidence": 0.9 "confidence": 0.7
} }
] ]
} }
**주의**: **주의**:
- 제안은 독립적이고 명확해야 - 확신이 없어도 제안사항으로 포함 (confidence 0.6 이상이면 OK)
- 회의 맥락에서 실제 중요한 내용만 포함 - 회의 내용에서 의미 있는 내용은 모두 제안사항으로 추출
- confidence는 0-1 사이 (확신 정도) - confidence는 0-1 사이 (MVP에서는 낮아도 괜찮음)
"""; """;
String userPrompt = String.format(""" String userPrompt = String.format("""

View File

@ -0,0 +1,322 @@
# AI 제안사항 SSE 연동 가이드
## 📋 개요
실시간 회의 중 AI가 생성한 제안사항을 Server-Sent Events(SSE)를 통해 프론트엔드로 전송하는 기능입니다.
## 🔗 API 정보
### Endpoint
```
GET http://localhost:8086/api/ai/suggestions/meetings/{meeting_id}/stream
```
### Parameters
- `meeting_id` (path): 회의 ID (예: `test-meeting-001`)
### Response Type
- **Content-Type**: `text/event-stream`
- **Transfer-Encoding**: chunked
- **Cache-Control**: no-cache
## 🎯 동작 방식
### 1. 데이터 흐름
```
STT Service → Event Hub → AI Service (Python)
Redis 저장
임계값 도달 (3개 세그먼트)
Claude API 분석
SSE로 프론트엔드 전송
```
### 2. 임계값 설정
- **최소 세그먼트**: 3개
- **예상 시간**: 약 15-30초 분량의 대화
- **텍스트 보관**: 최근 5분간 데이터
### 3. SSE 이벤트 종류
#### ✅ `ping` 이벤트 (Keep-alive)
```
event: ping
data: connected
```
- **목적**: SSE 연결 유지
- **주기**: 5초마다 전송
- **처리**: 프론트엔드에서 로그만 출력하고 무시
#### ✅ `ai-suggestion` 이벤트 (AI 제안사항)
```
event: ai-suggestion
id: 3
data: {"suggestions":[...]}
```
## 💻 프론트엔드 구현
### 참고 파일
```
/Users/jominseo/HGZero/test-audio/stt-test-wav.html
```
### 기본 구현 코드
```javascript
const meetingId = 'your-meeting-id';
const aiServiceUrl = 'http://localhost:8086';
let eventSource = null;
// SSE 연결
function connectAISuggestions() {
const sseUrl = `${aiServiceUrl}/api/ai/suggestions/meetings/${meetingId}/stream`;
eventSource = new EventSource(sseUrl);
// Keep-alive 핸들러 (로그만 출력)
eventSource.addEventListener('ping', (event) => {
console.log('Ping received:', event.data);
});
// AI 제안사항 핸들러
eventSource.addEventListener('ai-suggestion', (event) => {
try {
const data = JSON.parse(event.data);
displaySuggestions(data);
console.log('✅ AI 제안사항 수신:', data.suggestions.length + '개');
} catch (e) {
console.error('AI 제안 파싱 실패:', e);
}
});
// 연결 성공
eventSource.onopen = () => {
console.log('✅ AI 제안사항 SSE 연결 성공');
};
// 에러 핸들링
eventSource.onerror = (error) => {
const state = eventSource.readyState;
console.error('SSE Error:', error, 'State:', state);
// CLOSED 상태일 때만 재연결
if (state === EventSource.CLOSED) {
console.log('❌ AI 제안사항 SSE 연결 종료');
eventSource.close();
// 5초 후 재연결
setTimeout(() => {
console.log('AI SSE 재연결 시도...');
connectAISuggestions();
}, 5000);
}
};
}
// AI 제안사항 표시
function displaySuggestions(data) {
if (!data.suggestions || data.suggestions.length === 0) {
return;
}
data.suggestions.forEach(suggestion => {
// suggestion 구조:
// {
// id: "uuid",
// content: "제안 내용",
// timestamp: "HH:MM:SS",
// confidence: 0.85
// }
console.log(`[${suggestion.timestamp}] ${suggestion.content}`);
console.log(` 신뢰도: ${(suggestion.confidence * 100).toFixed(0)}%`);
// UI에 표시하는 로직 추가
// ...
});
}
// 연결 종료
function disconnectAISuggestions() {
if (eventSource) {
eventSource.close();
eventSource = null;
console.log('✅ AI SSE 연결 종료');
}
}
```
## 🚨 주요 이슈 및 해결방법
### 1. CORS 오류
**증상**
```
Access to resource has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present
```
**해결**
- ✅ 이미 백엔드에서 CORS 헤더 설정 완료
- Python AI Service는 `http://localhost:8888` origin 허용
### 2. SSE 연결이 즉시 끊어짐
**증상**
- `readyState: CLOSED`
- 계속 재연결 시도
**원인**
- EventSource가 `ping` 이벤트를 처리하지 못함
- Keep-alive 메시지가 없어서 브라우저가 연결 종료로 판단
**해결**
```javascript
// ping 이벤트 핸들러 반드시 추가
eventSource.addEventListener('ping', (event) => {
console.log('Ping:', event.data);
});
```
### 3. 데이터가 오지 않음
**원인**
- Redis에 텍스트가 충분히 쌓이지 않음 (3개 미만)
- STT 서비스가 텍스트를 Event Hub로 전송하지 않음
**확인 방법**
```bash
# 터미널에서 직접 테스트
curl -N http://localhost:8086/api/ai/suggestions/meetings/test-meeting-001/stream
```
**해결**
- 최소 15-30초 정도 음성 입력 필요
- STT Service와 Event Hub 연결 상태 확인
### 4. 브라우저 캐시 문제
**증상**
- 코드 수정 후에도 이전 동작 반복
**해결**
- **Hard Refresh**: `Ctrl+Shift+R` (Windows) / `Cmd+Shift+R` (Mac)
- 시크릿 모드 사용
- 개발자 도구 → Network → "Disable cache" 체크
## 📦 응답 데이터 구조
### AI 제안사항 응답
```typescript
interface SimpleSuggestion {
id: string; // UUID
content: string; // 제안 내용 (1-2문장)
timestamp: string; // "HH:MM:SS" 형식
confidence: number; // 0.0 ~ 1.0 (신뢰도)
}
interface RealtimeSuggestionsResponse {
suggestions: SimpleSuggestion[];
}
```
### 예시
```json
{
"suggestions": [
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"content": "OFDM 기술의 신제품 적용 가능성을 검토하고, 기술 사양 및 구현 방안에 대한 상세 분석 보고서를 작성하여 다음 회의 전까지 공유해야 합니다.",
"timestamp": "17:01:25",
"confidence": 0.88
},
{
"id": "73ba9f1e-7793-46a4-bd6a-8dde9db36482",
"content": "AICC 구축 협의를 위한 구체적인 일정을 수립하고, 관련 부서 담당자들과 협의 미팅을 조율해야 합니다.",
"timestamp": "17:01:25",
"confidence": 0.85
}
]
}
```
## 🔧 테스트 방법
### 1. 로컬 환경 테스트
```bash
# AI Service 실행 확인
curl http://localhost:8086/health
# SSE 연결 테스트 (3초 후 자동 종료)
timeout 30 curl -N http://localhost:8086/api/ai/suggestions/meetings/test-meeting-001/stream
```
### 2. 브라우저 테스트
1. `http://localhost:8888/stt-test-wav.html` 접속
2. 개발자 도구(F12) 열기
3. Network 탭에서 `stream` 요청 확인
4. Console 탭에서 "Ping received" 로그 확인
### 3. 실제 음성 테스트
1. "녹음 시작" 버튼 클릭
2. 15-30초 정도 음성 입력
3. AI 제안사항 표시 확인
## ⚙️ 환경 설정
### Backend (Python AI Service)
- **Port**: 8086
- **Endpoint**: `/api/ai/suggestions/meetings/{meeting_id}/stream`
- **CORS**: `http://localhost:8888` 허용
### 임계값 설정
```python
# app/config.py
min_segments_for_analysis: int = 3 # 3개 세그먼트
text_retention_seconds: int = 300 # 5분
```
## 📝 체크리스트
프론트엔드 구현 시 확인 사항:
- [ ] `EventSource` 생성 및 연결
- [ ] `ping` 이벤트 핸들러 추가 (필수!)
- [ ] `ai-suggestion` 이벤트 핸들러 추가
- [ ] 에러 핸들링 및 재연결 로직
- [ ] 연결 종료 시 리소스 정리
- [ ] UI에 제안사항 표시 로직
- [ ] 브라우저 콘솔에서 ping 로그 확인
- [ ] Hard Refresh로 캐시 제거
## 🐛 디버깅 팁
### Console 로그로 상태 확인
```javascript
// 정상 동작 시 5초마다 출력
console.log('Ping received:', 'connected');
console.log('Ping received:', 'alive-3');
```
### Network 탭에서 확인
- Status: `200 OK`
- Type: `eventsource`
- Transfer-Encoding: `chunked`
### 문제 발생 시 확인
1. AI Service 실행 여부: `curl http://localhost:8086/health`
2. CORS 헤더: Network 탭 → Headers → Response Headers
3. 이벤트 수신: EventStream 탭에서 실시간 데이터 확인
## 📞 문의
문제 발생 시:
1. 브라우저 Console 로그 확인
2. Network 탭의 요청/응답 헤더 확인
3. 백엔드 로그 확인: `tail -f /Users/jominseo/HGZero/ai-python/logs/ai-service.log`
---
**작성일**: 2025-10-29
**작성자**: Backend Team (동욱)
**참고 파일**: `/Users/jominseo/HGZero/test-audio/stt-test-wav.html`

View File

@ -472,13 +472,21 @@
eventSource = new EventSource(sseUrl); eventSource = new EventSource(sseUrl);
// Ping 이벤트 핸들러 (keep-alive)
eventSource.addEventListener('ping', (event) => {
console.log('Ping received:', event.data);
// ping은 로그에 표시하지 않음 (연결 유지용)
});
// AI 제안사항 이벤트 핸들러
eventSource.addEventListener('ai-suggestion', (event) => { eventSource.addEventListener('ai-suggestion', (event) => {
try { try {
const data = JSON.parse(event.data); const data = JSON.parse(event.data);
displaySuggestions(data); displaySuggestions(data);
addLog('✅ AI 제안사항 수신', 'info'); addLog('✅ AI 제안사항 수신 (' + data.suggestions.length + '개)', 'info');
} catch (e) { } catch (e) {
addLog('AI 제안 파싱 실패: ' + e.message, 'error'); addLog('AI 제안 파싱 실패: ' + e.message, 'error');
console.error('Parse error:', e, 'Data:', event.data);
} }
}); });
@ -496,15 +504,19 @@
default: stateText = 'UNKNOWN'; default: stateText = 'UNKNOWN';
} }
addLog(`❌ AI 제안사항 SSE 오류 (State: ${stateText})`, 'error'); console.error('SSE Error:', error, 'State:', stateText);
// 연결이 닫혔을 때만 재연결 시도 // CLOSED 상태일 때만 에러로 표시하고 재연결
if (state === EventSource.CLOSED) { if (state === EventSource.CLOSED) {
addLog(`❌ AI 제안사항 SSE 연결 종료`, 'error');
eventSource.close(); eventSource.close();
setTimeout(() => { setTimeout(() => {
addLog('AI SSE 재연결 시도...', 'info'); addLog('AI SSE 재연결 시도...', 'info');
connectAISuggestions(); connectAISuggestions();
}, 5000); }, 5000);
} else if (state === EventSource.CONNECTING) {
// 연결 중일 때는 에러 로그를 표시하지 않음
console.log('SSE reconnecting...');
} }
}; };
} }