AI 제안사항 SSE 스트리밍 기능 구현 및 CORS 문제 해결

주요 변경사항:
- 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 <noreply@anthropic.com>
This commit is contained in:
Minseo-Jo
2025-10-29 17:20:10 +09:00
parent 13eb213211
commit c664116cd2
7 changed files with 435 additions and 19 deletions
+27 -2
View File
@@ -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")
+2 -2
View File
@@ -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:
+32 -12
View File
@@ -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)
+27
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())
+10
View File
@@ -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():
"""헬스 체크"""