From c664116cd2f5b1f8f6146a0bed97aa539f65528f Mon Sep 17 00:00:00 2001 From: Minseo-Jo Date: Wed, 29 Oct 2025 17:20:10 +0900 Subject: [PATCH] =?UTF-8?q?AI=20=EC=A0=9C=EC=95=88=EC=82=AC=ED=95=AD=20SSE?= =?UTF-8?q?=20=EC=8A=A4=ED=8A=B8=EB=A6=AC=EB=B0=8D=20=EA=B8=B0=EB=8A=A5=20?= =?UTF-8?q?=EA=B5=AC=ED=98=84=20=EB=B0=8F=20CORS=20=EB=AC=B8=EC=A0=9C=20?= =?UTF-8?q?=ED=95=B4=EA=B2=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 주요 변경사항: - Event Hub 리스너를 Python AI Service에 통합하여 STT 텍스트 실시간 수신 - LocalDateTime 배열 형식을 Unix timestamp로 변환하는 로직 추가 - SSE 응답에 CORS 헤더 명시적 추가 (localhost:8888 허용) - SSE Keep-alive를 위한 ping 이벤트 추가 (5초 주기) - Redis 데이터 정리 스크립트 추가 - 분석 임계값을 MVP 수준으로 조정 (3개 세그먼트 = 약 15-30초) - 프론트엔드 SSE 연동 가이드 문서 작성 - 프론트엔드에 ping 이벤트 핸들러 추가 및 에러 핸들링 개선 기술적 개선사항: - EventSourceResponse에 Access-Control-Allow-Origin 헤더 추가 - timestamp 변환 로직으로 Java-Python 호환성 해결 - Redis 저장 오류 로깅 강화 - SSE generator에 주기적 heartbeat 전송으로 연결 유지 문서: - develop/dev/ai-frontend-integration-guide.md: 프론트엔드 개발자를 위한 상세 연동 가이드 🤖 Generated with Claude Code Co-Authored-By: Claude --- ai-python/app/api/v1/suggestions.py | 29 +- ai-python/app/config.py | 4 +- ai-python/app/services/eventhub_service.py | 44 ++- ai-python/cleanup_redis.py | 27 ++ ai-python/main.py | 10 + develop/dev/ai-frontend-integration-guide.md | 322 +++++++++++++++++++ test-audio/stt-test-wav.html | 18 +- 7 files changed, 435 insertions(+), 19 deletions(-) create mode 100644 ai-python/cleanup_redis.py create mode 100644 develop/dev/ai-frontend-integration-guide.md diff --git a/ai-python/app/api/v1/suggestions.py b/ai-python/app/api/v1/suggestions.py index 118cc88..5b27f06 100644 --- a/ai-python/app/api/v1/suggestions.py +++ b/ai-python/app/api/v1/suggestions.py @@ -1,5 +1,6 @@ """AI 제안사항 SSE 엔드포인트""" -from fastapi import APIRouter +from fastapi import APIRouter, Response +from fastapi.responses import StreamingResponse from sse_starlette.sse import EventSourceResponse import logging import asyncio @@ -94,9 +95,16 @@ async def stream_ai_suggestions(meeting_id: str): previous_count = 0 + # Keep-alive를 위한 주석 전송 + yield { + "event": "ping", + "data": "connected" + } + while True: # 현재 세그먼트 개수 확인 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 @@ -106,6 +114,8 @@ async def stream_ai_suggestions(meeting_id: str): accumulated_text = await redis_service.get_accumulated_text(meeting_id) if accumulated_text: + logger.info(f"텍스트 누적 완료 - meetingId: {meeting_id}, 길이: {len(accumulated_text)}") + # Claude API로 분석 suggestions = await claude_service.analyze_suggestions(accumulated_text) @@ -124,6 +134,12 @@ async def stream_ai_suggestions(meeting_id: str): previous_count = current_count + # Keep-alive 주석 전송 (SSE 연결 유지) + yield { + "event": "ping", + "data": f"alive-{current_count}" + } + # 5초마다 체크 await asyncio.sleep(5) @@ -138,7 +154,16 @@ async def stream_ai_suggestions(meeting_id: str): finally: 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") diff --git a/ai-python/app/config.py b/ai-python/app/config.py index fd74ade..1346ea6 100644 --- a/ai-python/app/config.py +++ b/ai-python/app/config.py @@ -42,8 +42,8 @@ class Settings(BaseSettings): # 로깅 log_level: str = "INFO" - # 분석 임계값 - min_segments_for_analysis: int = 10 + # 분석 임계값 (MVP 수준) + min_segments_for_analysis: int = 3 # 3개 세그먼트 = 약 15-30초 분량의 대화 text_retention_seconds: int = 300 # 5분 class Config: diff --git a/ai-python/app/services/eventhub_service.py b/ai-python/app/services/eventhub_service.py index 7e63350..6cea95f 100644 --- a/ai-python/app/services/eventhub_service.py +++ b/ai-python/app/services/eventhub_service.py @@ -63,28 +63,48 @@ class EventHubService: } """ 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") meeting_id = event_data.get("meetingId") 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( f"STT 텍스트 수신 - meetingId: {meeting_id}, " - f"텍스트 길이: {len(text)}" + f"텍스트 길이: {len(text)}, timestamp: {timestamp}" ) - # Redis에 텍스트 축적 (슬라이딩 윈도우) - await self.redis_service.add_transcript_segment( - meeting_id=meeting_id, - text=text, - timestamp=timestamp - ) - - logger.debug(f"Redis 저장 완료 - meetingId: {meeting_id}") + try: + # Redis에 텍스트 축적 (슬라이딩 윈도우) + await self.redis_service.add_transcript_segment( + meeting_id=meeting_id, + text=text, + timestamp=timestamp + ) + 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 모드) # await partition_context.update_checkpoint(event) diff --git a/ai-python/cleanup_redis.py b/ai-python/cleanup_redis.py new file mode 100644 index 0000000..0ec1fb4 --- /dev/null +++ b/ai-python/cleanup_redis.py @@ -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()) diff --git a/ai-python/main.py b/ai-python/main.py index c1b2e77..5e6d0e9 100644 --- a/ai-python/main.py +++ b/ai-python/main.py @@ -4,7 +4,9 @@ from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from app.config import get_settings from app.api.v1 import router as api_v1_router +from app.services.eventhub_service import start_eventhub_listener import logging +import asyncio # 로깅 설정 logging.basicConfig( @@ -39,6 +41,14 @@ app.add_middleware( 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") async def health_check(): """헬스 체크""" diff --git a/develop/dev/ai-frontend-integration-guide.md b/develop/dev/ai-frontend-integration-guide.md new file mode 100644 index 0000000..7f106b1 --- /dev/null +++ b/develop/dev/ai-frontend-integration-guide.md @@ -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` diff --git a/test-audio/stt-test-wav.html b/test-audio/stt-test-wav.html index 23fb242..d3e0fc9 100644 --- a/test-audio/stt-test-wav.html +++ b/test-audio/stt-test-wav.html @@ -472,13 +472,21 @@ eventSource = new EventSource(sseUrl); + // Ping 이벤트 핸들러 (keep-alive) + eventSource.addEventListener('ping', (event) => { + console.log('Ping received:', event.data); + // ping은 로그에 표시하지 않음 (연결 유지용) + }); + + // AI 제안사항 이벤트 핸들러 eventSource.addEventListener('ai-suggestion', (event) => { try { const data = JSON.parse(event.data); displaySuggestions(data); - addLog('✅ AI 제안사항 수신', 'info'); + addLog('✅ AI 제안사항 수신 (' + data.suggestions.length + '개)', 'info'); } catch (e) { addLog('AI 제안 파싱 실패: ' + e.message, 'error'); + console.error('Parse error:', e, 'Data:', event.data); } }); @@ -496,15 +504,19 @@ default: stateText = 'UNKNOWN'; } - addLog(`❌ AI 제안사항 SSE 오류 (State: ${stateText})`, 'error'); + console.error('SSE Error:', error, 'State:', stateText); - // 연결이 닫혔을 때만 재연결 시도 + // CLOSED 상태일 때만 에러로 표시하고 재연결 if (state === EventSource.CLOSED) { + addLog(`❌ AI 제안사항 SSE 연결 종료`, 'error'); eventSource.close(); setTimeout(() => { addLog('AI SSE 재연결 시도...', 'info'); connectAISuggestions(); }, 5000); + } else if (state === EventSource.CONNECTING) { + // 연결 중일 때는 에러 로그를 표시하지 않음 + console.log('SSE reconnecting...'); } }; }